Skip to content Skip to sidebar Skip to footer

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

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.

Solution 2:

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

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

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

Solution 3:

i think you forgot to read documentation.

Document says :

// Triggering a native browser event using the simulate plugin
$( ".js-a2" ).simulate( "click" );

Solution 4:

Old question, but here's a nifty and simple solution: You can basically "register" a native JS event with jQuery by assigning the DOM element's onEvent handler to be the native event. Ideally, we would check first to ensure the onEvent handler has not already been set. For example, 'register' the native JS click event so it will be triggered by jQuery:

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

var trigger_element = $('.js-a2')[0]; // native DOM elementif (!trigger_element.onclick) {
  trigger_element.onclick = trigger_element.click;
}

Here is a fiddle: http://jsfiddle.net/f9vkd/162/

Solution 5:

You have to use $("selector").trigger('click')

Post a Comment for "Why Jquery Cannot Trigger Native Click On An Anchor Tag?"