Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding click event via addEventListener to confirm navigation from a hyperlink

I am writing some JavaScript that what I essentially want to do is confirm when a user clicks a link that they do actually want to click it.

My code currently looks like this:

var Anchors = document.getElementsByTagName("a");

for (var i = 0; i < Anchors.length ; i++)
{
    Anchors[i].addEventListener("click", function () { return confirm('Are you sure?'); }, false);
}

This code displays the confirm box as I would expect to see it, but then navigates to the link regardless of the button pressed in the confirm box.

I believe the problem is related to my usage of the addEventListener (or a limitation of the implementation of it) because if I add manually write the following in a HTML file, the behaviour is exactly what I would expect:

<a href="http://www.google.com" onclick="return confirm('Are you sure?')">Google</a><br />
like image 883
Andy Avatar asked May 18 '11 08:05

Andy


People also ask

Is it better to use addEventListener or onclick?

addEventListener can add multiple events to a particular element. onclick can add only a single event to an element. It is basically a property, so gets overwritten.

How do I add an event listener to all links?

addEventListener('click', callback, false); else document. attachEvent('onclick', callback); The pros of this solution is that when you dynamically add another anchor, you don't need to specifically bind an event to it, so all links will always fire this, even if they were added after these lines were executed.

What is the purpose of the addEventListener () method?

The addEventListener() method allows you to add event listeners on any HTML DOM object such as HTML elements, the HTML document, the window object, or other objects that support events, like the xmlHttpRequest object.


2 Answers

I changed your onclick function to include a call to event.preventDefault() and it seemed to get it working:

var Anchors = document.getElementsByTagName("a");

for (var i = 0; i < Anchors.length ; i++) {
    Anchors[i].addEventListener("click", 
        function (event) {
            event.preventDefault();
            if (confirm('Are you sure?')) {
                window.location = this.href;
            }
        }, 
        false);
}

(See http://jsfiddle.net/ianoxley/vUP3G/1/)

like image 90
Ian Oxley Avatar answered Sep 20 '22 15:09

Ian Oxley


You have to prevent the execution of the default event handler.

See How to use Javascript's addEventListener() to override an HTML Form's default submit() behavior

--EDIT--

We'll, I've seen you've answered yourself while I was editing the answer

like image 42
Toni Toni Chopper Avatar answered Sep 19 '22 15:09

Toni Toni Chopper