0

I'm working on an assignment where I have to create a link that is set up to take the user to a new webpage, but the instructions tell me to use javascript so that when the user clicks the link and alert window pops up that says "Stop That" and cancels the action of the link. My current javascript displays the alert message, but the link still works if the user clicks "OK." Anyone know how to keep the link from working? I added my javascript and my html for the link below:

JS:

<script type="text/javascript">
    function stop_link(node)
    {
        return alert("Stop That!");
    }
</script>

HTML Link:

<a href="index.html" onclick="return stop_link(this);">Do Not Click Here!</a>
  • I apologize if there is already a question that has a solution for my problem. I searched, but couldn't find anything that worked. –  Mar 05 '14 at 16:46
  • http://stackoverflow.com/questions/10219073/html-how-to-prevent-the-browser-from-opening-the-link-specified-in-href – Linek Mar 05 '14 at 16:56

1 Answers1

4

You should return false from your event handler in order to stop event propagation.

alert() does not return false, in fact it does not return anything, which means what it returns is implicitly undefined and undefined !== false

function stop_link(node) {
    alert("Stop That!");
    return false;
}
techfoobar
  • 65,616
  • 14
  • 114
  • 135
  • It shouldn't if you are using the above code to explicitly return false. – techfoobar Mar 05 '14 at 16:51
  • I think the problem is using `return stop_link(this);` in the in-line handler, which in essence returns a new function that does its thing, but does not stop the default behaviour from happening. – Andrei Nemes Mar 05 '14 at 16:53
  • Oh wait. I'm sorry. I left "return" before the alert(); even after I added "return false;" below it. Once I removed the first return, it fixed my problem. Thanks! –  Mar 05 '14 at 16:53
  • 2
    @AndreiNemes - `return stop_link(this);` does not return a new function. It returns what `stop_link(this)` returns - which is undefined as per OP's original code. – techfoobar Mar 05 '14 at 16:55