how can i simplify this code? The Mouse-Events are all quite similar. Therefore there should be a way to shorten the code.
THANKS,
Johannes
var $allItems = $('ul.image-grid li'),
$kindertanzItems = $('li[data-type=kindertanz]'),
$urbanItems = $('li[data-type=urban]'),
$ethnoItems = $('li[data-type=ethno]'),
$gesundheitItems = $('li[data-type=gesundheit]');
$kindertanzItems.hover(function(){
$allItems.each(function(){
$(this).css("opacity","0.1");
});
$kindertanzItems.each(function(){
$(this).css("opacity","1").css("background-color","#232628").css("border-color", "black");
});
}).mouseleave(function(){
$allItems.each(function(){
$(this).css("opacity","1");
});
$kindertanzItems.each(function(){
$(this).css("background-color","#33373b").css("border-color", "#222527");
});
});
$urbanItems.hover(function(){
$allItems.each(function(){
$(this).css("opacity","0.1");
});
$urbanItems.each(function(){
$(this).css("opacity","1").css("background-color","#232628").css("border-color", "#101011");
});
}).mouseleave(function(){
$allItems.each(function(){
$(this).css("opacity","1");
});
$urbanItems.each(function(){
$(this).css("background-color","#33373b").css("border-color", "#222527");
});
});
$ethnoItems.hover(function(){
$allItems.each(function(){
$(this).css("opacity","0.1");
});
$ethnoItems.each(function(){
$(this).css("opacity","1").css("background-color","#232628").css("border-color", "black");
});
}).mouseleave(function(){
$allItems.each(function(){
$(this).css("opacity","1");
});
$ethnoItems.each(function(){
$(this).css("background-color","#33373b").css("border-color", "#222527");
});
});
$gesundheitItems.hover(function(){
$allItems.each(function(){
$(this).css("opacity","0.1");
});
$gesundheitItems.each(function(){
$(this).css("opacity","1").css("background-color","#232628").css("border-color", "#101011");
});
}).mouseleave(function(){
$allItems.each(function(){
$(this).css("opacity","1");
});
$gesundheitItems.each(function(){
$(this).css("background-color","#33373b").css("border-color", "#222527");
});
});
You’re only applying styles – therefore you should be using CSS not Javascript.
Create a CSS file and add the following:
And instead of identifying
<li>s by their data-type, you should add classes to them, so you can do:Update: The requirement is to highlight not only whichever
<li>the mouse is hovering over, but also every other<li>with the samedata-type. The Javascript to do this is:Hope that finally helps!
Sidenote: while the above will work, I’d recommend setting a CSS class for the highlighted state. That way instead of messing with all the CSS attributes in your javascript, you can simply do
.removeClass("highlight")for all items, and.addClass("highlight")for the others.