tags:

views:

70

answers:

3

How can I toggle the bhavior on a CLick. When I click on a button, I want it to change it to red. When I click again, it should become blue and so on

+1  A: 

use .toggle

e.g

$("#inputId").toggle(
      function () {
        $(this).addClass('someClass');
      },
      function () {
        $(this).addClass('differentClass');
      },
);
redsquare
A: 

HTML:

<input id="MyButton" type="button" value="Click me" class="Color1" />

JQuery:

<script type="text/javascript">
    $(document).ready(function() {
        $("#MyButton").click(function() {
            if ($(this).attr("class") == "Color1") {
                $(this).attr("class", "Color2");
            }
            else {
                $(this).attr("class", "Color1");
            }
        });
    });
</script>
Alex York
A: 

<!-- To change this template, choose Tools | Templates and open the template in the editor. --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> <script src="jquery/jquery.js" language="javascript" type="text/javascript">

</script> <script> $(document).ready(function(){

$("button").click(function () {

    $('#blue').toggleClass("red");

  });

});

</script> <style> div { margin:3px; width:50px; position:absolute; height:50px; left:10px; top:30px; background-color:yellow; } div.blue{ background-color: blue; } div.red { background-color:red; } </style> </head> <body> <button>Start</button> <div id="blue"></div>

</body>

</html>

thinzar