Jacob
Jacob

Reputation: 1459

How to pass ID to function after event listener click

Im pretty new to HTML5/Javascript/CSS3 and im confused on exactly how to pass the id of my event listener to the new function. I'm building a video player and this is the volume up and down part, and I would rather be able to use one function for both volume up and volume down using if statements, which would check the id.

Here is what im working with:

 volume_up = document.getElementById('volume_up'); //get the volume_up button
 volume_up.addEventListener('click', volumeUp, false); //call function "volumeUp" on click

Here is the "volumeUp" function:

function volumeUp(click_button){
alert(click_button.id); // i want to be able to get the id here
myMovie.volume = myMovie.volume - 0.1;
}

If i was able to get the ID, i could do vol up and vol down in this one function instead of 2 via if statements.

I have tried doing this:

   volume_up.addEventListener('click', volumeUp(volume_up), false);

and

    volume_up.addEventListener('click', volumeUp(volume_up.id), false);

with no luck. I have the volume up button linked up, and whenever i press it, the volume does change, and the alert does popup, but it says undefined.

Any help would be appreciated. Thanks :)

Upvotes: 1

Views: 4257

Answers (2)

SeanCannon
SeanCannon

Reputation: 77956

document.getElementById('volume_up').addEventListener('click', _volume, false);
document.getElementById('volume_down').addEventListener('click', _volume, false);

function _volume(event){
    if(this.id == 'volume_up') {
        myMovie.volume += 0.1;
    } else {
        myMovie.volume -= 0.1;
    }
}

This is just an example. You'll want to use some defensive logic to check for IE and use attachEvent instead when applicable.

The reason these didn't work...

volume_up.addEventListener('click', volumeUp(volume_up), false);
volume_up.addEventListener('click', volumeUp(volume_up.id), false);

...is because you're invoking the function and passing the result of volumeUp as the callback, which would not be a typeof == 'function'

Upvotes: 3

Andre Loker
Andre Loker

Reputation: 8408

In the event handler "this" is bound to the element that fired the event, so you can just use "this.id".

Check out this example: http://jsfiddle.net/vyGdJ/

Upvotes: 2

Related Questions