Motim
Motim

Reputation:

Toggle behavior on Click

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

Upvotes: 1

Views: 1077

Answers (3)

thinzar
thinzar

Reputation: 1550

<!-- 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>

Upvotes: 0

redsquare
redsquare

Reputation: 78667

use .toggle

e.g

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

Upvotes: 3

Alex York
Alex York

Reputation: 5450

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>

Upvotes: 1

Related Questions