BITS_Python
BITS_Python

Reputation: 381

setattribute in javascript

This is my code to dynamically set the onclick attribute to links, but without me clicking the links itself, the alert is triggered.

window.onload = function() {
    var links = document.getElementsByTagName("a");
    for(var i=0;i<links.length;i++) {
        elm = links[i];
        elm.setAttribute("onclick", alert("you clicked a lik"));
    }
}

Upvotes: 0

Views: 5699

Answers (2)

gion_13
gion_13

Reputation: 41533

change the corresponding line to:

elm.setAttribute("onclick", function() { alert("you clicked a link");});

If you pass as argument a function call (such as alert('msg')), the function is executed imediatley and the actual passed argument is the function's return value. All you have to do is wrap your eventHandler code into an anonymous function.
Also, you can declare a function that handles your event and send it's name as argument :

function handleClick() { alert("you clicked a link");}
elm.setAttribute("onclick", handleClick);

P.S. : I recommend using the addEventListener functionality instead of plain old onEvent inline attributes :

elm.addEventListener('click', function() { alert("you clicked a link");}, false);

Upvotes: 1

Jose Faeti
Jose Faeti

Reputation: 12302

Try to put the alert statement into an anonimous function

window.onload = function()
{
    var links = document.getElementsByTagName("a");
    for(var i=0; i < links.length; i++)
    {
        links[i].setAttribute("onclick", function () {
            alert("you clicked a link");
        });
    }
}

Upvotes: 0

Related Questions