JuanKman94
JuanKman94

Reputation: 112

Javascript not changing html background color persistenly

everybody. I'm hoping you can help me here, I'm trying to change the color of the body section of my document through javascript by clicking a button.

There are three buttons, each sets a background color. The problem is: When I click one of 'em, it changes the background color for just a second, then it returns to the originally set color, here's a sample of my code:

<html>
<head>
  <script type="text/javascript">
    function colorish(my_color){
      if (my_color === 'gray'){
        document.body.style.background = '#CCCCCC';
      }else if (my_color === 'orange'){
        document.body.style.background = '#FF9900';
      }else if (my_color === 'blue'){
        document.body.style.background = '#C1DAD6';
      } else {
        alert('on else');
      }
    }
  </script>
</head>

<body style="background: orange;">
  <form>
    <button name="back_color" onclick="colorish('gray')">Gy</button>
    <button name="back_color" onclick="colorish('orange')">Oe</button>
    <button name="back_color" onclick="colorish('blue')">Be</button>
  </form>
</body>
</html>

The script is on a separate file on my environment, but it is the exact same.

If in the script I include:

onload = selector();

function selector(){
  var buttons = document.getElementsByName('back_color');

  buttons[0].onclick = colorish('gray');
  buttons[1].onclick = colorish('orange');
  buttons[2].onclick = colorish('blue');
}

It just enters every buttons[].on... assignment and leaves the background set to the last assignment, being blue in this case.

I'm not an expert so maybe there's something I'm missing about html with js.

Upvotes: 2

Views: 178

Answers (2)

user2349072
user2349072

Reputation: 41

Removing the <form> tag will fix your problem. Clicking the button submits the form and reloads the page, resetting the page to its original state.

Upvotes: 2

esqew
esqew

Reputation: 44701

Without declaring a type for your buttons, they act as though they are type="submit". Since there's no configured action parameter on your <form> element, the action is the same page on which they are accessed. It's not that the background is only appearing for a split second and then returning to the normal color, the page is reloading and defaulting back to that color just as if you had just loaded it.

To stop this behavior, give each of your buttons a type="button":

<button type="button" name="back_color" onclick="colorish('gray')">Gy</button>
<button type="button" name="back_color" onclick="colorish('orange')">Oe</button>
<button type="button" name="back_color" onclick="colorish('blue')">Be</button>

As a side note, if you're not using buttons as part of a form to submit data, you don't need a corresponding <form> node - they will function and be standards-compliant all by themselves.

Upvotes: 5

Related Questions