Reputation: 65
I am using the same variables for mouseover and mouseout,is there any way to shorten this?
$('#service_tab li').on('mouseover', function() {
var $a = $(this).find("a"),
dt = $a.attr("href");
$(dt).addClass('tabv');
$("#tabs-1").addClass('tabh');
});
$('#service_tab li').on('mouseout', function() {
var $a = $(this).find("a"),
dt = $a.attr("href");
$(dt).removeClass('tabv');
$("#tabs-1").removeClass('tabh');
});
Upvotes: 0
Views: 54
Reputation: 1270
Yes you can use just one function
instead of repeat your code.
See the example below.
$('#service_tab li').on('mouseover', function() {
myFunction('mouseover');
});
$('#service_tab li').on('mouseout', function() {
myFunction('mouseout');
});
function myFunction(value){
var $a = $(this).find("a"),
dt = $a.attr("href");
if(value == 'mouseout'){
$(dt).removeClass('tabv');
$("#tabs-1").removeClass('tabh');
}else{
$(dt).addClass('tabv');
$("#tabs-1").addClass('tabh');
}
}
Or you can use a switch
$('#service_tab li').on('mouseover', function() {
myFunction('mouseover');
});
$('#service_tab li').on('mouseout', function() {
myFunction('mouseout');
});
function myFunction(value){
var $a = $(this).find("a"),
dt = $a.attr("href");
switch(value){
case 'mouseout' :
$(dt).removeClass('tabv');
$("#tabs-1").removeClass('tabh');
break;
case 'mouseover':
$(dt).addClass('tabv');
$("#tabs-1").addClass('tabh');
break;
}
}
Just like Drow said (thanks), you can also use toggleClass
method of jquery.
toggleClass : Add or remove one or more classes from each element in the set of matched elements.
$('#service_tab li').hover(function() {
var $a = $(this).find("a"),
dt = $a.attr("href");
$(dt).toggleClass('tabv');
$("#tabs-1").toggleClass('tabh');
})
Upvotes: 1
Reputation: 4901
Use event.type.
$('#service_tab li').on('mouseover mouseout', function (e) {
var $a = $(this).find("a"),
dt = $a.attr("href");
if (e.type == 'mouseover') {
$(dt).addClass('tabv');
$("#tabs-1").addClass('tabh');
} else {
$(dt).removeClass('tabv');
$("#tabs-1").removeClass('tabh');
}
});
Upvotes: 2