Use jQuery to duplicate an image that has the "active" class, then assign it as the background image for a div element

I am utilizing the default carousel from Twitter Bootstrap to create a basic slider. What I aim to do is, when an item becomes active, the image inside that item should be duplicated and set as the background image for the div with the 'testimonials-bg' class.

Although I have attempted the following code, it does not seem to be functioning correctly:

$("#testimonial-carousel .item.active").each(function() {

      var $myBg  = $(".testimonial-bg", this),
          $myImg = $(".testimonial-img img", this);

      $myBg.css({backgroundImage: "url('"+ $myImg[0].src +"')"});

    });

I have created a Fiddle demonstrating this issue:
https://jsfiddle.net/4t17wxxw/

Answer №1

To update the background image to match the active item, subscribe to the slid.bs.carousel event:

var $myBackground = $(".testimonial-background");

$('#carousel-testimonials').on('slid.bs.carousel', function () {
    var $image = $('img','.carousel-inner> .item.active');
    $myBackground.css({backgroundImage: "url('"+ $image[0].src +"')" });
    console.log($image[0].src);   
});

View functional example here

Answer №2

When your code is initially run at the start of a script, it may not be sufficient if you want it to run every time the slide changes. In that case, subscribing to the 'slid.bs.carousel' event can be useful as it triggers each time a new slide is displayed in the carousel.

For more information about this event, you can refer to: http://getbootstrap.com/javascript/#carousel-events.

// Update Testimonial Background based on active slide
$('#testimonial-carousel').on('slid.bs.carousel', function () {
  $("#testimonial-carousel .item.active").each(function() {
      var $myBg  = $(".testimonial-bg", this),
          $myImg = $(".testimonial-img img", this);

      $myBg.css({backgroundImage: "url('"+ $myImg[0].src +"')"});

    });
});

Answer №3

There isn't a class named "testimonial-bg" available. Here is the code that should be used for each slide rotation or when assigning a background image.

$("#testimonial-carousel .item.active").each(function() {
    $(this).css("background", "url('"+$(this).find(".testimonial-img img").attr('src')+"')" );
});

Check out the demo on Fiddle here

Cheers

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The children routes in my Vue application are failing to render their content once resolved, instead opting to render the parent view

I've gone through the entire process again, cleaning up the code a bit (I'm still learning Vue so my code might be a bit messy) but I can't seem to get the component for the child path to render. It always defaults to the parent path. This ...

Ways to achieve an arched shadow effect for an image using React and Tailwind CSS?

Looking to add a unique touch to my React project with a shadow effect resembling an arch shape at the top of an image using Tailwind CSS. The ultimate goal is to create a semi-transparent arch-shaped shadow covering the top portion of the image, similar t ...

Why isn't the npm table populating the command line interface table?

I attempted to create a command line table using npm table, but encountered issues with it. Here is my code and an explanation. const {table} = require('table'); let data; let output; data = [['id','product','name&apos ...

Tips for transferring a boolean value to a generic parameter in Java?

Looking to pass a boolean value to the Generic type in order to be utilized within a condition. This is the generic type interface OptionTypeBase { [key: string]: any; } type OptionsType<OptionType extends OptionTypeBase> = ReadonlyArray<Opt ...

Positioning a block element following an inline-block element

I am in possession of the following HTML code: <div id="wrapper"> <div class="inline-block"></div> <div class="inline-block"></div> <div class="inline-block"></div> <div class="block"></di ...

Conceal the standard style class of the p:selectOneRadio element

On my xhtml page, I've implemented p:selectOneRadio. However, I'm struggling to remove the default style class .ui-helper-hidden-accessible, resulting in the radio button icons not being visible. Here's a snippet of my code: <p:selectOne ...

Locking mat-toolbar and mat-tabs to the top in Angular Material 2

As I work on my website, my goal is to fix the < Mat-Toolbar > at the top of the screen and then directly underneath that, lock the < Mat-Tabs >. The challenge I'm facing is that the position: fixed in CSS is not working as expected. When ...

Receive a warning in the Heroku log stating "(node) sys is outdated. Util should be used instead" while the script is executed

I recently deployed a Node script on Heroku to be executed by a scheduler. However, upon running the script, I noticed a warning message in the logs. Dec 07 11:01:10 xxx heroku/scheduler.3255 Starting process with command `node bin/script` Dec 07 11:01:1 ...

The issue with the Bootstrap slider persists

The slider function in the downloaded html and css codes from bootstrap is not working properly. When clicking the arrow, the screen drops below instead of sliding. Even though the code was copied directly from bootstrap, the issue persists. <div c ...

Creating a Pyraminx using triangular shapes

Attempting to create a Pyraminx, a tetrahedron made up of multiple triangles, through my coding. The approach I am taking may not be very precise. You can find my code here: https://codepen.io/jeffprod/pen/XWbBZLN. The issue I'm facing is manually in ...

Ways to differentiate between a single date and multiple dates using PHP

Is there a way to compare two dates in PHP? I have two different dates: one is from the database and the other is selected from a Datepicker. $dbdate = 01-06-201402-06-201403-04-201405-06-2014 //DB date $datepickerDate = 06-06-2014 //Datepicker date. ...

Different approach to iterating through elements

Looking to implement .forEach instead of a traditional for loop? 'use strict'; var score = (function(){ function updateScore() { for(var i = 0; i < arguments.length; i++) { this.score += arguments[i]; ...

Include the clicked link into the text input area using Ajax or Jquery

Hey there, I'm just starting out with jquery and ajax so please be patient with me. Below is a snippet of my script that fetches branch names from the database asynchronously: $(document).ready(function () { $("#pickup").on('keyup' ...

Making the child element expand to the full width of its parent while maintaining an overflow-x:auto property

Is there a way to stretch a child div without specifying fixed widths? Even when trying to wrap items and child in one wrapper div, the child div always takes up 100% width. Not full horizontal width. Thank you. .parent { background: skyblue; widt ...

Scrolling with JQuery Sortable will go up in the list, but it won't allow for

My current issue revolves around a problem in JSP, but for better understanding, I have replicated the issue using HTML. The main page involves using sortable to enable drag and drop rearrangement of elements (list items). However, the scrolling behavior i ...

Menu navigation - ensuring the background color extends to cover the entire page, not just the viewport

I'm facing an issue with the left navigation bar's design. Specifically, I'd like the grey color of the bar to extend vertically across the entire page. Currently, the gray bar ends at the viewport's edge. Is there a way to make the ba ...

Mastering the 'wing' corner effect using only CSS

Is there a way to achieve the corner effect shown in this image (top corners)? I'm not familiar with the name of this effect. If it is possible, how would you go about implementing it? Update: Some have suggested that this question is a duplicate. Ho ...

Exploring the seamless integration of Material UI with React version 18

I am having an issue with my background not turning black in React version 18.2.0 when using makeStyles from Material UI version 4. Despite no errors in the code, the background remains unchanged. How can I fix this problem? import './App.css'; i ...

"Exploring the power of Vue.js through dynamic and recursive components

I am struggling with creating a recursive custom component that calls itself. Unfortunately, I keep encountering an error. An unknown custom element: <TestRec> - have you registered the component correctly? For recursive components, ensure to specif ...

I'm struggling to make the jquery parentsUntil function work properly

Would appreciate some help with using the jquery parentsUntil method to hide a button until a radio box is selected. I've been struggling with this for a few days now and can't seem to figure out what I'm doing wrong. Any insights would be g ...