Reputation: 89
Sorry for the really simple question but how could I combine below Jquery ? The question is how can I set :
$('.cmb2 OR .cmb3 OR .cmb4').hover(function ()
$('.cm2 OR .cm3 OR .cm4 DEPENDS ON WHAT IS HOVERED IN ABOVE LINE ').addClass('cmactive');
COMPLETE CODE :
$('.cmb2').hover(function ()
{
$('.cmactive').hide();
$('.cmactive').removeClass('cmactive');
$('.cm2').addClass('cmactive');
$('.cm2').show();
});
$('.cmb3').hover(function ()
{
$('.cmactive').hide();
$('.cmactive').removeClass('cmactive');
$('.cm3').addClass('cmactive');
$('.cm3').show();
});
$('.cmb4').hover(function ()
{
$('.cmactive').hide();
$('.cmactive').removeClass('cmactive');
$('.cm4').addClass('cmactive');
$('.cm4').show();
});
Upvotes: 1
Views: 49
Reputation: 700910
You can use the comma combinator to combine selectors:
$('.cmb2,.cmb3,.cmb4').hover(function ()
In the event handler the context (this
) is the element where the event was triggered, so you can check the class of that element to find out what element to show.
$('.cmb2,.cmb3,.cmb4').hover(function () {
$('.cmactive').hide().removeClass('cmactive');
var target =
$(this).hasClass('cmb2') ? '.cm2' :
$(this).hasClass('cmb3') ? '.cm3' :
'.cm4';
$(target).addClass('cmactive').show();
});
Upvotes: 2
Reputation: 12003
Use commas to have a list of selectors, and if you assign it to a variable you can do work against all of them in the callback function.
var $cmbs = $('.cmb2, .cmb3, .cmb4');
$cmbs.hover(function ()
$(this).addClass('cmactive');
$cmbs.not(this).removeClass('cmactive');
});
Upvotes: 1
Reputation: 1450
Why not add a common class to all three of them and then queue off of that? Alternatively you can use a CSS selector like this: $('[class^="cmb"]')
. You can also select multiple classes by separating what you want with a comma, so you could do $('.cmb2, .cmb3, .cmb4')
Upvotes: 0