I want to add class as I hover over an item and remove it as soon as the hover is removed in JavaScript. For now, my code is not removing the class until I hover over that item again.
myChart.on('mouseover', function(params){
var collapseItem = params.name "-content"
var toCollapse = document.getElementById(collapseItem)
var collapseHeading = toCollapse.previousElementSibling
collapseHeading.classList.toggle("active")
})
CodePudding user response:
is this you want?
var myChart = document.getElementById("tt");
myChart.onmouseover = function(event){
var collapseItem = event.target.tagName "-content";
var toCollapse = document.getElementById(collapseItem);
var collapseHeading = toCollapse.previousElementSibling;
collapseHeading.classList.toggle("active");
}
#tt{
height: 40px;
width: 40px;
background-color: red;
}
.active{
height: 50px;
width: 50px;
background-color: green;
}
<div id="tt">
<div id="prev">
</div>
<div id="DIV-content">
</div>
</div>
CodePudding user response:
you can listen to mouseout event (taken from this post)
function toggleActiveClass(params){
var collapseItem = params.name "-content"
var toCollapse = document.getElementById(collapseItem)
var collapseHeading = toCollapse.previousElementSibling
collapseHeading.classList.toggle("active")
}
myChart.on('mouseover', toggleActiveClass);
myChart.on('mouseout', toggleActiveClass);
CodePudding user response:
You need to use "mouseover" as well as "mouseout" to make the toggle or class addition/removal work properly. Currently when your cursor leave there no function to remove the class.
function toggleActiveClass(params) {
var collapseItem = params.name "-content"
var toCollapse = document.getElementById(collapseItem)
var collapseHeading = toCollapse.previousElementSibling
collapseHeading.classList.toggle("active")
}
myChart.on('mouseover', toggleActiveClass);
myChart.on('mouseout', toggleActiveClass);