简体   繁体   中英

Toggle class on div = Untoggle class on another div

I have some divs (#div1, #div2, #div3) that change appearence on click, they toggle a class using this script:

$(document).ready(function() {
    $("#parent_div").on('click', '.current_class', function () {
        $(this).toggleClass("new_class");
    });
});

Now I want the the divs to be unable to toggle at the same time, so they work kinda like a radio-button with same "name" .

Example: Imagine three divs that looks the same (default class), then you click on one of the divs (example #div1) and that one toggles a new class and change appearence. Now you click on one of the other two and this one also change appearence (toggle class), at the same time when this one change appearence #div1 changes back to the default class.

So there can only be one div of those three that toggles the new class at once.

Is this possible?

You first need to remove the class from all the divs, and then add it to the current one. Try this:

$("#parent_div").on('click', '.current_class', function () {
    $('#parent_div .new_class').removeClass('new_class'); // remove exisiting
    $(this).addClass("new_class"); // add to current
});

Update

Added functionality to remove class from current:

$("#parent_div").on('click', '.current_class', function () {
    var $this = $(this);
    if (!$this.hasClass('new_class')) {
        $('#parent_div .new_class').removeClass('new_class');
        $this.addClass("new_class");
    }
    else {
        $this.removeClass("new_class");
    }
});

Use:

$(document).ready(function() {
    $("#parent_div").on('click', '.current_class', function (){
        if($(this).hasClass('.new_class')){
            $(this).removeClass('.new_class');
        }else {
            $('.new_class').removeClass('.new_class');
            $(this).addClass('.new_class');
        }
    });
});

Updated : Code now allows for toggling of current element with class .new_class .

This would be possible, but you'll need to reset all the other divs manually.

An example would be :

I have 3 divs available with id's div-1, div-2 and div-3. I'm using a default class 'default' and a definition class so i can click them 'clickable', and my other class would be 'selected'.

To implement this you would need to do the following:

$(document).ready(function()  {
    $('#parent-div').on('click, 'clickable', function() {
        $('.selected').removeClass("selected").addClass("default");
        $(this).addClass("selected");
    })
});

I hope this helps. I didn't have the possibility to check if the syntax is exactly correct, but I believe this does the job as required.

Kind regards, NDakotaBE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM