I have a jquery code that shakes a div when clicked.
$("#error").click(function() {
$("#box-login").show('shake', 55);
$(".header-login").show('shake', 55);
$("#content-login .error").show('blind', 500);
return false;
});
I want to call this as a function when there is a form validation error, for example…
$("#box-login").validate({
rules: {
username: "required",// simple rule, converted to {required:true}
password: {// compound rule
required: true,
email: true
},
url: {
url: true
},
comment: {
required: true
}
},
messages: {
comment: "Please enter a comment."
}
});
});
How do i combine these two or is there any other better method to call the shake as a function when there is some error? Please help.
The main thing is to make your shake function its own named, reusable function:
Then call that function from both your
clickandinvalidHandlerhandlers (either directly or indirectly):Now, there I’ve called it directly. Note that it will be called with different arguments in the two situations; if you want to do something with those arguments, you might have separate event handlers, both of which call your
shakeItfunction:});
(Those both might also be named, reusable functions, but if they’re really one-offs and if you like anonymous functions — I don’t — the above would be fine.)
This is basically just a specific example of modularization, which is in general a good guideline for writing software: Make the pieces small and reusable, then string them together to do things.