1

Lets say I have code:

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

I want that after page is loaded #target would be auto clicked, yet click function remain active.

For example same button for play and stop. This would launch play method but if pressed again would stop that.

Should I just trow it to separate method or if there is single line call for such event?

4 Answers 4

6

It's quite simple and you almost had it...

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

Here's a fiddle: http://jsfiddle.net/gislikonrad/xqKBE/

Sign up to request clarification or add additional context in comments.

2 Comments

Although it is more elegant solution, having click separate feels more secure and flexible.
The accepted answer is less efficient... At least take $('#trigger') and put it in a variable and call click and trigger on that...
4
// when the page is ready
$(function() {
    $('#target').click(function() {
        alert('Handler for .click() called.');
    });

    // trigger click handler for #target
    $("#target").trigger('click');
});

Comments

1
$('#target').trigger("click");

Comments

1

I think you should the use toggle() event (not to be confused with toggle for showing and hiding!) as this handles multiple functions off the same event. You can then call click() after binding to call it once automatically:

$('#target').toggle(function() {
  $(this).text('Stop');
}, function() {
  $(this).text('Play');
}).click();

JSFiddle Example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.