0

I have several buttons in my html document like this one:

<button id="demo" type="button" class="btn btn-primary btn-sm mapButton">Map</button>

Now I used the class mapButton to add an eventListener for all of these buttons.

var allMapButtons = document.getElementsByClassName("mapButton");

for (var i = 0; i < allMapButtons.length; i++) {
    allMapButtons[i].addEventListener('mouseover', function() { 
    alert("button mouseover");//works
    allMapButtons[i].innerHTML = "123"; //doesn't work
    document.getElementById("demo").innerHTML = "sometext"; //doesnt' work
});
}

I want to change the text of the button and something else when the event happens. But only the alert(...) statement in the above code works. Even if I delete the alert(...) statement, the innerHTML statements won't be work. How can I change the text of the button with my approach?

d4rty
  • 3,970
  • 5
  • 34
  • 73
  • You can use `this.innerHTML` inside the function to access the element on which `mouseover` event is triggered. – AKS Apr 01 '16 at 10:20
  • https://jsfiddle.net/rayon_1990/7wyoaf8f/ – Rayon Apr 01 '16 at 10:23
  • https://jsfiddle.net/TomKarachristos/L6couu2o/ . You can see here what's the problem, when you call the function inside the event the i value is allMapButtons.length+1. Look for JavaScript closure term. – Thomas Karachristos Apr 01 '16 at 10:25

0 Answers0