V
V
valgerofficial2021-06-05 20:36:22
JavaScript
valgerofficial, 2021-06-05 20:36:22

How to switch classes for several buttons at once?

There are 3 buttons with icons, by clicking on one of them, instead of the previous icon, an icon with a cross appears. But here's the problem, if you click on another button, then the previous button does not change its property (that is, the cross is not replaced by the previous icon). And the question is how to change the class of the previous icon by clicking on another button? That is, for each icon, the icon should change to a cross, and the previous button should be deleted.

<!-- Кнопки -->
<div class="header__button">
  <button class="btn header__basket_btn"><i class="feather-shopping"></i></button>
        <button class="btn header__search_btn"><i class="feather-search"></i></button>
  <button class="btn header__user_btn"><i class="feather-user"></i></button>
</div>

The class should change from .feather-shopping to .feather-close.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Malmind, 2021-06-05
@Malmind

As far as I understood the task, you need to make one choice from 3 buttons and the button that the user clicked has one picture, and the rest have another at this time.
I solved this not through classes, but by cloning elements and templates (template tag).
https://codepen.io/qmalmind/pen/yLMjPBg
To work with classes, they usually use:

someVar.classList.add("someClass"); // Добавляет класс
someVar.classList.remove("someClass"); // Убирает класс 
someVar.classList.toggle("someClass"); // По очереди добавляет, убирает

S
Sergio, 2021-06-06
@sergiodev

Alternatively, you can add a .feather-close icon inside each button, hidden by default, and on click on the button, show this icon and hide the original icon:

<!-- HTML -->

<div class="header__button">
    <button class="btn header__basket_btn">
        <i class="icon feather-shopping"></i>
        <i class="close-icon feather-close"></i>
    </button>
    <button class="btn header__search_btn">
        <i class="icon feather-search"></i>
        <i class="close-icon feather-close"></i>
    </button>
    <button class="btn header__user_btn">
        <i class="icon feather-user"></i>
        <i class="close-icon feather-close"></i>
    </button>
</div>

/* CSS */

.header__button .btn .close-icon {
    display: none;
}
.header__button .btn.close .icon {
    display: none;
}
.header__button .btn.close .close-icon {
    display: inline;
}

// JavaScript

$('.header__button .btn').click(function() {
    $(this).toggleClass('close');
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question