0

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"));
    }
}

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Have to be careful clicking those liks, catch them at the wrong angle you'll get a right wetting.
yeah, funny. that's what copy-paste does.
0

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");
        });
    }
}

Comments

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.