Reputation: 12275
basically I am trying to trim down some of this code, but I am not sure how to do so, I have 9 DIV's positioned all absolute in different spots. They are all Grey, but when hovered the DIV that is hovered, fades out and the corresponding DIV fades in. Is there a better way to write this?
$('#l1').hover(function () {
$(this).fadeOut('300');
$('#l1c').fadeIn('300')
});
$('#l2').hover(function () {
$(this).fadeOut('300');
$('#l2c').fadeIn('300')
});
$('#l3').hover(function () {
$(this).fadeOut('300');
$('#l3c').fadeIn('300')
});
$('#l4').hover(function () {
$(this).fadeOut('300');
$('#l4c').fadeIn('300')
});
$('#l5').hover(function () {
$(this).fadeOut('300');
$('#l5c').fadeIn('300')
});
$('#l6').hover(function () {
$(this).fadeOut('300');
$('#l6c').fadeIn('300')
});
$('#l7').hover(function () {
$(this).fadeOut('300');
$('#l7c').fadeIn('300')
});
$('#l7').hover(function () {
$(this).fadeOut('300');
$('#l7c').fadeIn('300')
});
$('#l1c').mouseout(function () {
$(this).fadeOut('300');
$('#l1').fadeIn('300')
});
$('#l2c').mouseout(function () {
$(this).fadeOut('300');
$('#l2').fadeIn('300')
});
$('#l3c').mouseout(function () {
$(this).fadeOut('300');
$('#l3').fadeIn('300')
});
$('#l4c').mouseout(function () {
$(this).fadeOut('300');
$('#l4').fadeIn('300')
});
$('#l5c').mouseout(function () {
$(this).fadeOut('300');
$('#l5').fadeIn('300')
});
$('#l6c').mouseout(function () {
$(this).fadeOut('300');
$('#l6').fadeIn('300')
});
$('#l7c').mouseout(function () {
$(this).fadeOut('300');
$('#l7').fadeIn('300')
});
Upvotes: 2
Views: 138
Reputation: 14337
$('#l1,#l2,#l3,#l4,#l5,#l6,#l7').hover(function() {
$(this).fadeOut(300);
$("#" + this.id + "c").fadeIn(300);
});
$('#l1c,#l2c,#l3c,#l4c,#l5c,#l6c,#l7c').mouseout(function() {
$(this).fadeOut(300);
$("#" + this.id.substring(0, this.id.length - 1)).fadeIn(300);
});
Upvotes: 6
Reputation: 4312
You can add two class for the two types of div. eg: for #l1 to #l7, add class ".ln"; for #l1c to #l7c, add class ".lnc", then use below code:
$(".ln").live("hover", function(){
$(this).fadeOut('300');
$("#" + $(this).attr("id") + "c").fadeIn(300);
};
$(".lnc").live("mouseout", function(){
var id = $(this).attr("id");
$(this).fadeOut('300');
$("#" + id.substring(0, id.length - 1)).fadeIn(300);
};
Upvotes: 1