user3394791 user3394791 - 1 month ago 9
HTML Question

Onclick not creating permanent change

I am writing a code with multiple divs that uses a button to change the background colors of divs when clicked. The background of the divs are hard coded into the html:
ex:

<div style="background-color: grey">
</div>


When I click the button, I want the background color to be permanently changed to white. However, the color only changes to white for an instant. the code is as such:

<script>
var divs=document.getElementsByTagName("div");
function noColors(){
for(i=0;i<divs.length;i++){
divs[i].style.backgroundColor="white";
}
};
</script>
<form>
<button onclick="noColors()"> I HATE THESE COLORS!!! </button>
</form>


Any help would be appreciated

Answer

Remove the form tag:

<button onclick="noColors()"> I HATE THESE COLORS!!! </button>
<div style="width: 100px;height: 100px; background-color: red"></div>
<div style="width: 100px;height: 100px; background-color: yellow"></div>
<div style="width: 100px;height: 100px; background-color: blue"></div>
<script>
var divs=document.getElementsByTagName("div");
function noColors(){
  for(i=0;i<divs.length;i++){
    divs[i].style.backgroundColor="white";
  }
};
</script>

when the form tag is used and you click on the button the colors change but the form also submits, which leads to reload of the page. This way you loose the colors of the div elements.

Comments