'Toggle class on div when a specific element is hovered hover (and removed)
I have this javascript (below) which adds/removes a class when an anchor element is hovered over.
a.forEach(item => {
item.addEventListener('mouseover', () => {
cursor.classList.add('hover');
});
item.addEventListener('mouseleave', () => {
cursor.classList.remove('hover');
});
})
This works - but in addition I'd like to apply a different class when two links buttons are interacted with. The classes being .swiper-button-prev and .swiper-button-next. So probably something like hover-swiper-prev and hover-swiper-next depending on which one is interacted with.
Basically when I hover over an image carousel I'd like to display different cursor styling (arrows) for each link and rotate 180 degrees (so they point left/right) when switching to prev/next 'blocks'.
For context I'm using this great bit of code to create a custom javascript mouse cursor (it's for a portfolio/bit of fun so it's fine): https://codepen.io/ntenebruso/pen/QWLzVjY
Solution 1:[1]
Not sure about how you html looks, but here is a small snippet that might help. I added some css to demonstrate.
- Add the class you want to add as an attribute to the html elements.
- Grab that information to add and remove the class accordingly
const a = document.querySelectorAll("a");
const cursor = document.getElementById("cursor");
a.forEach((item) => {
const interaction = item.dataset.interaction;
item.addEventListener("mouseover", () => {
cursor.classList.add(interaction);
});
item.addEventListener("mouseleave", (event) => {
cursor.classList.remove(interaction);
});
});
.swiper-button-prev{
background-color:green;
}
.swipper-button-next{
background-color:yellow;
}
.hover-swiper-prev{
background-color:orange;
}
.hover-swiper-next{
background-color:pink;
}
<a href="" data-interaction="swiper-button-prev">Swipper prev</a>
<a href="" data-interaction="swipper-button-next">Swipper next</a>
<a href="" data-interaction="hover-swiper-prev">Hover prev</a>
<a href="" data-interaction="hover-swiper-next">Hover next</a>
<div style="width: 50px; height: 50px;" id="cursor">
cursor
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Simon Leroux |
