alexunder
alexunder

Reputation: 2155

understanding event handlers

As an exercise, I'm trying to add an event listener to an ebay.com element.

Expected result: show an alert and stop the web page from going to the next URL.

What happens: the alert is shown but the next URL is shown anyway.

I found something interesting on the product pages where I'm testing out preventDefault, stopPropagtion and stopImmediatePropagation.

No matter which combinations I use, nothing seem to work.

The basic code is:

$('#binBtn_btn').click(function(evt){
    alert('hi');
    evt.stopPropagation(); //or any other option.
});

The thing is that I get the alert, but it still goes to the next page, as if I never stopped the propagation.

I read a lot of articles about event handling, but I couldn't find the answer. Your help is much appreciated.

Upvotes: 2

Views: 106

Answers (2)

Dave Salomon
Dave Salomon

Reputation: 3297

My best guess it that the Button has its own click handler, and it's firing before yours.

$('#binBtn_btn').data("events") shows us that there is indeed a click event. Remove that using off.

$('#binBtn_btn').off('click');

Clicking the button now will still cause the form the submit, as all we're doing is browsing to a page. The button is actually just an a tag.

$('#binBtn_btn').click(function(e){
    alert('Gotcha!');
    e.preventDefault();
});

Let's see what happens if we remove their handler, add ours, and then re-add their one...

var existing = $('#binBtn_btn').data('events').click[0];
$('#binBtn_btn').off('click');
$('#binBtn_btn').click(function(e){ alert('foo'); e.stopImmediatePropagation(); return false; });
$('#binBtn_btn').data('events').click.push(existing);

Same, but just looking at the function for the click handler (rather than tweaking the events.click array directly...)

var existing = $('#binBtn_btn').data('events').click[0].handler;
$('#binBtn_btn').off('click');
$('#binBtn_btn').click(function(e){ alert('foo'); e.stopImmediatePropagation(); e.preventDefault(); });
$('#binBtn_btn').click(existing);

As expected, what is now the second handler -- their handler -- doesn't first. (I've added a return false; rather than e.preventDefault();, just to demonstrate different ways of doing things!)

You can check out what they're doing by placing a breakpoint and viewing the existing var above. You'll see that at the end of their function, they do indeed call e.preventDefault();.

Hope this helps.

Upvotes: 1

Syed Muhammad Zeeshan
Syed Muhammad Zeeshan

Reputation: 1045

try using evt.preventDefault() like this:

$('#binBtn_btn').click(function(evt){ 

    evt.preventDefault();
    alert('hi');  

});

Then it will not go to the next page.

Upvotes: 1

Related Questions