Martin
Martin

Reputation: 207

Changing links dynamically with jQuery

Is it possible to check whether an li has a specific class and then change an attribute.

<ol class="carousel-indicators">
    <li class="active" data-slide-to="0" data-target="#carousel"></li>
    <li data-slide-to="1" data-target="#carousel"></li>
    <li data-slide-to="2" data-target="#carousel"></li>
</ol>

When an li is displayed it will add class=active as shown in the example below.

<li data-slide-to="2" data-target="#carousel" class="active"></li>

I want to target the class and then change the dynamically.

$("#carousel-link").attr("href", "http://www.w3schools.com/jquery");

For example if if li data-slide-to="1" is actve I want to change the link dynamically by using $("#carousel-link").attr("href", "http://www.w3schools.com/jquery");

For example if if li data-slide-to="2" is actve I want to change the link dynamically by using $("#carousel-link").attr("href", "http://www.w3schools.com/php");

Upvotes: 0

Views: 103

Answers (2)

WonderGrub
WonderGrub

Reputation: 396

If I understand correctly, I don't think you want to look for which slide is active. You actually want to bind to the carousel's events.

Bootstrap Carousel Events

Bootstrap's carousel class exposes two events for hooking into carousel functionality.

Both events have the following additional properties:

  • direction: The direction in which the carousel is sliding (either "left" or "right").
  • relatedTarget: The DOM element that is being slid into place as the active item.

All carousel events are fired at the carousel itself (i.e. at the <div class="carousel">).

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

You'll likely want to use the "slide" event, then handle the change within the callback function.

$('#carousel').on('slide.bs.carousel', function () {
  // handle update here
})

One thing confuses me about your code. Do you need to update the "href" value or can it simply be set when the slide is built? The above solution is great if you are determining the "href" dynamically on slide change. But, if you know what the value should be when the page loads, it would be much easier to just set it.

 

EDIT: Updating "href" of target slide

Based on your structure, you can update the "href" of the upcoming slide like this:

$('#carousel').on('slide.bs.carousel', function (event) {
    $(event.relatedTarget).find('a').attr('href', 'your-new-url');
})

Upvotes: 0

andreini
andreini

Reputation: 198

In your HTML code you have an end tag

</section>

but there is no

<section>

that precedes it. Make sure this is fixed and see if the problem persists.

Upvotes: 1

Related Questions