Change bgcolor according to class

1

For now I do not have much knowledge in JS and I would like to ask a question ...

I need to change bgcolor according to the 'active' class. For example: "if the active class is in conjunction with 'banner-bg-1', the color of the body will be 'orange'"

Here is the sample code:

link

    
asked by anonymous 09.03.2018 / 12:16

2 answers

1

Maybe you can do this, instead of checking the active class in the element, you can directly pick up the slide event which element is active, and setting a data-attribute in html you can determine which color is related to each item. so you do not need to change your javascript to each different color, just hit the data-bg in html.

$(document).ready(function() {
  //seta fundo referente a ao item active por default.
  trocaFundo("orange");

  $('#banner').on('slide.bs.carousel', function(ev) {
    $('body').addClass('animating');
    trocaFundo(ev.relatedTarget.dataset.bg);
  });

  function trocaFundo(color) {
    $('body').css({
      background: color
    });

  }
});
body.animating {
  background: "orange";
  transition: background .7s ease-out;
}

.carousel-inner {
  height: 250px;
}

.carousel-indicators {
  text-align: center;
  bottom: 0;
  right: 0;
  left: 0;
  width: 100%;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
<div class="col-md-8 carousel slide" id="banner" data-ride="carousel">
  <div class="carousel-inner">
    <div class="item banner-bg-1 active" data-bg="orange">
      <div class="col-md-offset-7 col-md-5">
        <div class="banner-texto">
          <h1>orange/laranja</h1>
        </div>
      </div>
    </div>
    <div class="item banner-bg-2" data-bg="gray">
      <div class="col-md-offset-7 col-md-5">
        <div class="banner-text">
          <h1>grey/cinza</h1>
        </div>
      </div>
    </div>
    <ol class="carousel-indicators">
      <li data-target="#banner" data-slide-to="0" class="banner-li-1 active"></li>
      <li data-target="#banner" data-slide-to="1" class="banner-li-2"></li>
    </ol>
  </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
    
09.03.2018 / 12:49
1

The slid.bs.carousel event occurs after the slide is active.

$('#banner').on('slid.bs.carousel', function (ev) {
    mudaBG();
});
    
09.03.2018 / 12:32