tirenweb
tirenweb

Reputation: 31729

Exchanging classes between two divs when clickin on one of them

I have this code below. When I run the app and I click on "bar", the message The not 'current' div has been clicked is shown. Then if I click on "foo", the message is not shown. I expected the message was shown, since I have exchanged the class current between the two divs.

<div class="current">foo</div>
<div>bar</div>

$('document').ready(function(){
    $('div').not('.current').on('click', function(){
        alert("The not 'current' div has been clicked.")
        var aux = $(this);
        $('div').removeClass('current');
        aux.addClass('current');
    });
});

Upvotes: 0

Views: 77

Answers (4)

Jai
Jai

Reputation: 74738

I think what you want is on clicking of a div which does not have a .current class would get the click event and swap the .current class, as you are manipulating dom with the jQuery and swapping the class, it does not get the applied new class, it takes the element which was loaded when page was ready, so you can delegate the event to the document and you would get what you want:

$(document).on('click', 'div:not(.current)', function () {
  alert("The not 'current' div has been clicked.");
  var aux = $(this);
  $('div').removeClass('current');
  aux.addClass('current');
});

Tryout this fiddle

Upvotes: 0

palaѕн
palaѕн

Reputation: 73926

On DOM ready, you have assigned the click event only for the div not having the class current. Hence, the code doesn't work. You need to assign the click events to all the div's and check for the class inside it like:

$('div').on('click', function (e) {
    if (e.target.className === 'current') return;
    console.log("The not 'current' div has been clicked.")
    var $aux = $(this);
    $('div').removeClass('current');
    $aux.addClass('current');
});

Upvotes: 0

Luigi De Rosa
Luigi De Rosa

Reputation: 720

Use this code:

$('document').ready(function(){
    $('div').on('click', function(){
        if($(this).hasClass('current')) return;

        alert("The not 'current' div has been clicked.")
        var aux = $(this);
        $('div').removeClass('current');
        aux.addClass('current');
    });
});

Check the class inside the callback ;)

jsfiddle here: http://jsfiddle.net/5hFv4/

Upvotes: 0

Strille
Strille

Reputation: 5781

You only add the click event to the "not current" element, and when you switch classes one of the elements still has no click event. Instead you can do:

$('document').ready(function(){
    $('div').on('click', function(){
        if ($(this).hasClass("current")){
            return;
        }

        alert("The not 'current' div has been clicked.")
        var aux = $(this);
        $('div').removeClass('current');
        aux.addClass('current');
    });
});

Upvotes: 1

Related Questions