I have a div which contains a lot of big sized images, and with JavaScript I'm trying to insert this HTML in another div with toggle
Please run the code snippet
$(".toggleimages").on("click", function(e) {
e.preventDefault();
var sele = document.querySelector(".bgcontainer");
var colocontainer = '<div class=container><span class=bgImage><span style="background-image:url(https://www.gamewallpapers.com/img_script/wallpaper_dir/img.php?src=wallpaper_destiny_2_02_2560x1440.jpg&height=450&width=800&fill-to-fit)"></span> </span><span class=bgImage><span style="background-image:url(https://www.gamewallpapers.com/img_script/wallpaper_dir/img.php?src=wallpaper_skull_and_bones_01_2560x1440.jpg&height=450&width=800&fill-to-fit)"></span></span></div>'
sele.insertAdjacentHTML('beforeend', colocontainer)
$(".bgcontainer").slideToggle();
});
li{
list-style-type: none;
font-size: 35px;
cursor: pointer;
}
span{
display: inline-block;
width: 200px;
height: 140px;
background-size: cover;
}
.bgcontainer{
display: none;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="toggleimages"><i class="fa fa-picture-o" aria-hidden="true"></i></li>
<div class="bgcontainer"></div>
My problem is that the div renders each time you toggle the button
How can I prevent the HTML from inserting twice? Or insert and remove on toggle?
Why insert on toggle?: The div is hidden by default, and this is used only IF i wanted to select some background images, So i find it really bad for page speed if all of this big images to render everytime you load the page, instead with javascript I want to insert the html on toggle.
sele.insertAdjacentHTML('beforeend', '')insert the emty html.. so every time your fresh html append...