views:

330

answers:

5

Hi i am using the "selectable" of jQuery UI and i have multiple divs aligned vertically as a list and upon selecting each div the div's background changes to PINK and when i select another DIV the one selected previously should change to WHITE background. As of now i achieved what i need but the problem is the EACH function. if i have 100 divs, it loops for 100 times and checks the below conditions. My question is how can i avoid this looping and make unique selection (i.e., No two DIVs should have same color).

$(".selectDiv").click(function(){
    var clkLink = this.id;
    $(".selectDiv").each(function(){
     var clkLink2 = this.id;
     if(clkLink != clkLink2)
      $(clkLink2).css("background","#FF00CC");
     else
      $(clkLink2).css("background","#FFFFFF");
    });
});
A: 

If you addClass rather than change the css you can then filter by the classname in a selector.

redsquare
+5  A: 

If you have the colours as css classes, it is quite easy to do:

$('.selectDiv').click(function(){
   $('.isSelected').removeClass('isSelected');
   $(this).addClass('isSelected');
});
Jimmy Stenke
+1 this is the right way to do it
cletus
+1  A: 

This will reset them all, then change the currently clicked one:

$(".selectDiv").click(function(){
    $(".selectDiv").css("background","#FFFFFF");
    $(this).css("background","#FF00CC"); 
});
karim79
A: 
var currentDiv = null;

$('div.selectDiv').click(function() {
    if (currentDiv !== null) {
        currentDiv.css('background', '#ff00cc');
    }
    currentDiv = $(this);
    currentDiv.css('background', '#ffffff');
});
RaYell
A: 

Your jQuery UI Selectable click event shouldn't automatically be assigned using the click event of your divs. The Selectable feature has its own event binding called "Stop".

var previousSelection = {}; // Use this to store the previous selection if desired

$('#selectDiv-Container').selectable({
                    stop: function() {
                        previousSelection = $(this);
                        $('.ui-selected', this).each(function() {
                            // Iterate through my new selections if desired.
                        });
                    }
                });

I'm assuming your selectable list has a container called "selectDiv-Container" for the purposes of illustration. If you want to keep the previously-clicked item in memory (to style it or whatever), you'd cache it in a variable as above (previousSelection).

When your user clicks your list, the "stop" event fires. You can iterate through all the selected values and set their styles at that point.

Phil.Wheeler