addEventListener and arguments

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

addEventListener and arguments

Post by social_experiment »

I've started working on adding event listeners and ran into a problem. How do you pass arguments to the function you will use as an event listener?

My example is that i want certain elements to display when i click on a link. My hidden elements will then have id's one through four. I have a function (say displayHidden() which accepts the element id as an argument.

Code: Select all

 // makes the hidden element display
 function displayHidden(id)
 {
      var theElement = document.getElementById(id);
      var elementStyle = theElement.style;

      elementStyle.height = 30 + 'px';
      elementStyle.display = 'block';
}
Now the code i use to add my event listener looks like this

Code: Select all

     var theLink = document.getElementById('link');
     theLink.addEventListener("mouseover", displayHidden, false);
This works fine, if i modify displayHidden() to not accept an argument. Is there a way to add an event listener AND pass an argument to the event listener function?
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: addEventListener and arguments

Post by Weirdan »

Code: Select all

<span class="hideLink" data-elementToHide="hideMe1">Click to hide</span><div id="hideMe1">jkfdgkhjdgfjkhdfghjkoiwe</div>
<span class="hideLink" data-elementToHide="hideMe2">Click to hide</span><div id="hideMe2">jkfdgkhjdgfjkhdfghjkoiwe</div>
<script>
<![CDATA[
(function(d) {
    var elts = d.getElementsByClassName("hideLink");
    for (var i = 0; i < elts.length; i++) {
        elts[i].addEventListener("click", hide, false);
    }
    function hide(e) {
        var id = e.target.getAttribute("data-elementToHide");
        d.getElementById(id).style.display = "none";
    }
})(document);
]]>
</script>
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: addEventListener and arguments

Post by pickle »

~Weirdan - that solution will only work with HTML5 aware browsers, and cause errors in those that aren't. Perhaps a better attribute would be "rel"?

Looking around, it appears there is no way to pass an argument to the function, because it is a reference to the function, not a call of the function. The only way around this is to wrap the function call inside another, anonymous function. I've made a JSFiddle as an example: http://jsfiddle.net/Q26xd/1/
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: addEventListener and arguments

Post by Weirdan »

pickle wrote:~Weirdan - that solution will only work with HTML5 aware browsers, and cause errors in those that aren't.
Why would it? It's simply unknown attribute - the worst thing that could happen it won't be available through DOM. Browsers are not validators.
http://caniuse.com/#dataset - it appears all browsers (back to IE5.5) have no problems with data-* attributes.
Perhaps a better attribute would be "rel"?
Any attribute would serve. data-* attributes are just forward-compatible way to express custom data attached to html element.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: addEventListener and arguments

Post by pickle »

I was wrong. When I wrote that I thought browsers that didn't support HTML5 would throw a JS error on this line:

Code: Select all

var id = e.target.getAttribute("data-elementToHide");
But obviously that's not true.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: addEventListener and arguments

Post by social_experiment »

Thanks for both the replies Weirdan & pickle. This is the code i am using that works

Code: Select all

document.getElementById('Link').addEventListener('mouseover', function(e) { displayHidden('hidden'); }, false);
document.getElementById('Link').addEventListener('mouseout', function(e) { hideDisplay('hidden');}, false);
I've only tested it using Firefox at the moment. From examples i've seen Internet Explorer requires a different method when adding event listeners.
Edit
I've added the following to the script to add event listeners for internet explorer. This is the complete function i use to add event listeners for both IE and FF. The IE ones doesn't seem to work but i don't receive any errors from the browser to indicate a problem.

Code: Select all

function init()
{
	var linkId = document.getElementById('Link');	
	
	if (typeof linkId.addEventListener != "undefined") {
		document.getElementById('Link').addEventListener('mouseover', function(e){ displayHidden('hidden');}, false);
		document.getElementById('Link').addEventListener('mouseout', function(e){ hideDisplay('hidden');}, false);
	}
	else if (typeof linkId.attachEvent != "undefined") {
                                // add 'on' the events.
		linkId.attachEvent('onmouseover', function(e){ displayHidden('hidden');});
		linkId.attachEvent('onmouseout', function(e){ hideDisplay('hidden');});
	}
}
Edit
Adding 'on' to the events when attaching them solves the problem.
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
Post Reply