7

I have this simple code : here

$(".btn").on('click',function () {

  $(".a").trigger('click');
});

$(".btn2").on('click',function () {

  $(".a")[0].click();
});

I'm trying to simulate pressing on Anchor.

But when I use jQuery's trigger, it doesn't work (why?)

When I use "jsobj".click() func, it does work.

After reading the jQuery documentation, I don't see any reason why it shouldn't.

Help ?

PS: I'm using Chrome.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Royi Namir
  • 144,742
  • 138
  • 468
  • 792

3 Answers3

7

Actually $(".a").trigger('click'); triggers the click event but it doesn't mean that it'll click the link, instead it'll execute the event handler if you already have one, i.e.

$(".btn, .btn2").on('click',function () {
    $($(".a")[0]).trigger('click'); // first element
});

$(".a").on('click', function (e){
    alert(e.target);
});​

The given example will trigger the click event of the a and will execute the handler (the anonymous function) that's already have been registered for that event using

$(".a").on('click', function (e){...});

DEMO.

The Alpha
  • 143,660
  • 29
  • 287
  • 307
  • so whtqa is the difference between click and trigger click ? – Royi Namir Jul 16 '12 at 12:53
  • 1
    you should have a `handler` defined to trigger a `click event` then both way you can trigger the event, i.e. `$(".a").trigger('click');` or `$($(".a")[0]).click();` but you have to have a `click handler for that.` – The Alpha Jul 16 '12 at 12:56
  • sorry, i dont understand why trigger click on button will actually do as if i pressed it , while trigger href wont – Royi Namir Jul 16 '12 at 12:57
  • this is different scenario.here you attached explictly the on click to the href. – Royi Namir Jul 16 '12 at 13:11
3

because $(".a")[0] return raw JavaScript node you cannot use jQuery object methods for that.

Ram
  • 143,282
  • 16
  • 168
  • 197
2

This is because JQuery's .trigger() doesn't really trigger the native events. Try this for example in your script:

$(".btn").on('click',function () {

  $(".a").trigger('click');
});
$(".a").click(function(){alert('triggered!')});

When you create a costume handler using JQuery, THEN the event will be triggered with the .trigger() method.

Update: This is quite interesting, seems to happen only with <a> tags AND with href. Check this out

Adi
  • 5,089
  • 6
  • 33
  • 47
  • where it says that trigger doesnt trigger the native events ( altoght i know its the answer by behavior ) – Royi Namir Jul 14 '12 at 19:34
  • @RoyiNamir, Check the example in the update, very interesting. As for where it says, I've just concluded that. – Adi Jul 14 '12 at 19:35