-1

I am tried to change the background color for div by using JavaScript, but the changes didn't applied because when I press on button the browser make reload for the page and restore to default setting without change.

How I can change the background color for div without page reload or the changes applied?

Mohammad Diab
  • 258
  • 3
  • 13

2 Answers2

3

Page reloads because your button is inside a form and when you click it - you submit the form.

Inside the onclick function you need to prevent default action, just end with:

return false;

If you ask why: submit is default button type:

Button types:

  • submit: The button submits the form data to the server. This is the default if the attribute is not specified, or if the attribute is dynamically changed to an empty or invalid value.
  • reset: The button resets all the controls to their initial values.
  • button: The button has no default behavior. It can have client-side scripts associated with the element's events, which are triggered when the events occur.

Recommended readings:

Community
  • 1
  • 1
skobaljic
  • 9,379
  • 1
  • 25
  • 51
  • 1
    That's only true for a submit button – Gary Jun 19 '15 at 21:58
  • For any button - [check this](http://jsfiddle.net/gdb37t5h/) – skobaljic Jun 19 '15 at 22:28
  • 1
    Interesting catch, but not "any button". `input type='button'` and `button type='button'` [do not behave that way](http://jsfiddle.net/gdb37t5h/1/). – Gary Jun 19 '15 at 22:33
  • `input type='button'` is an `` tag, I'm talking about ` – skobaljic Jun 19 '15 at 22:36
  • Fair enough, a little presumptuous IMO but then again the OP didn't give much to go off. At any rate, yes, the default button will act as a submit but merely setting the type will do the same thing while being more semantic. I'm exactly disagreeing with you, but I think this context was necessary. Btw that link might render this question a dupe. – Gary Jun 19 '15 at 22:42
  • Well, only MDN says it is default type for button, think 10 years ago it was different and some of browsers did not submit the form if type was not specified to `submit` (thinking of IE). Or even if you specify `submit` it would not submit the form, you would have to use an `input` tag or script. – skobaljic Jun 19 '15 at 22:52
3

Here's some code using jQuery that changes the background without reloading:

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Changing DIV Background Color</title>
  <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
  <style>
  #changing_background {
    background-color: red;
    min-height: 200px;
  }
  </style>
</head>
<body>

<div id="changing_background"></div>

<button id="change_background">Click Me</button>

<script>
  $("#change_background").click(function(e){
    $("#changing_background").css("background-color", "blue");
  });
</script>

</body>
</html>
rphv
  • 5,409
  • 3
  • 29
  • 47