Home > Back-end >  Bootstrap Carousel wont work on dynamically created elements from JS
Bootstrap Carousel wont work on dynamically created elements from JS

Time:12-15

I'm trying to create a social media type feed like LinkedIn where each div element is a carousel that displays images just like a social media feed. In JS, based on the response from API I dynamically create the following element with images for the carousel:

  <div   data-bs-ride="carousel">
    <div >
      <div >
        <div > <img src="company_logo.jpg" alt="company_logo"></div>
        <div >
          <h3>Company Name</h3>
        </div>
      </div>
      <div >
        <img src="linkedin_logo.png" alt="linked-in_logo">
      </div>
    </div>
    <p >Caption for social media post</p>
    <div >
      <div >
        <img src="img.jpg"  alt="...">
      </div>
      <div >
        <img src="img.jpg"  alt="...">
      </div>
      <div >
        <img src="img.jpg"  alt="...">
      </div>
    </div>

Above snippet is dynamically created from JS and displays as Social media post which holds company logo, name, caption and images which display as carousel. I've used the following cdn to include Bootstrap:

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL jjXkk Q2h455rYXK/7HAuoJl 0I4" crossorigin="anonymous"></script>  

The problem is that bootstrap carousel just doesn't work on the above dynamically rendered element. If I hardcode the above snippet directly into the html body, the carousel starts working, but it won't work on the same snippet that is dynamically generated. I checked in Chrome dev tools, the dynamically generated element is the exact same as the hardcoded element but it only works for the latter. I've tried to fiddle with "data-bs-ride=carousel" attribute but that doesn't help. I'm new to Bootstrap so I don't have many solutions. Any input will really help me.

EDIT: Script function that appends carousel slides to body

function Posts1(obj){
requestBody.companyId=obj.companyId;
requestBody.accessToken=obj.accessToken;
console.log(requestBody);
const options={
    method:'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: requestBody
}
var xmlhttp = new XMLHttpRequest();   // Get Ugc Posts api call 
theUrl = "https://localhost:44346/api/GetUgcPosts";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify(requestBody));
xmlhttp.onload=()=>{
    if(xmlhttp.status==200){
        let i=0;
        data=JSON.parse(xmlhttp.response);
        data.post.slice().forEach(element => {
            const linkedin_sec=document.createElement('div');
            linkedin_sec.className="carousel slide";
            linkedin_sec.setAttribute("data-bs-ride","carousel")
            let link="";
            let caption="";           
            const pfp_name='<div ><div ><div > <img src="' data.pfp '" alt="user_avatar"></div><div ><h3>' data.orgName '</h3></div></div><div ><img src="/img/linkedin.png" alt="linked-in_avatar"></div></div>';                
            if(element.caption.includes('https')){
                link=element.caption.split('https')[1].split(' ')[0];
                caption='<p >' element.caption '</p><a href="https' link '">Follow Link</a>'
            }
            else{
                caption='<p >' element.caption '</p>'
            }
            const slides=document.createElement('div');
            slides.className="carousel-inner";
            let i=0;
            element.imgUrl.forEach(img=>{
                
                const imgSlide='<div ><img src="' img '"  alt="..."></div>';
                i  ;
                slides.insertAdjacentHTML("afterbegin",imgSlide);
            })
            if((element.imgUrl[0])&&(element.imgUrl.length>1)){
            }
            
            linkedin_sec.innerHTML=pfp_name caption;
            linkedin_sec.appendChild(slides);
            document.body.insertBefore(linkedin_sec, document.body.firstChild);
    })
    }
    else{
        console.log("Error")
    }
    
}

}

Also added the following script

<script>
$(window).load(function(){
$('.carousel').carousel({
  interval:1000
});
console.log("window is loaded");
})
</script>

CodePudding user response:

Please check this

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=\, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
    <title>Document</title>
</head>

<body>
    <div  data-bs-ride="carousel">
        <div >
            <div >
                <div > <img src="https://images.unsplash.com/photo-1599305445671-ac291c95aaa9?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8TE9HT3xlbnwwfHwwfHw=&auto=format&fit=crop&w=500&q=60" alt="company_logo"></div>
                <div >
                    <h3>Company Name</h3>
                </div>
            </div>
            <div >
                <img src="https://images.unsplash.com/photo-1611944212129-29977ae1398c?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8TElOS0VESU58ZW58MHx8MHx8&auto=format&fit=crop&w=500&q=60" alt="linked-in_logo">
            </div>
        </div>
        <p >Caption for social media post</p>
        <div >
            <div >
                <img src="https://images.unsplash.com/photo-1520209759809-a9bcb6cb3241?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1470&q=80"  alt="...">
            </div>
            <div >
                <img src="https://images.unsplash.com/photo-1520209759809-a9bcb6cb3241?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1470&q=80"  alt="...">
            </div>
            <div >
                <img src="https://images.unsplash.com/photo-1520209759809-a9bcb6cb3241?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1470&q=80"  alt="...">
            </div>
        </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL jjXkk Q2h455rYXK/7HAuoJl 0I4" crossorigin="anonymous"></script>  
</body>

</html>

CodePudding user response:

I think I may have done a very silly mistake here. So the bootstrap carousel now applies to all the elements static as well as dynamic. All I had to do was move the following jQuery snippet from the html file to the my script.js at the end after all the dynamic elements are appended to the html body.

<script>
      $(window).load(function(){
      $('.carousel').carousel({
      interval:1000
    });
    console.log("window is loaded");
  })
</script>
  • Related