Jquery onclick problem add class and delete class

first post here. I am new to jquery and I came across some sort of gray area. I hope I find my answer here and learn from him :)

So, I mean 10 different divs. Everyone has the same class. And every time I click on the div, it should add another class (in this case background-color in css). For this, I have this:

$(document).ready(function() {
$(".menucardmenu").click(function(){
        if($(this).hasClass("menucardmenu")) {
               $(this).addClass("backgroundmenucard");
    }
    else {
        alert ("condition false");
    }
  });
});

But the question is, how can I make sure that only one div can have this background color (in my case, backgroundmenucard). Depending on which div the user clicks, this div will have a background color, and the previous div (which was pressed) should reset back to normal. Can I do it with this right ?:

$ (this) .removeClass ("backgroundmenucard");

Does anyone know the answer to this question?

Regards, Andrew

+3
5

:

$(".menucardmenu").click(function(){
    $(".backgroundmenucard").removeClass("backgroundmenucard");
     $(this).addClass("backgroundmenucard");
  });

: http://jsfiddle.net/r2Sua/

( if, )

+4

...

$(".menucardmenu").removeClass("backgroundmenucard");

this

+2
$(function() // shorthand for document ready
{
    var $divs = $('div.menucardmenu'), // standard jQuery "cache" idiom
        BG_CLASS = 'backgroundmenucard'; // stay DRY, less prone to typos

    $divs.live('click', function() // use .live to bind only 1 event listener
    {   
        // remove the class from all divs
        $divs.removeClass(BG_CLASS);

        // add the class to this div
        $(this).addClass(BG_CLASS);
    }
  });
});

Verification is if($(this).hasClass("menucardmenu"))completely unnecessary, as you are already selecting elements that have this class. He will always value up true.

+1
source
$('.menucardmenu').click(function(){
 $('.menucardmenu').removeClass('backgroundmenucard');
 $(this).addClass('backgroundmenucard');
});
0
source

Another variant:

$(".menucardmenu").not(this).removeClass("backgroundmenucard");
$(this).addClass("backgroundmenucard");

This way you are not deleting or adding a class to a specific (this) element

0
source

All Articles