Home > Back-end >  Why html will not keep css changes made by javascript when I click a button
Why html will not keep css changes made by javascript when I click a button

Time:05-05

I asked this question to answer it because there is no clear info or question about this. I found the solution in a comment, not in an answer. so I hope this will help others.

HTML

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  
  <a href=""  id="btn" onclick="clickBtn()">btn</a>
  
  
  <div  id="box"></div>
  
 
  
</body>
</html>

CSS

.btn{
  width: 150px;
  height: 50px;
  cursor: pointer;
  margin: 10px;
  background: black;
  color: white;
}

.box{
  width: 200px;
  height: 200px;
  background: orange;
  margin: 5px;
}

javascript

 var box = document.getElementById("box");

function clickBtn() {
   
  if (box.style.background = "orange"){ 
      box.style.background = "blue";
  } else {
      box.style.background = "green";
  }
}

CodePudding user response:

use href="javascript:void(0)" in a tag. The javascript:void(0) can be used when we don't want to refresh or load a new page in the browser on clicking a hyperlink.

CodePudding user response:

1- If you use <a> as a button, it will refresh the page as long as it has href="". so remove href and it will work without refreshing the page.

2- if you want to keep the href, then change the <a> to button. it worked for me.

  • Related