Philip
Philip

Reputation: 621

Changing CSS class with JavaScript has no effect

I want my nav bar (that is in the form of a list) to stay invisible (display: none;) on page load, and to appear when something is clicked (currently using a button)

here is my HTML code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>

<head>
<script type="text/javascript" src="js/navbar.js"></script>
<link rel="stylesheet" type="text/css" href="main.css">
<script type=text/javascript>
function changeClass(){
document.getElementById("mainnav").setAttribute("class", "show");
}
</script>
</head>

<body>

<div class="wrapper">

<input  type="button" value="click" onClick="changeClass()">

<div id="mainnav">

 <ul >
<li>Home</li>
<li>Emergency Repair Service</li>
<li>Heating</li>
<li>Air Conditioning</li>
<li>Products</li>
<li>Specials</li>
<li>Contact</li>
</ul>

</div><!--mainnav-->

Here is my CSS

#mainnav {
display:none;
}

ul li {
float: left;
list-style-type: none;
}

.show {
display: block;
height: 75px;
width: 100%;
background-color: #000;
}

Here is my javascript

function changeClass(){
document.getElementById("mainnav").setAttribute("class", "show");
}

thanks!

Upvotes: 2

Views: 2559

Answers (4)

Nick
Nick

Reputation: 8540

Change this:

.show {
    display: block;
    height: 75px;
    width: 100%;
    background-color: #000;
}

to this:

#mainnav.show {
    display: block;
    height: 75px;
    width: 100%;
    background-color: #000;
}

display:block in the .show class will then override display:none in the #mainnav selector, because the new rule is more specific.

Upvotes: 0

Kai
Kai

Reputation: 9328

ID selector (#mainnav) rules have a higher precedence than class selector (.show) rules. Therefore, display:none will persist even after you assign your div the class .show.

You could initially use a .hide class and replace it with a .show or use an !important rule in your CSS.

An article on CSS specificity: http://coding.smashingmagazine.com/2010/04/07/css-specificity-and-inheritance/

Upvotes: 1

Moin Zaman
Moin Zaman

Reputation: 25465

It works. See my example here: http://jsbin.com/uyonuc

Are you sure you're setting it to be hidden from the CSS initially?

Also try adding a !important to display:block to make sure it overrides any other property.

Upvotes: 2

Kamil Lach
Kamil Lach

Reputation: 4629

I think js is good but problem is in css, try change it like below.

.show {
display: block !important;
height: 75px;
width: 100%;
background-color: #000;
}

Upvotes: 2

Related Questions