Changing class for DIV through JavaScript works great until I “interrupt it” by changing style attribute for that DIV.
case 0: changes left to 400
case 1: changes left to 600
case 2: doesn’t work!
Why’s that?
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<style type="text/css">
.pos1 {left: 200px; top:400px;}
.pos2 {left: 400px; top:400px;}
.pos3 {left: 800px; top:400px;}
</style>
</head>
<body>
<div id = "img" class = "pos1" style="position:absolute;"> <img src="gfx/1n.png"> </div>
<script type="text/javascript">
var action = 0;
window.onmousedown = function(event){makeAction();}
function makeAction() {
switch(action) {
case 0: action++; document.getElementById('img').className = "pos2"; break
case 1: action++; document.getElementById('img').style.left = "600px"; break;
case 2: action++; document.getElementById('img').className = "pos3"; break;
}
}
</script>
</body>
</html>
Because the style attribute you set in the second case overrides the style from the class you assign in the last case.
After this first case the image tag is
So it’s positioned left by 400px.
After the second case the image tag is
Even though it still has class pos2, the style attribute overrides the left positioning, so it’s now positioned left by 600px.
After the last case the image tag is:
Even though it now has class pos3, the style attribute still overrides the left positioning, so it remains positioned left by 600px.
Understand that CSS does not depend on when it’s applied, but that it always follows the rules of specificity. And the rules state that style rules in the style attribute of a tag override style rules from a class.
You can override the rule using the
importantkeyword: