jyoon jyoon - 3 months ago 14
jQuery Question

How to change the background-color of the parent class by jquery

Hi I'm trying to make a bootstrap carousel with

.carousel-indicators
positioned
relative
.
However, because of this, I cannot set the
background-color
of each carousel item different

since it can't be applied to the upper part where indicators are positioned.

So I am trying to apply the
background-color
attribute to the parent class instead.

This is my HTML code:

<div id="carousel-example-generic" class="carousel slide" data-ride="carousel" data-interval="false">

<!-- Wrapper for slides -->
<div class="carousel-inner" role="listbox">

<!-- Indicators -->
<ol class="carousel-indicators text-left">
<li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
<li data-target="#carousel-example-generic" data-slide-to="1"></li>
<li data-target="#carousel-example-generic" data-slide-to="2"></li>
<li data-target="#carousel-example-generic" data-slide-to="3"></li>
</ol>

<div id="item0" class="item active">
</div>
<div id="item1" class="item">
</div>
<div id="item2" class="item">
</div>
<div id="item3" class="item">
</div>
</div>
</div>




And below is the jQuery code that I've tried,

But it doesn't work and I'm wondering why.




$(document).ready(function () {
if ($("#item2").hasClass('active')) {
$(".carousel-inner").css('background-color, '#d4ddde');
}
else {
$(".carousel-inner").css('background-color, 'none');
}
});





I edited the jQuery grammar but still doesn't work.

Answer

The thing is, your code is executed just one time at the opening of your page. So when the carousel slides, and Bootstrap adds the active class to his items, you code is not re-executed. You have to use the callbacks functions that provide you Bootstrap.

The Bootstrap's carousel plugin fire 2 events when the slides move :

  • slide : This event fires immediately when the slide instance method is invoked.
  • slid : This event is fired when the carousel has completed its slide transition.

So if you want to watch what's happened during the transition or if you want to add a class to whatever you want, you may want to use these events.

Let's see the code :

This is how you can add and watch these events with jQuery :

$('#carousel-example-generic').on('slide', function() {
    //Do something before the animation
});

$('#carousel-example-generic').on('slid', function() {
    //Do something after the animation
});​​

In your case :

This code below should fix your problem :

$(document).ready(function () {
    $('#carousel-example-generic').on('slide', function() {
        if ($("#item2").hasClass('active')) {
            $(".carousel-inner").css('background-color, '#d4ddde');
        }
        else {
            $(".carousel-inner").css('background-color', 'none');
        }
    });
});

Here's official bootstrap's carousel doc : http://getbootstrap.com/2.3.2/javascript.html#carousel

Comments