jQuery API

.click()

.click( handler(eventObject) ) Returns: jQuery

Description: Bind an event handler to the "click" JavaScript event, or trigger that event on an element.

  • version added: 1.0.click( handler(eventObject) )

    handler(eventObject)A function to execute each time the event is triggered.

  • version added: 1.4.3.click( [eventData], handler(eventObject) )

    eventDataA map of data that will be passed to the event handler.

    handler(eventObject)A function to execute each time the event is triggered.

  • version added: 1.0.click()

This method is a shortcut for .bind('click', handler) in the first two variations, and .trigger('click') in the third.

The click event is sent to an element when the mouse pointer is over the element, and the mouse button is pressed and released. Any HTML element can receive this event.

For example, consider the HTML:
<div id="target">
  Click here
</div>
<div id="other">
  Trigger the handler
</div>

The event handler can be bound to any <div>:

$('#target').click(function() {
  alert('Handler for .click() called.');
});

Now if we click on this element, the alert is displayed:

Handler for .click() called.

We can also trigger the event when a different element is clicked:

$('#other').click(function() {
  $('#target').click();
});

After this code executes, clicks on Trigger the handler will also alert the message.

The click event is only triggered after this exact series of events:

  • The mouse button is depressed while the pointer is inside the element.
  • The mouse button is released while the pointer is inside the element.

This is usually the desired sequence before taking an action. If this is not required, the mousedown or mouseup event may be more suitable.

Examples:

Example: To hide paragraphs on a page when they are clicked:

<!DOCTYPE html>
<html>
<head>
  <style>
  p { color:red; margin:5px; cursor:pointer; }
  p.hilite { background:yellow; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p>First Paragraph</p>

  <p>Second Paragraph</p>
  <p>Yet one more Paragraph</p>
<script>
    $("p").click(function () { 
      $(this).slideUp(); 
    });
    $("p").hover(function () {
      $(this).addClass("hilite");
    }, function () {
      $(this).removeClass("hilite");
    });
</script>

</body>
</html>

Demo:

Example: To trigger the click event on all of the paragraphs on the page:

$("p").click();

Support and Contributions

Need help with .click() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to .click()? Report it to the jQuery core team.

Found a problem with this documentation? Report it to the jQuery API team.

* All fields are required
  • bobbykjack

    According to my testing, under Firefox 3, this event also fires on a submit button when that button's form is submitted, even if it's submitted via the keyboard. This is quite non-intuitive, so be sure it doesn't catch you out!

  • http://twitter.com/yeah_its_me Bri Lance

    It's important to remember that click() will not trigger the default behavior on a link, even if nothing else is preventing it. So you can't use click() by itself to simulate the user clicking on a link and being taken to another url.

  • aandras72

    If you have a situation where you have defined a javascript function that attaches an event through the click function described here, and this function gets executed multiple times, will the function overwrite the click event or will it append to the click event. That is:

    $(“a”).click(fucntion() {
    doSomething();
    }

    Suppose this gets executed multiple times (say 3 times). Will the result be a call to doSomething() once, or doSomething() three times?

    Thanks in advance!

  • Leviath

    I give credit to another for this idea.

    An example of using binding instead of the click reference.

    Say you want to use a table cell, when clicked it jumps you over to a url.

    The markup:
    —–

    Click this table cell to reference this page.

    Then the jquery script:
    —–
    $(function(){
    $(“tr[link]“).bind(“click”, function(){
    var NewLink= $(this).attr(“link”);
    window.location.href = NewLink;
    });
    });

    Have fun :)

  • Alex

    try adding the following code to prevent the browers default behaviour.

    event.preventDefault(); //stop default browser behaviour

    code example:

    $(“a”).click(function(event){
    event.preventDefault(); //stop default browser behaviour
    alert(“This alert will be displayed without following the link”);
    });

  • john

    Inside a click() function the element clicked is available by using the variable 'this'. Not mentioned above and perhaps not expected by some new to jquery/javascript

    $('.foo').click(function(){
    alert(this);
    alert($(this));
    });

  • Manny Fresh

    That’s why there’s this: http://api.jquery.com/event.stopPropagation/

    Just discovered jquery but I’m liking it more and more

  • Anonymous

    I don’t think the code provided here quite works. The anonymous function that does the binding won’t execute, and the selector should be td["link"] rather than tr["link"].

    I got it working by putting this in the ‘ready’ function:
    $(“td[link]“).bind(“click”, function(){
    var NewLink= $(this).attr(“link”);
    window.location.href = NewLink;
    });

  • OneWorld

    But, how CAN I simulate a user clicking a link? I would like to have it that way:

    $(“a#desired_link”).click();

  • Anonymous

    the following HTML:

    Checkbox
    click Checkbox

    alerts with jQuery 1.3.2 on click “checked” and with 1.4.2 “not checked” (tested in IE8 & FF3.6).
    Somehow the handling changed. In the past the input field was first (de-)activated and then the event was fired, now it is turned. Are there any jQuery event which fired in the old order?

  • http://siderite.blogspot.com Siderite

    I have a button with an old style onclick=”doSomething();return false;” which works as expected. If I add a new element and set the onclick=”$(this).prev().click();”, the doSomething method is executed, but the click is also bubbled to the underlying button and a submit occures.

  • http://randomtweak.com randomtweak

    you don’t need to be putting the .click() event listener in the onclick attribute – you should have something like:

    Click

    $(‘#myButton’).click(function(event) {
    alert(‘doSomething’);
    event.preventDefault();
    });

  • chiel

    If you're binding a click handler to a click event and later calling the click programmatically as well as from a user click and want to differentiate the two events in the handler, you can check for eventObject.originalEvent which is set in the user click but not the .click() call.

    Example:
    $('#el').click(function(evt){ if(evt.originalEvent){ //user click } else { // .click() call } });

    This can be useful when having a looping carousel you want to stop once the user clicks on one of the elements.

    I didn't find a built in solution but found this when checking the event object.

  • Anonymous

    How does one handle click events for DOM elements loaded dynamically through AJAX? I can’t seem to get the event handler to register the new element’s click event. Any thoughts?

  • Phil

    You need to bind it with .live() (http://api.jquery.com/live/) as this attaches “a handler to the event for all elements which match the current selector, now or in the future”

  • http://dynamicfiles.de FibreFoX

    You have to use the RIGHT selector ;)

    http://api.jquery.com/attribute-ends-with-selec…

    use this here
    $('a[href$='#desired_link]').click()

  • Punksmurf

    It's not the selector that's the problem (he just wants to select an 'a' with the id 'desired_link' here).

  • http://dynamicfiles.de FibreFoX

    i know, but with the selector i wrote, he will get that elements … he can specify the selector to make that possible he wants, he just hast to look if the link ends with or has that '#desired_link' anchor-text
    the problem is, that
    $(“a#desired_link”).click();
    is the wrong selector because its not CSS-like, so he has to point at an a where the href-attribute ends with #desired_link

  • Slarti_mnini

    if it's a question of actually going to the link then
    location.href = $('a#desired_link').attr('href')
    should do the job. If you have other click events bound then you maybe should trigger them first with the .click() statement and then do the location.href (unless the click event returns false of course!).

    Note: I haven't really tested this – may need some refinements to cope with relative links or jump-to-placeholder type links, but the principle is there.

  • Slarti_mnini

    if it's a question of actually going to the link then
    location.href = $('a#desired_link').attr('href')
    should do the job. If you have other click events bound then you maybe should trigger them first with the .click() statement and then do the location.href (unless the click event returns false of course!).

    Note: I haven't really tested this – may need some refinements to cope with relative links or jump-to-placeholder type links, but the principle is there.

  • http://pulse.yahoo.com/_6W7LVKLQEQV3UXMKPPMYOETRBA Emmett

    Sometimes you are handling keyboard input completely separately, and want jQuery not to interfere. I ran into this today. The quick fix I am using (which works in webkit and qt-webkit, the latter of which is my sole deployment platform at this time) is checking to see if event.detail === 1. If it is, I assume that this is an actual mouse input.

    There are several fields which are consistently different between mouse and keyboard in seemingly predictable ways, at least in webkit. Here’s the list of them, with the first being a typical mouse click value and the second being a keyboard input value:

    screenY: 486 :: 0
    screenX: 490 :: 0
    pageY: 457 :: 0
    pageX: 510 :: 0
    offsetY: 5 :: 0
    offsetX: 50 :: 0
    layerY: 5 :: -452
    layerX: 50 :: -460
    detail: 1 :: 0
    clientY: 380 :: -77
    clientX: 488 :: -22

  • http://twitter.com/Duffleman The Duffleman

    I am using .load() to load a page and then .click() to activate a click handler for that loaded page. But jQuery does not see the link. How can I get it to see the link and add the handler?

  • Kreeves

    I've noticed some quirky behavior with live in IE (version 7). My recommendation is to look into .delegate() http://api.jquery.com/delegate/ which appears to work great across all browsers.

  • Celsoluiz81

    Hello….can someone help me with a problem, which has been haunting me for weeks? I have an array of ids and I go through this array with an each loop. For each item in the array I want to fire a click() method that will select the corresponding radio button. Like this:

    $.each(confArray, function(index, id) {
    var selector = “:radio[id='"+id+"'][class=componentInputRadio]“;
    $(selector).click();
    });

    Where “confArray” is the array containing the id integer.
    I´ve tried this with IE and it works fine, but with Firefox and Chrome it seems to only work for the last id of the array and all others are ignored. I don´t know what I´m doing wrong.

    Help with this would be greatly appreciated. Thank you very much!

  • http://twitter.com/dtrt_nz Do The Right Thing

    Hi Celsoluiz81, the thing that jumps out at me is that IDs should be unique, so much of what you have appears to be redundant.

    How about just:
    $.each(confArray, function(index, id) {
    $('#' + id).click();
    });

  • Celsoluiz81

    Yes, I´m sorry….my mistake. It was originally like you suggested, but I have tried out so many things that I ended up forgetting to edit it back to the original form. Anyway…I´ve tried that before and it doesn´t work either. Thank you a lot for your reply? Do you or does anyone else have any other ideas? THANK YOU!

  • http://grittytech.co.uk Yarekt

    The .click() handler is applied only in the current scope. I had something simillar as well. You have to make sure you instansiate a brand new click handler (or something along thouse lines). I dont have time to explain, but imagine it like this. in the each function you are binding the *same* click handler over and over to elements, only one that will work will always be the last one, since it “rebinds” to the new element every time.
    Im sure you'll figure it out from that.

  • Jeff

    Is the function definition in the description above for the second variation? Shouldn't it be:

    .click(handler(eventObject), [ eventData ] )

    instea of:

    .click( [ eventData ], handler(eventObject) )

  • Celsoluiz81

    Ok! Thank you for your tip. I´ll try it in the upcoming days. Does anyone have an idea of how I´d go about doing this? Instanciating a new click event in a loop? There seems to be a lot of confusion and loose topics about this on the net, but none of them have worked for me so far. Thanks.

  • Antoniuswb

    I'm having some problems. I trying to build a portfolio where the visitor can click left or right to load images on those pages. The problem I'm having is that the animation does not work once I click either left or right button to load new images. Am i forgetting something put in with the codes?

  • M H Rasel

    function myfun()
    {
    //my event handler code. here i want the event to work like following
    event.preventDefault();
    }
    $(“#myelement”).click(myfun);

    how can i pass the event to myfun. i cant use inline function here anyway, any help?
    thanks in advance

  • http://www.learningjquery.com/ Karl Swedberg

    Please direct this question to the appropriate forum at http://forum.jquery.com/
    You'll have a much better chance of having the questions answered there.

    Thanks for understanding.

  • Derleek

    you could try something like…

    function myfun(event){

    event.preventDefault();
    }

    $(“#myelement”).click(function(event){ myfun(event); });

  • Sevil

    Is there any function like this:
    $(“button”).click(function(){
    $(this).addClass(“active”);
    }, function(){
    $(this).removeClass(“active”);
    });

    I want to add class when click the button element, and remove class when “unclick!”. Like “a” element in active state.

  • http://www.codersgrave.com Sevil

    Ok. I found a solution.
    $(“button”).bind(“mousedown mouseup”, function(){
    $(this).toogleClass(“active”);
    });

  • Sarbe97

    hi. I am designing a simple page. i am adding a row dynamically with a span having class=”spn”.

    $(““).insertAfter(“#tbl”);

    But when i try access the span like

    $(“.spn”).click(function(){

    something ….

    })

    it fails. It doesnt go to that span

    I have to write like

    $(“#tbl”).click(function(){

    $(this).find(“.spn”).click(function(){

    something ….

    });

    Then it works. But then i have to click twice. And later it becomes a mess of clicks. Please help me on this matter

    })

  • Sarbe97

    previous one was the wrong one…

    hi. I am designing a simple page. i am adding a row dynamically with a span having

    class=”spn”.

    $(“

    “)

    .insertAfter(“#tbl”);

    But when i try access the span like

    $(“.spn”).click(function(){

    something ….

    })

    it fails. It doesnt go to that span

    I have to write like

    $(“#tbl”).click(function(){

    $(this).find(“.spn”).click(function(){

    something ….

    });

    Then it works. But then i have to click twice. And later it becomes a mess of clicks. Please

    help me on this matter

    })

  • insertioncompleted

    you might want to use livequery (plugin)

  • mayur

    hi..
    mr.Antoniuswb
    if you have doute in jquery..so you can leave this jquery……..i request you……….
    pls………
    mayur(india)

  • Mithun

    can any one help, after click. Animation effects for the appropriate button loads. But after loading it must open a link to some other page. But here it is going to some other page before animation start

  • Joseph Hamilton

    You need to use animation callback, what this means is you say to the animation, “When you are finished playing, do this”.

  • Mithun

    Thank You Mr. Joseph Hamilton. I had that idea but i was not knowing how to execute. And now i removed the img link and wrote an function….

  • Mithun

    pl help. I am placing an image inside a button, so that to make image as an button. But that image is round. Behind this the button also visible in square. so how to make the square button not visible which is behind my image. so only image wants to display and it needs to be button.

  • Mithun

    Attention pl anybody help me fast.
    I am trying to load a content box with animation effect. And what i need is after i load it the content inside should appear from transparency level 0 to 100%. So how could i do it. Only for this transparency i am struggling. If anyone helps me soon. Ill be very great…

  • PD

    I have menu buttons under a map control. The menu buttons have JQuery click events and all works fine. The map is expandable and it hides the menu buttons. But when I collapse the map again and show the menu buttons then the click of menu buttons doesn't work. It only works when I refresh the whole page (hit F5) and that is absolutely not desirable. Is there a best way to do this

  • PD

    I have menu buttons under a map control. The menu buttons have JQuery click events and all works fine. The map is expandable and it hides the menu buttons. But when I collapse the map again and show the menu buttons then the click of menu buttons doesn't work. It only works when I refresh the whole page (hit F5) and that is absolutely not desirable. Is there a best way to do this

  • Telegraph

    is there a way to tell the difference between a human click and a jQuery triggered click?

  • Post

    screenY: 486 :: 0
    screenX: 490 :: 0
    pageY: 457 :: 0
    pageX: 510 :: 0
    offsetY: 5 :: 0
    offsetX: 50 :: 0
    layerY: 5 :: -452
    layerX: 50 :: -460
    detail: 1 :: 0
    clientY: 380 :: -77
    clientX: 488 :: -22

  • Shira

    Perhaps by checking if associated DOM element has focus or is hovered..

  • http://www.tedera.com Ramiro

    or instead of livequery, you can use the built in jquery funtion .live('click', function() { etc });

  • joyphper

    when i use ajax load the content,the click events can't Response,why?

  • http://www.learningjquery.com/ Karl Swedberg
  • Mithun

    can anybody help me pl ?
    I have designed an website. Just want to launch. But at this point of time, i noticed that this is not resolution friendly.I designed this in wide screen 1366 by 768. So i came to now that, to make such type of website, we must use % instead of giving pixels. Okay ill agree with it. But i want to know is there any other way to make resolution friendly or else i need to change entire website now. It takes lot of time for me if i want to alter % in place of pix. So pl anyone tell me any other way of doing resolution friendly including all images resize. From the next time ill use this % concept itself…I will be very great if anybody solves my problem…

  • vinsmith

    its not so difficult to convert into percentage. check in google. Ul find the converter…

  • Jen

    I'm trying to use this on a page:
    $(document).ready(function(){
    $('a.track_this_link').click(function() {
    $.post(http://www.mysite.com/tracker…., {id:this.id});
    return true;
    });
    });

    The tracker.php file never gets the data. I've tried putting other actions in place of the post (like an alert) so I know that everything else is working, it's just not posting to that tracker.php file. I can't figure out what's wrong with this.

  • Sakthiprakash D

    $(this).click(function()
    {
    some code;
    }
    This is working……………..what is the problem in the above code……….can any one………

  • http://twitter.com/alanGalan Alan Garcia

    In IE7, using .delegate() instead of .live() does indeed work. Thanks!

  • Priya12

    U can do the same like this,

    $(“button”).click(function(){
    $(this).removeClass(“active”).addClass(“active”);
    });

  • psmail

    Thanks, Karl – this caused me days of pain and your reference to the FAQ was spot on (sure … you think I would have just stumbled across the FAQ myself … cest la vie)

  • http://www.i4u2.biz I4u2

    great information

  • Flavien Volken

    Is seems that html defined actions “<input onclick=”doStuff()” type=”button”>” are not fired by jQuery once we call $(“input”).click();

  • http://deebster.com/ Deebster

    Look at .live() (http://api.jquery.com/live/) or .delegate() (http://api.jquery.com/delegate)

    Edit: whoops, this was already replied to

  • Jason Simon

    I believe the documentation is wrong, at least how I had to use it. It works like this:

    .click( handler(eventObject), eventDataArray );

  • Neder

    Hi, I'm using the event click() to call a method in Code Behind, like this:

    HTML
    <asp:button bordercolor=”White” id=”btnAddGS” onclick=”AddGSBandeira” runat=”server”>

    JAVASCRIPT
    $(“#ctl00_ContentPlaceHolder1_btnAddGS”).click();

    C#
    public void AddGSBandeira(object sender, EventArgs e)
    {

    }

    Its work normally, but I need to pass a param in the javascript call, like this:
    $(“#ctl00_ContentPlaceHolder1_btnAddGS”).click(“param”);

    But I do not know how this works …can anybody help?</asp:button>

  • Atobison

    I am working with a gridview and churning through the rows to add them into HttpContext Response to create an excel sheet. Because I wanted to disable the page while the export was processing the export button calls a javascript method that clicks a server-side button which process the export code.

    I end the export with:

    HttpContext.Current.Response.Write(sw.ToString());
    HttpContext.Current.Response.End();

    This works great on chrome but on IE8 the page just reloads without displaying the download box. If I click a server side button directly the download works fine. My guess is that some difference between javascript.click and a actual click in the (object sender, ImageClickEventArgs e) part of the event is causing this to mal-function.

    Any Ideas how I can fix this?

  • Atobison

    You can disregard this, I found a way to do a javascript and codebehind event at the same time from 1 button.