I’ve got following code:
(function($) {
$(".tmb:first-child").on('mouseenter', function() {
$(".style-light-bg").css("background-color", "rgb(208,206,202)");
$(".tmb:nth-child(2)").addClass("filtered");
});
$(".tmb:first-child").on('mouseleave', function() {
$(".style-light-bg").css("background-color", "#e6e5e2");
$(".tmb:nth-child(2)").removeClass("filtered");
});
$(".tmb:nth-child(2)").on('mouseenter', function() {
$(".style-light-bg").css("background-color", "rgb(177,180,174)");
$(".tmb:first-child").addClass("filtered");
});
$(".tmb:nth-child(2)").on('mouseleave', function() {
$(".style-light-bg").css("background-color", "#e6e5e2");
$(".tmb:first-child").removeClass("filtered");
});
})(jQuery);
.style-light-bg {
background-color: #e6e5e2;
transition: background-color .4s ease-out;
}
.tmb {
opacity: 1;
transition: all .4s ease-in;
}
.filtered {
filter: grayscale(1);
opacity: .2;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="style-light-bg">
<div class="isotope-container">
<div class="tmb"><img src="my-image-1"></div>
<div class="tmb"><img src="my-image-2"></div>
<div class="tmb"><img src="my-image-2"></div>
<div class="tmb"><img src="my-image-2"></div>
...
</div>
</div>
What I’m doing here is when you hover the first .tmb div the second one will lose opacity and grayscale. The background of the container div (style-light-bg) will change. When hovered the second .tmb div the same thing will happen to the first .tmb div. This works perfect and is exactly what I’m trying to achieve.
Now I want that when I hover the first .tmb div all the other .tmb div’s (dynamically amount of div’s, because they can be added or disappear) will have the class .filtered. Also the background should change of the .style-light-bg into 5 different colors. For example .tmb 1, .tmb 6, .tmb 11, … will change the background color to red. .tmb 2, .tmb 7, .tmb 12, … will change the background color to blue. And so on…
2
Answers
Use event delegation to handle dynamically added and removed divs.
Use
$(this)
to access the current target of the event.Use
$(this).index()
to get its position in the list. You can then use the remainder when dividing by 5 to get a number that cycles for each 5 items. Then use this to refer to one of 5 classes that have the different background colors for the container.@Barmar already did a great job. But following the jQuery philosophy: "write less – do more" – it can be done with even less code: