Reputation: 77
I am trying to have an icon that switches class when the parent div is hovered. So far, here is my code:
var actionIcon = document.querySelector(".task > svg")
var taskContainer = document.querySelector(".task")
function iconScale() {
actionIcon.classList.toggle('big');
}
taskContainer.onmouseenter = iconScale
taskContainer.onmouseleave = iconScale
And the HTML:
<div class="task">
<h3>Title</h3>
<svg viewBox="0 0 24 24">
<path d="..." />
</svg>
</div>
My issue is that the effect I am trying to achieve is only happening on the very first parent element and none of the other ones. I'm pretty sure I am not specifying something but I don't know what. Anyone could give me a hint?
Upvotes: 0
Views: 57
Reputation: 5613
You asked for JavaScript, but as an alternative and simpler example, you don't even need to use JavaScript; what you want can be done entirely in CSS:
svg {
height: 50px;
width: 50px;
background-color: red;
}
.task:hover svg {
background-color: blue;
}
<div class="task">
<h3>Title</h3>
<svg viewBox="0 0 24 24">
</svg>
</div>
<div class="task">
<h3>Title</h3>
<svg viewBox="0 0 24 24">
</svg>
</div>
<div class="task">
<h3>Title</h3>
<svg viewBox="0 0 24 24">
</svg>
</div>
<div class="task">
<h3>Title</h3>
<svg viewBox="0 0 24 24">
</svg>
</div>
Upvotes: 2
Reputation: 4768
Fixed code to map to ALL divs that are tasks. Cannot use querySelector as it only returns first instance.
const actionIcon = (parent) => {
return parent.querySelector('svg');
};
document.addEventListener('DOMContentLoaded', function() {
// Add events to ALL divs that conform
let tasks = document.getElementsByClassName('task');
for(let t of tasks) {
t.onmouseenter = iconScale;
t.onmouseleave = iconScale;
}
function iconScale(event) {
let icon = actionIcon(event.target);
icon.classList.toggle('big');
}
});
svg {
height: 50px;
width: 50px;
background-color: red;
}
.big {
background-color: blue;
}
<div class="task">
<h3>Title</h3>
<svg viewBox="0 0 24 24">
</svg>
</div>
<div class="task">
<h3>Title</h3>
<svg viewBox="0 0 24 24">
</svg>
</div>
<div class="task">
<h3>Title</h3>
<svg viewBox="0 0 24 24">
</svg>
</div>
<div class="task">
<h3>Title</h3>
<svg viewBox="0 0 24 24">
</svg>
</div>
Upvotes: 2