Skip to content

jQuery Dynamic Style

  • jQuery

You might want to change the style of elements after some events, you could leverage jQuery to fulfill. For example, if you have an element like this:

<button style='color: white; background-color: blue;'>Post it</button>

Change Style after Click

We'd like to change the background color of the button once been clicked, we can do it like this:

<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(function() {
  $("#btn1").click(function() {
    $("#btn1").attr("style", "color: white; background-color: red;");
  });
});
</script>
<button id='btn1' style='color: white; background-color: blue;'>Post it</button>

The key function is ".attr()" which can change the attribute "style" dynamically. We can test the output:



The drawback is that, once you click it, the style can not go back. Let's see a more controllable way to do it.

Toggle Class

An advanced way that can change style dynamically is to use ".toggleClass()" to switch style back and forth.

<style>
  .color_blue {
    color: white; background-color: blue;
  }
  .color_red {
    color: white; background-color: red;
  }
</style>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(function() {
  $("#btn2").click(function() {
    $("#btn2").toggleClass("color_red");
  });
});
</script>
<button id='btn2' class='color_blue'>Post it</button>

You can benefit from switching the style back and forth by toggling the second class ".color_red" after every clicking. Let's test the output:



Add Class

There are more ways that can achieve similar effects, you can try it by yourself:

...
$("#btn1").attr("class", "color_red");
...

or

...
$("#btn2").addClass("color_red");
...

Leave a Reply

Your email address will not be published. Required fields are marked *