How to Trigger a Click Event using jQuery

This seems a little silly to even mention here, but some people don’t now how to actually trigger events for which they’ve sculpted all that nifty jQuery code functionality for.

It’s actually really simple to be honest. You know that $(‘#button’).click(function(){ alert(‘button clicked!’); }); code you just wrote into your page?

Well try running $(‘#button’).click(); – yes that’s right, the function you previously wrote just got triggered, didn’t it?

And this applies for most events which you create actions for. Calling the event function with a parameter basically means you are creating a handle for when that event is triggered. Calling the event function without any parameters is tantamount to triggering that event.

Simple, but missed by a surprisingly large amount of people! :)

You might also enjoy:

About Craig Lotter

Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under the Funakoshi karate style and for the most part, simply enjoys life with his amazing wife and daughter. Oh, and he draws ever now and then too.
This entry was posted in Technology & Code, Tutorials and tagged event, , , trigger. Bookmark the permalink.
  • http://www.bloodpressuretoday.com/blood-pressure-treatment Alfonso Yount

    I've been struggling for this and thank you for your help.

  • http://www.craiglotter.co.za Craig Lotter

    Eek, yet another potentially hand-craafted spam comment that got through! O.o

  • http://twitter.com/ryanwheale Ryan

    Is there a way to trigger a click event from another element’s click event? This code assumes that the link is an actual hyperlink that may or may not have other click events tied to it. Either way, the link should redirect you to a new page.

    $(‘#myDiv’).click(function() {
    $(this).find(‘a:last’).click(function(e) {
    // Prevent from bubbling, which would cause an endless loop
    e.stopPropagation();
    }).trigger(‘click’);
    });

    Thanks.

blog comments powered by Disqus