javascript – How to remove the class for a block when it is clicked again?

Question:

Hello! There are blocks (each has its own id), when clicked, the corresponding class is added to them. We clicked on block number 1, a class was added to it. They clicked on block No. 2, a class was added to it, while the class was removed from block No. 1. This is all true. But it is necessary that when you click on the block again, the class is removed from the block, i.e. clicked on block No. 1, the class was added, clicked again – the class was deleted. Help me please.

$(document).ready(function(){
    $('.map-marker').on('click', function() {
        var $me = $(this);
        var id = $me.data("id");

    var $tab = $('.map-marker[data-id=' + id + ']');
    var $tabBody = $('.map-bubble[data-id = ' + id + '-content]');

        $('.map-marker').removeClass('is-open');
        $('.map-marker[data-id=' + id + ']').addClass('is-open');

        $('.map-bubble').removeClass('is-visible');
        $('.map-bubble[data-id = ' + id + '-content]').addClass('is-visible');

    });
});

Answer:

In this case, you need to use toggleClass on two elements at once: the currently active one and the one that was clicked on. You can use the add method to merge

For example like this:

$(document).ready(function(){
    $('.map-marker').on('click', function() {
        var $me = $(this);
        var id = $me.data("id");

    var $tab = $('.map-marker[data-id=' + id + ']');
    var $tabBody = $('.map-bubble[data-id = ' + id + '-content]');

        $('.map-marker.is-open').add(this).toggleClass('is-open');

        $('.map-bubble.is-visible').add('.map-bubble[data-id = ' + id + '-content]').toggleClass('is-visible');

    });
});
Scroll to Top
AllEscort