Question

I want to change the backColor of my div on a button click using Jquery. Currently i am doing this by changing my class.

Here is my Css:

.GreenColor
{

background-color:#00FF00;
}

.RedColor
{

background-color:#FF0000;
}

Here is my Script in my php file:

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.2.min.js">
</script>
<script>


$(document).ready(function(){


$("button").click(function() {
  $(this).closest("div").toggleClass("RedColor").toggleClass("GreenColor");
});
});
</script>

But somehow it does nothing.

Could use some help here ;)

Was it helpful?

Solution

Can try like

$("#button").click(function() {
   $(this).closest("div").toggleClass("RedColor GreenColor");
});

Or even try like

$("#button").toggle(function() {
    $(this).closest("div").removeClass("RedColor").addClass("GreenColor");
}, function() {
    $(this).closest("div").removeClass("GreenColor").addClass("RedColor");
});

OTHER TIPS

Use .toggleClass() uses the second parameter for determining whether the class should be added or removed. If this parameter's value is true, then the class is added; if false, the class is removed. In essence, the statement:

$("button").click(function() {
      $(this).closest("div").toggleClass("RedColor GreenColor");
    });

Jquery Documentations says

You should use $(':button') selector because:

:button is a jQuery extension and not part of the CSS specification, queries using :button cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :button to select elements, first select the elements using a pure CSS selector, then use .filter(":button").

see fiddle:

http://jsfiddle.net/ravi441988/kE3W8/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top