Z
Z
zhyshy2019-05-27 16:22:36
JavaScript
zhyshy, 2019-05-27 16:22:36

How to change the class of another element when changing the class of one element?

Good afternoon!
There is a standard carousel on Bootstrap 4, in the carousel there are 2 pictures - dark and light.

<div class="carousel-item night-bg"></div>
<div class="carousel-item day-bg active"></div>

How can I add some additional class when changing a slide and assigning a class, for example "night-bg active", to another element, not from the carousel, and remove this class when "day-bg active"?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Usachov, 2019-05-27
@zhyshy

Bootstrap 4 carousels have events that can and should be used. To better tailor events to your needs, read the documentation, it is not hidden on the web. It should look something like this:

$('.carousel').on('slide.bs.carousel', function(event) {
  var slideIndex = event.to, // индекс слайда, к которому переходим
    activeSlide = $('.slide').eq(slideIndex), // активный слайд
    myOuterElem = $('.my-outer-element'); // некий элемент вне карусели

  if(activeSlide.hasClass('night-bg')) {
    myOuterElem.addClass('my-new-class'); // добавляем класс к внешнему элементу если ночь
  } else
  if(activeSlide.hasClass('day-bg')) {
    myOuterElem.removeClass('my-new-class'); // убираем класс у внешнего элемента если день
  }
});

R
Rsa97, 2019-05-27
@Rsa97

Option 1: Find where the class changes and add another element's class change.
Option 2: MutationObserver

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question