Andrei Rosu
Andrei Rosu

Reputation: 1387

Toggle between two or more functions

The following code doesn't seem to work for jQuery versions higher than 1.8. Can someone explain how can we get the same functionality from newer versions, though? Also, shouldn't we have a structure like element.click(function(){element.toggle();}) ? Why is the toggle() method alone working on click, without actually specifying a .click() method before it?

HTML:

<div style="width: 100px; height: 100px; background: orange;"></div>

JS

$("div").toggle(
  function () {
    $(this).css({"background":"blue"});
  },
  function () {
    $(this).css({"background":"red"});
  },
  function () {
    $(this).css({"background":"yellow"});
  }
);

Upvotes: 1

Views: 1006

Answers (2)

dfsq
dfsq

Reputation: 193261

First of all, don't try to deal with raw CSS properties, this is really inflexible approach. Avoid $.fn.css method for styling. You should use classes with necessary styles, background, color, etc.

Now, the simple and effective solution I can think of is to use toggleClass method like this:

var classes = ['blue', 'red', 'yellow'];

$("div").toggleClass(function(i, oldClass) {
    var newClass = classes[(classes.indexOf(oldClass) + 1) % classes.length]
    return oldClass + ' ' + newClass;
});

Here is a simple demo that toggles classes on each click.

$('.toggle').click(function() {
  
    var classes = ['blue', 'red', 'yellow'];

    $("div").toggleClass(function(i, oldClass) {
        var newClass = classes[(classes.indexOf(oldClass) + 1) % classes.length]
        return oldClass + ' ' + newClass;
    });
  
});
div {padding: 20px; border: 1px #DDD solid;}

.blue {background: blue;}
.red {background: red;}
.yellow {background: yellow;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>

<button class="toggle">Toggle</button>

The benefit here is that you can toggle as many classes (not only 3) as you wich, just add new class to classes array.

Upvotes: 1

Rajesh
Rajesh

Reputation: 24915

try this

var count = 0;

function changeBackground() {
  var color = "";
  switch (count % 3) {
    case 0:
      color = "blue";
      break;
    case 1:
      color = "red";
      break;
    case 2:
      color = "yellow";
      break;
  }
  $("#content").css("background", color);
  count++;
}
div {
  height: 100px;
  width: 100px;
  background: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="content" onclick="changeBackground()"></div>

Upvotes: 1

Related Questions