<script>
$(document).ready(function(){
//Load City by State
$('#billing_state_id').live('change', function() {
//do something
});
$('#click_me').live('click', function() {
//do something
//need to recall $('#billing_state_id').live('change', function() { but how?
});
});
</script>
Load City by State working fine but i don't know whether it's possible or not to call it within another function like $('#click_me').live('click', function().
3 Answers 3
I assume you don't want to rebind the event, but call the handler.
You can use trigger() to trigger events:
$('#billing_state_id').trigger('change');
If your handler doesn't rely on the event context and you don't want to trigger other handlers for the event, you could also name the function:
function someFunction() {
//do stuff
}
$(document).ready(function(){
//Load City by State
$('#billing_state_id').live('change', someFunction);
$('#click_me').live('click', function() {
//do something
someFunction();
});
});
Also note that live() is deprecated, on() is the new hotness.
3 Comments
wrap you shared code into another function:
<script>
function myFun () {
//do something
}
$(document).ready(function(){
//Load City by State
$(document).on('change', '#billing_state_id', function() {
myFun ();
});
$(document).on('click', '#click_me', function() {
//do something
myFun();
});
});
</script>
8 Comments
click, myFun);` also note, .live is deprecated..click() or .change() to trigger the event manually (See my comment on the other answeR). What I was talking about is writing myFun instead of function(){ myFun()} since myFun is already a function and you're wrapping it in another (anonymous function expression) for a reason that's beyond me :) The second thing I said is that .live is deprecated (Since jQuery 1.7 if I recall correctly) and should not be used in new code. .on should be preferred to it.I think in this case you want something like this:
$(window).resize(resize=function resize(){ some code...}
Now u can call resize() within some other nested functions:
$(window).scroll(function(){ resize();}
.liveis deprecated, useon(check the manual page on it, it's very descriptive. Moreover, jQuery is just JavaScript... you call a function just like you would at any other point with JS