Reputation: 157
I have a bunch of grids with a class called "grid-show". I want to style this specific element that my mouse is over (without using the .hover property in CSS), but when the mouse is not over, I want it to stop and goes back to normal. The "else if" in my example doesent manage to do that.
let divShow = document.querySelectorAll('.grid-show');
for(i = 0; i < divShow.length; i++){
divShow[i].addEventListener('mouseover', function(eve){
if (eve.target) {
eve.target.style.color = "orange"
} else if(!eve.target){
eve.target.style.color = " ";
}
})
}
Upvotes: 0
Views: 61
Reputation: 370779
You should use mouseenter
instead (which only fires when the mouse enters the targeted container - it doesn't bubble) and add a separate listener for mouseout
:
document.querySelectorAll('.grid-show').forEach((div) => {
div.addEventListener('mouseenter', () => {
div.style.color = 'orange';
});
div.addEventListener('mouseleave', () => {
div.style.removeProperty('color');
});
});
<div class="grid-show">foo</div>
<div class="grid-show">bar</div>
If you use mouseover
instead of mouseenter
, the event will also run whenever the mouse enters a child element, which is (probably) not desirable, eg
document.querySelectorAll('.grid-show').forEach((div) => {
div.addEventListener('mouseover', () => {
console.log('mouseover handler');
div.style.color = 'orange';
});
div.addEventListener('mouseleave', () => {
div.style.removeProperty('color');
});
});
<div class="grid-show">foo<span>child</span></div>
<div class="grid-show">bar<span>child</span></div>
The problem with if (eve.target) {
is that an event.target
for a mouse event will always be truthy.
Upvotes: 2
Reputation: 122906
No need for a loop if you use event delegation
document.addEventListener("mouseover", evt => {
const origin = evt.target;
if (origin.classList && origin.classList.contains("grid-show")) {
origin.classList.add("hoverColor");
}
});
document.addEventListener("mouseout", evt => {
const origin = evt.target;
if (origin.classList && origin.classList.contains("grid-show")) {
origin.classList.remove("hoverColor");
}
});
.grid-show {
cursor: pointer;
}
.hoverColor {
color: orange;
}
<div class="grid-show">div 1</div>
<div class="grid-show">div 2</div>
<div class="grid-show">div 3</div>
<div class="grid-show">div 4</div>
Upvotes: 1
Reputation: 1415
Using a CSS based solution would be more elegant, but if you still want to do it programmatically, you could use the "mouseout" event to remove the style:
let divShow = document.querySelectorAll('.grid-show');
for(i = 0; i < divShow.length; i++){
divShow[i].addEventListener('mouseover', function(event){
event.target.style.color = "orange"
})
divShow[i].addEventListener('mouseout', function(event){
event.target.style.color = "";
})
}
Upvotes: 5