Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery trigger click vs click ()?

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.

like image 376
Royi Namir Avatar asked Jul 14 '12 19:07

Royi Namir


People also ask

What is difference between click and Onclick in jQuery?

So, using a string that is tied to a function, onclick produces an attribute within the binded HTML tag. . click, on the other hand, attaches the function to the property element.

What is trigger click in jQuery?

jQuery trigger() Method The trigger() method triggers the specified event and the default behavior of an event (like form submission) for the selected elements. This method is similar to the triggerHandler() method, except that triggerHandler() does not trigger the default behavior of the event.

What is trigger (' click ')?

trigger( "click" ); As of jQuery 1.3, . trigger() ed events bubble up the DOM tree; an event handler can stop the bubbling by returning false from the handler or calling the . stopPropagation() method on the event object passed into the event.

How is click different from Onclick?

click is a function on HTML elements you can call to trigger their click handlers: element. click(); onclick is a property that reflects the onclick attribute and allows you to attach a "DOM0" handler to the element for when clicks occur: element.


2 Answers

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.

like image 166
The Alpha Avatar answered Sep 30 '22 17:09

The Alpha


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

like image 26
undefined Avatar answered Sep 30 '22 17:09

undefined