Raphael Rafatpanah
Raphael Rafatpanah

Reputation: 20007

How to use jQuery event in sequence

I am trying to play around with learning jQuery and have made the following jsFiddle:

http://jsfiddle.net/jkNK3/

The idea is to have a div's color change on click. Fine, I got that but I am wondering if there is a way to have the div's color change through multiple classes changes, perhaps with some sort of array or loop. Let me explain.

I have created several CSS classes like so:

.color1 {..}
.color2 {..}
.color3 {..}
.color4 {..}
.color5 {..}
.color6 {..}

and am wondering if we can do something like

addClass("color" + i)

where i can be looped through 1 - 6.

Is there any way to accomplish this? Thanks for the help.

Upvotes: 2

Views: 63

Answers (3)

michael salmon
michael salmon

Reputation: 416

This is a good place to consider the danger of global javascript namespaces. Here's a simple example that takes advantage of closures to avoid that with jquery:

$(function() {
    var numb  = 1;
    // this bit of managing the color state swap is another topic for discussion, so keeping it simple
    var colors_len = 6; 
    $("div").click(function() { 
        // this closure has access to the numb variable
        if (numb < colors_len) {
            numb++;
            $(this).addClass("color" + numb);
            $(this).removeClass("color" + (numb-1));
        } else {
            numb = 1;
            $(this).removeClass("color" + colors_len);
            $(this).addClass("color" + numb);
        }
    });
});

http://jsfiddle.net/2taH5/

ps. Jquery ui also has a swap class method but that is more for animations

Upvotes: 3

adeneo
adeneo

Reputation: 318302

In my opinion the easiest would be to just store the color number in jQuery's handy data(), and then increment it from that:

function fnClick() {
    var numb = $(this).data('color') || 2;
    $(this).addClass("color" + numb).data('color', ++numb)
}

FIDDLE

To make it go back to the first color after the last color etc

function fnClick() {
    var numb = $(this).data('color') || 2;
    numb = numb == 7 ? 1 : numb;
    $(this).removeClass().addClass("color" + numb).data('color', ++numb)
}

FIDDLE

Upvotes: 2

Sushanth --
Sushanth --

Reputation: 55750

How about using a random number to give a random color to the div.

var classCount = 6;

$(document).ready(function () {
    $("div").on("click", fnClick);
});



function fnClick(e) {
   // Get the currently clicked element
   var $this = $(e.target),
       className = 'color' + Math.floor((Math.random() * classCount )+1);
   // Remove the exixting class/s
   $this.removeClass();
   // Add the class
   $this.addClass(className);
}

Check Fiddle

Upvotes: 2

Related Questions