Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset a CSS attribute that's been changed using JavaScript?

I have navigation buttons that increase in width from 100px, to 150px when hovered over :

nav li:hover{
width:150px;
}

But using javascript I have made it so that which ever option has been selected, will continue to have a width of 150px. When each option is selected, it makes the other options go back to 100px as I intended :

function show1(){
document.getElementById("nav1").style.width="150px";
document.getElementById("nav2").style.width="100px";
document.getElementById("nav3").style.width="100px";
}
function show2(){
document.getElementById("nav2").style.width="150px";
document.getElementById("nav1").style.width="100px";
document.getElementById("nav3").style.width="100px";
}
function show3(){
document.getElementById("nav3").style.width="150px";
document.getElementById("nav1").style.width="100px";
document.getElementById("nav2").style.width="100px";
}

The problem is, once one of the navigation options has been selected, they no longer increase in width to 150px when hovered over, because the functions have set them to stay at 100px.

I am trying to work out how to make it so that each of the navigation buttons always increases in width when hovered over, while whichever one has been selected stays at the increased length. So i'm trying to find a way to reset the width value to how it is defined by my CSS after each function is executed.

Anyone know how to solve this? I'm fairly beginner level at javacript.

like image 946
user3466122 Avatar asked Dec 03 '25 05:12

user3466122


2 Answers

I would do this by putting the "selected" style in a separate CSS class, and dynamically adding that class to the objects you want to have the fixed width, then dynamically removing it.

Fiddling with CSS classes in JS is not very difficult; see here for example.

like image 179
15ee8f99-57ff-4f92-890c-b56153 Avatar answered Dec 05 '25 19:12

15ee8f99-57ff-4f92-890c-b56153


Make it an empty string and it takes over the one from your stylesheet again

document.getElementById("nav2").style.width = "";

like image 37
timing Avatar answered Dec 05 '25 18:12

timing