phil_sw phil_sw - 10 months ago 39
CSS Question

the ID is taking over my class when im using Javascript

I've been sitting with this problem for like 2hours, what im trying to make is a website where you push a button, it changes color. I know this can be done with css, but im not interested in that.

The main problem is that when i push a button, nothing happens.. However, if i remove the ' #sug from the css' everything works perfectly... So what i want to do, is to make the layout very basic at the beginning, so there's nothing to it, except like the black background, and when I push the buttons it should switch..

Also, i know you can implement onclick in the button tag, but that's not what im going for either. I want to know WHY this happens and how i can resolve this problem?

Here's my html file

<!DOCTYPE html>

<html>
<head>
<meta charset="utf-8"/>
<link type="text/css" rel="stylesheet" href="Struktur.css"/>
<script type="text/javascript" src="struktur.js"></script>
<title> My first Javascript project </title>
</head>
<body>
<div id="sug" class="cool insane normal">
<header>
<h1> Welcome to this Javascript site! </h1>
</header>
<section>
<p>
text
</p>
</section>
<button type="button" id="normal"> First style </button>
<button type="button" id="crazy"> Second style </button>
<button type="button" id="insane"> Third style </button>
</div>
</body>

</html>


Here's my CSS file

#sug{
background-color: black;
}

.normal{
height: 500px;
background-color: blue;
color: white;
padding: 30px;
margin: auto;
width: 500px;
}

.insane {
height: 500px;
background-color: green;
padding: 30px;
margin: auto;
width: 500px;
color: white;
}
.cool{
height: 500px;
background-color: red;
padding: 30px;
margin: auto;
width: 500px;
color: white;
}


And here's my javascript file

window.onload = setUp;

function setUp(){
document.getElementById("normal").onclick = setNormalStyle;
document.getElementById("crazy").onclick = setCoolStyle;
document.getElementById("insane").onclick = setInsaneStyle;
}
function setNormalStyle() {
var messageBox = document.getElementById("sug");
messageBox.className = "normal";
}

function setCoolStyle(){
var savingTheSecondVar = document.getElementById("sug");
savingTheSecondVar.className = "cool";
}
function setInsaneStyle(){
var savingTheThirdVar = document.getElementById("sug");
savingTheThirdVar.className = "insane";
}

Answer Source

The problem is your CSS.

#sug{
   background-color: black;
}

Overrides the background-color of your classes because it is a more specific selector (i.e. an id selector).

change the rest of your classes in the css to include the id like

#sug.normal, #sug.insane, #sug.cool etc.

Here is a nice article on CSS specificity to help you understand more: https://css-tricks.com/specifics-on-css-specificity/