Reputation: 10297
I have two on click event handlers that are nearly identical:
$('#imgPreTravel').on( "click", function() {
$('#preTravel').addClass('finaff-form-help-hide');
$('#postTravel').addClass('finaff-form-help-hide');
$('#postTSec0').removeClass('finaff-form-help-hide');
});
$('#imgPostTravel').on( "click", function() {
$('#preTravel').addClass('finaff-form-help-hide');
$('#postTravel').addClass('finaff-form-help-hide');
$('#postTSec0').removeClass('finaff-form-help-hide');
});
(the only difference being the IDs - imgPreTravel
and imgPostTravel
).
Can I combine them into one on click function and, if so do they need to be comma-separated? IOW, should it be like this, similar to the way multiple classes can be assigned to an element:
$('#imgPreTravel #imgPreTravel').on( "click", function() {
$('#preTravel').addClass('finaff-form-help-hide');
$('#postTravel').addClass('finaff-form-help-hide');
$('#postTSec0').removeClass('finaff-form-help-hide');
});
...or like this, as if the IDs are arguments in a method call:
$('#imgPreTravel, #imgPreTravel').on( "click", function() {
$('#preTravel').addClass('finaff-form-help-hide');
$('#postTravel').addClass('finaff-form-help-hide');
$('#postTSec0').removeClass('finaff-form-help-hide');
});
?
Upvotes: 0
Views: 101
Reputation: 70528
If for whatever reason you think it would be clearer you could do this:
function clickfun() {
$('#preTravel').addClass('finaff-form-help-hide');
$('#postTravel').addClass('finaff-form-help-hide');
$('#postTSec0').removeClass('finaff-form-help-hide');
});
$('#imgPreTravel').on( "click", clickfun);
$('#imgPostTravel').on( "click", clickfun);
or
$('#imgPreTravel, #imgPostTravel').on( "click", clickfun);
Upvotes: 2
Reputation: 16989
You can most definitely do this, with comma separated selectors.
$('#imgPreTravel, #imgPreTravel').on('click', function() {
[...]
...would be almost the correct approach, though, in your example, #imgPreTravel
is the same id
twice and, would do no good in this case. You'll actually only wire to the first DOM element with that id
. See the jQuery Multiple Selector (“selector1, selector2, selectorN”) docs for more information...
Selects the combined results of all the specified selectors.
JSFiddle Example - with #imgPreTravel
and #imgPostTravel
example selectors
<div id="imgPreTravel">pre</div>
<div id="imgPostTravel">post</div>
$('#imgPreTravel, #imgPostTravel').on('click', function() {
console.log($(this));
});
Upvotes: 2
Reputation: 74
Already Answered:
answered Feb 2 '11 at 21:11
Rains 97.4k27250312 Here's the link
"
$("selector, selector")
That very syntax works. Do you want to call
.children("input")
on both?Alternatively
$.merge($("selector"), $("selector"));
"
I would have commented but I don't have a high enough reputation
Upvotes: 2