Reputation: 913
I click <a>
, it shows its id, but if I click the <a>
again, it shows alert()
twice, if I click it again, it shows alert()
3 times and it goes like that. How can I prevent repeating itself?
<a id="5" class="accRoom" onclick="dynamicLink()">5</a>
<a id="6" class="accRoom" onclick="dynamicLink()">6</a>
dynamicLink()
function in a .js folder
function dynamicLink() {
var x = document.getElementsByClassName("accRoom");
for (var i = 0; i < x.length; i++) {
x[i].addEventListener("click", function() {
alert(this.id);
}, false);
}
}
Upvotes: 2
Views: 3743
Reputation: 232
Don't use anonymous function
function awesomeAlert(){
alert(this.id);
}
function dynamicLink() {
var x = document.getElementsByClassName("accRoom");
for (var i = 0; i < x.length; i++) {
x[i].removeEventListener("click", awesomeAlert);
x[i].addEventListener("click", awesomeAlert, false);
}
}
Maybe you don't care but there are a lot of better ways to set listeners, and in the code above there is room to improve and that is another story.
Have fun
Upvotes: 1
Reputation: 104
That happen because everytime you click your script will attach the click event to all the elements with class accRoom
, you've just to attach the click one time :
var x = document.getElementsByClassName("accRoom");
for (var i = 0; i < x.length; i++) {
x[i].addEventListener("click", function() {
alert(this.id);
}, false);
}
Then the html should looks like :
<a id="5" class="accRoom">5</a>
<a id="6" class="accRoom">6</a>
Hope will help you.
var x = document.getElementsByClassName("accRoom");
function eventFunction() {
alert(this.id);
}
for (var i = 0; i < x.length; i++) {
x[i].removeEventListener('click',eventFunction,false);
x[i].addEventListener("click",eventFunction, false);
}
<a id="5" class="accRoom">5</a>
<a id="6" class="accRoom">6</a>
Or you could just send the clicked element as object this
to the function onclick :
//This link was added dynamically
document.body.innerHTML += '<a id="7" class="accRoom" onclick="dynamicLink(this)">7</a>';
function dynamicLink(_this) {
alert(_this.id);
}
<a id="5" class="accRoom" onclick="dynamicLink(this)">5</a>
<a id="6" class="accRoom" onclick="dynamicLink(this)">6</a>
Upvotes: 3
Reputation: 71
The function dynamicLink
is attaching an anonymous function (that does an alert) to the click event of every element with CSS class 'accRoom'.
The problem is that it is also attached to the click event. So each time you click it will attach another function to the click event, and so...
you can avoid that behaviour by removing the onclick
attribute on 'accRoom' links and calling dynamicLink
after the dom is loaded.
HTML:
<a id="5" class="accRoom">5</a>
<a id="6" class="accRoom">6</a>
JS:
var x = document.getElementsByClassName("accRoom");
for (var i = 0; i < x.length; i++) {
x[i].addEventListener("click", function() {
alert(this.id);
}, false);
}
document.addEventListener("DOMContentLoaded", addDynamicLinks)
Hope it helps
Upvotes: 1