12

I want to know if their is an option to call a function that is already assigned to a JQuery event.

For example:

$("#somediv").change(function() { //do something });

I want to be able to manually call that function that was originally assigned to the "somediv" element.

Thanks.

3
  • did you try if(typeof ($("#somediv").change) == 'function') { yourCode(); $("#somediv").change(); } Commented Aug 5, 2011 at 16:35
  • 1
    @jernej: I don't think that will do what you want; $("#somediv").change is going to give you the function change of the jQuery object, not your function. Commented Aug 5, 2011 at 16:37
  • @jernej typeof ($("#somediv").change) will always be 'function' with jQuery. Commented Aug 5, 2011 at 16:38

7 Answers 7

30

Use trigger:

$("#somediv").trigger("change");
Sign up to request clarification or add additional context in comments.

2 Comments

N.B. this is equivalent to $("#somediv").change();
Note: For both plain objects and DOM objects other than window, if a triggered event name matches the name of a property on the object, jQuery will attempt to invoke the property as a method if no event handler calls event.preventDefault(). If this behavior is not desired, use .triggerHandler() instead. Ref: api.jquery.com/trigger
23

Have you tried this?

$("#somediv").change();

Comments

4

JQuery can trigger a given event; just call $("#somediv").change().

Comments

1

I think what you meant to do is define the function outside change(..).

function whatever() { // do something }

$("#somediv").change(whatever);

Then you can call your function elsewhere.

At least that's how I interpreted your question.

Comments

1

If you don't want to actualy trigger the change event (as shown in the previous answers above), you should probably extract that function into something that you can call from multiple places. It looks like you have found a place where reuse is in your application and extracting it may be the best answer.

Comments

1

A simple way of achieving this is placing the "actual" function outside the Jquery call. So, your code would look something like:

$("#somediv").change(function() { doSomething(); });

var doSomething = function() {
// actually do something
}

This would make it quite simple to call the doSomething function form anywhere in your scripts.

1 Comment

Nice idea. You would probably need to pass $(this) into the doSomething function though using your example as in my situation i wanted to do something using the attributes of the #somediv
1
<script type="text/javascript">
window.onload = function () {
    $("#somediv").change();
}
</script>

i think this what you want to do .

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.