In this code, I have a main element (.long-brick2), and other elements that are inside it's div (.round2, .round2-2, .round2-2-2, .round2-2-2-2). I have a function that changes the colour of all those elements when the user hovers over them:
$(".long-brick2, .round2, .round2-2, .round2-2-2, .round2-2-2-2").mouseenter(function() {
$(".long-brick2, .round2, .round2-2, .round2-2-2, .round2-2-2-2").animate({
backgroundColor:"#2699F2" }, "slow");
});
$(".long-brick2, .round2, .round2-2, .round2-2-2, .round2-2-2-2").mouseleave(function() {
$(".long-brick2, .round2, .round2-2, .round2-2-2, .round2-2-2-2").animate({
backgroundColor: "#85A0DD"}, "slow");
});
This code works, but of course, it changes the colours of all the elements with those class names, all over the page. how can I use $(this) to achieve targetting the element I'm hovering over?
$(".long-brick2, .round2, .round2-2, .round2-2-2, .round2-2-2-2").mouseenter(function() {
$(this).animate({
backgroundColor:"#2699F2" }, "slow");
});
This code successfully targets only the element I'm currently hovering over, but it doesn't target (.round2, .round2-2, .round2-2-2, .round2-2-2-2), it only binds $(this) to (.long-brick2). So how can I target them all?
Edit
Got the desired effect with:
$(".long-brick2").mouseenter(function() {
$(this).children().animate({
backgroundColor:"#2699F2" }, "slow");
$(this).animate({
backgroundColor:"#2699F2" }, "slow");
});
The mouseenter
event should pass an event parameter into the function which would contain a reference (eg .target
) to the element that triggered the event.
Although, as @rory-mccrossan points out, $(this)
should work fine too...
Alternatively, could you not use CSS with :hover
pseudo-class? Does this styling need to be JS? Or is background colour change just an example for debugging?
SASS:
.long-brick2, .round2, .round2-2, .round2-2-2, .round2-2-2-2 {
background-color: #2699F2;
&:hover {
background-color: #85A0DD;
}
}
(pick a library to have animation/transition mixins - I know bootstrap supports them via SASS).
$(".long-brick2").mouseenter(function() {
$(this).children().animate({
backgroundColor:"#2699F2" }, "slow");
$(this).animate({
backgroundColor:"#2699F2" }, "slow");
});
This did it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.