1

I'm creating buttons out of "tags" taken from my database. I'd like to add mouse event listeners to each button. However, the listener only seems to work on the last created button. Any ideas? Thanks.

var tagsContainer = document.getElementById('tags');
var tagarray = placetags.split(" ");
for (var tagcounter = 0; tagcounter < tagarray.length; tagcounter++){
  var tag = document.createElement('input');
  tag.type = 'button';
  tag.value = tagarray[tagcounter];
  tag.id = 'tagbutton';
  tagsContainer.appendChild(tag);
  tag.addEventListener('mouseover' , function(){
    tag.style.color = 'white';
  });
  tag.addEventListener('mouseout' , function(){
    tag.style.color = 'orange';
  });
}
5
  • Something like this? jsfiddle.net/mjqWL/3 Commented Dec 8, 2012 at 2:56
  • thanks. a simple "this.style.color" instead of "tag.style.color" of course! Commented Dec 8, 2012 at 3:08
  • Sorry, I didn't even realize that I changed that. Adam's answer explains why. Commented Dec 8, 2012 at 3:10
  • @Blender - a badge for your troubles :) Commented Dec 8, 2012 at 3:24
  • Note that you can use a single event handler for all of your buttons. Commented Dec 8, 2012 at 3:36

1 Answer 1

1

You need to change your handlers from this

tag.addEventListener('mouseover' , function(){
    tag.style.color = 'white';
});

to this

tag.addEventListener('mouseover' , function(){
    this.style.color = 'white';
});

Since with your original code, your handlers are closing over the tag variable, and so tag ends up referring to the last button created.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm still seeing multiple buttons, however. Right now I'm just looking to do mouseover / mouseout events.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.