1

Here is my code:

    function Alert()
{   
alert("Please click on OK to continue.")
}
window.onload = function()

    {       
    var anchors = document.getElementsByTagName("a");
    for (var i = 0; i < anchors.length; i++) {
        anchors[i].onclick = function() {return(false);};
    }
};

the link is coded at this:

<a href="main.html" onclick="Alert()"> Link to Main Page</a>

When I put this to test, the link does not work (as expected), but I don't get the alert box that's supposed to say "Please click on OK to continue." when the link is clicked. Can someone give me advice on how to fix this? Ultimately, once the page loads and the the link is clicked, it should show and alert that says "Please click on OK to continue." and nothing should happen. I know how to do this by changing the "href" attribute, but I need to know how to do it without changing that part.

0

3 Answers 3

2

You don't get the alert because your code changes all the "click" handlers, removing the ones coded in HTML. There's only one "onclick" property on the DOM nodes involved, so as soon as your script runs the handler that calls "Alert()" is replaced by the one that just returns false.

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

Comments

1

You can do it really easily with JQuery:

$('a').on('click',function(e){
    e.preventDefault();
    alert('your alert message');
});

you can test it in this fiddle: http://jsfiddle.net/kvCwW/

Comments

0

You need to add e.preventDefault() to your click handler:

anchors[i].addEventListener("click", function(e) {
    e.preventDefault();
    return false;
}, false);

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.