Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why jQuery cannot trigger native click on an anchor tag?

Recently I found jQuery cannot trigger the native click event on an anchor tag when I'm clicking on other elements, the example below won't work:

html

<a class="js-a1" href="new.html" target="_blank">this is a link</a>
<a class="js-a2" href="another.html" target="_blank">this is another link</a>

javascript

$('.js-a1').click(function () {
  $('.js-a2').click();
  return false;
});

And here is the jsfiddle - 1. Click on the first link won't trigger native click on the second one.

After some searches, I found a solution and an explanation.

Solution

Use the native DOM element.

$('.js-a1').click(function () {
  $('.js-a2').get(0).click();
  return false;
});

And here is the jsfiddle - 2.

Explanation

I found a post on Learn jQuery: Triggering Event Handlers. It told me:

The .trigger() function cannot be used to mimic native browser events, such as clicking on a file input box or an anchor tag. This is because, there is no event handler attached using jQuery's event system that corresponds to these events.

Question

So here comes my question:

How to understand 'there is no event handler attached using jQuery's event system that corresponds to these events'?

Why is there not such corresponding event handler?

EDIT

I update my jsfiddles, it seems there's and error on the class name.

like image 920
Miaonster Avatar asked Dec 26 '13 09:12

Miaonster


2 Answers

there is no event handler attached using jQuery's event system that corresponds to these events

This means, at this point of the learning material, no jQuery event handlers has been attached to these elements using .click(function() {} or .bind('click', function () {}), etc.

The no-argument .click() is used to trigger (.trigger('click')) a "click" event from jQuery's perspective, which will execute all "click" event handlers registered by jQuery using .click, .bind, .on, etc. This pseudo event won't be sent to the browser.

.trigger()

Execute all handlers and behaviors attached to the matched elements for the given event type.

Check the updated jsFiddle example, click on the two links to see the difference. Hope it helps.

like image 150
Arie Xiao Avatar answered Nov 15 '22 11:11

Arie Xiao


First of all you need to prevent the default behaviour of link

$('.js-a1').click(function (e) {
  e.preventDefault();
  $('.js-a2').get(0).click();
  return false;
});

And to trigger the click event you can also use .trigger('click') better way

And the event handler is used like this:

$(document).on('click', '.js-a1',function(){//code in here});
// here now .js-a1 is event handler
like image 24
Bhojendra Rauniyar Avatar answered Nov 15 '22 11:11

Bhojendra Rauniyar