jQuery effects lost after append html to another DIV, - javascript

I have a div inside it has images carousel, and I'd like to append it to another DIV outside. However, I lost carousel on the new div outside. How can I enable carousel for the appended div?
online sample: http://jsfiddle.net/PYQXa/
<div class="inside">
<ul class="slider">
<li>
<img src="http://lorempixel.com/580/250/nature/1"> <!-- random image -->
</li>
<li>
<img src="http://lorempixel.com/580/250/nature/2"> <!-- random image -->
</li>
<li>
<img src="http://lorempixel.com/580/250/nature/3"> <!-- random image -->
</li>
<li>
<img src="http://lorempixel.com/580/250/nature/4"> <!-- random image -->
</li>
</ul>
</div>
<div class="outside">
<!-- append content here -->
</div>
jQuery
var $inside = $('.inside');
$inside.hide();
var appendcontent = $inside.find('.slider').html();
$(appendcontent).appendTo($('.outside'));
// settings
var $slider = $('.slider'); // class or id of carousel slider
var $slide = 'li'; // could also use 'img' if you're not using a ul
var $transition_time = 1000; // 1 second
var $time_between_slides = 2000; // 4 seconds
function slides(){
return $slider.find($slide);
}
slides().fadeOut();
// set active classes
slides().first().addClass('active');
slides().first().fadeIn($transition_time);
// auto scroll
$interval = setInterval(
function(){
var $i = $slider.find($slide + '.active').index();
slides().eq($i).removeClass('active');
slides().eq($i).fadeOut($transition_time);
if (slides().length == $i + 1) $i = -1; // loop to start
slides().eq($i + 1).fadeIn($transition_time);
slides().eq($i + 1).addClass('active');
}
, $transition_time + $time_between_slides
);
it would be working fine if you remove
var $inside = $('.inside');
$inside.hide();
var appendcontent = $inside.find('.slider').html();
$(appendcontent).appendTo($('.outside'));

var appendcontent = $inside.find('.slider').html();
The html() method returns the innerHTML of the jQuery element. In your example, it's a list of <li> nodes. Just replace the line with:
var appendcontent = $inside.find('.slider');

Edit : I've checked the fiddle again, you are appending only the 'li' into the new div. To have it work properly, you should use
$inside.find('.slider');

You were adding the slider class content into the outside class but .. u need to add inside content on outside div otherwise all anim related to slider class will be vanish..
var appendcontent = $inside.find('.slider').html();
var html = $inside.html();
$(html).appendTo($('.outside'));
And the slider need to select like this
var $slider = $('.outside .slider'); // class or id of carousel slider
DEMO

Because the appentcontent doesnt have the class "slider". You shold replace the line
$inside.find('.slider').html();
with
$inside.find('.slider').parent().html();

Related

How to show images on the DOM as they come in using Jquery after the DOM has loaded?

I am trying to add a template to the DOM using jquery. I wait for all the images to be loaded on the DOM, then grab all the images in a particular div, add a template to the DOM(which is a two card grid), and then use .each to loop over all those images and append them using the template to create multiple two card grids.
The issue is that it doesn't show up on the DOM.
Here is the code below:
<script>
function moveImages() {
var $gallery = $('#gallery');
// The template below will only have a 2 card grid. Hence an img counter.
var imgcount = 1;
// Initializing section counter for the 2 card grid. When img counter = 2, we increment it below so that we can have a new section ID to
// append the next two images one by one.
var sectioncount = 0;
//Here is the HTMl template, as the imgcount crosses 2, we create a new section. notice the dynamic variable below for sectioncount.
var template = `<section class="card-grid-section section-${sectioncount}" loading="lazy">
<a class="card-grid-two-image">
<div>
<picture id="card-one-two-grid-section-${sectioncount}">
</picture>
</div>
</a>
<a class="card-grid-two-image">
<div>
<picture id="card-two-two-grid-section-${sectioncount}">
</picture>
</div>
</a>
</section>`;
//getting the html for the article-text id above.
var test = $('#article-text').find('p').each(function(index, value) {
//looping over all the children of each p tag below which are mostly span and img
var children = value.childNodes;
children.forEach(function(item, index1){
// if the tag is a span, then we append it to the div with id gallery.
if(item.tagName == "SPAN"){
$gallery.append(`<p><span>${item.innerHTML}<span></p>`);
console.log("ADDED SPAN TO GALLERY");
}
//if tag is an img
else if(item.tagName == "IMG"){
//I want to skip the first image here
if(imgcount > 0){
if(imgcount == 1){
//appending the template to gallery only if imagecount = 1.
$gallery.append(template);
//item here, is an image. I am adding the first image to the card one of the first grid(template). Notice the sectioncount dynamic variable below.
var $card1 = $(`#card-one-two-grid-section-${sectioncount}`);
//Appending image to card one
$card1.append(item);
} else if(imgcount == 2){
//if image count is 2, we are adding the the second image to template we created above.
var $card2 = $(`#card-two-two-grid-section-${sectioncount}`);
$card2.append(item);
//Since image count is 2, we want a new grid id. Hence the sectioncount++.
sectioncount++;
//since we can only add two images to grid. I am setting imgcount back to 0;
imgcount = 0;
}
}
//Incrementing img count below.
imgcount++;
}
});
});
}
$(document).ready(function($) {
});
</script>
I think you meant to write something like this:
function gridTemplate(section) {
return $(`<section class="card-grid-section section-${section}" loading="lazy">
<a class="card-grid-two-image">
<div>
<picture id="card-one-two-grid-section-${section}"></picture>
</div>
</a>
<a class="card-grid-two-image">
<div>
<picture id="card-two-two-grid-section-${section}"></picture>
</div>
</a>
</section>`);
}
$(function () {
var imgcount = 1, sectioncount = 0;
$('#article-text p > *').each(function () {
if (this.tagName === "SPAN") {
$('#gallery').append(`<p><span>${this.innerHTML}<span></p>`);
} else if (this.tagName === "IMG") {
if (imgcount == 1) {
$('#gallery').append(gridTemplate(sectioncount));
$(`#card-one-two-grid-section-${sectioncount}`).append(this);
imgcount++;
} else {
$(`#card-two-two-grid-section-${sectioncount}`).append(this);
sectioncount++;
imgcount--;
}
}
});
});
(You really should cut back on the comments that say exactly what the code says - they are hugely distracting.)

In pure JS, I am trying to set two similar classes but with different numbers or to set the same class to two different elemnts

I tried to set the same class imagens-giratorias to two elements or to set imagens-giratorias and imagens-giratorias-2. The class worked in first element, and the same class stopped of animating in the second element.
[I provide the JSFiddle at the end.]
Check the #rafaelcastrocouto's original code at https://stackoverflow.com/a/59524483/8041366. If you prefer reading the complete code here, here is the code taken from there, but with a bit modified:
var counter = 1;
var div = document.querySelector('.imagens-giratorias');
var imagens = document.querySelectorAll('.imagens-giratorias img');
var showNext = function () {
counter++;
if (counter > 3) counter = 1;
div.classList.remove('imagem1', 'imagem2', 'imagem3')
div.classList.add('imagem'+counter);
};
for (var img of imagens) {
img.addEventListener('animationend', showNext);
}
And small CSS snippet:
<div class="section-2">
<div class="item-2">
<div class="imagens-giratorias imagem1">
</div>
</div>
</div>
<div class="section-3">
<div class="item-2">
<div class="imagens-giratorias imagem1">
</div>
</div>
Or
<div class="section-3">
<div class="item-2">
<div class="imagens-giratorias-2 imagem1">
</div>
</div>
1st solution, that same original code above I am referring.
2nd solution:
var div = document.querySelector('.imagens-giratorias, .imagens-giratorias-2');
var imagens = document.querySelectorAll('.imagens-giratorias img, .imagens-giratorias-2 img');
3rd solution
var div = document.querySelector('[class^=imagens-giratorias]');
var imagens = document.querySelectorAll('[class^=imagens-giratorias] img');
4th solution
const contador = 1;
const div = document.querySelector('.imagens-giratorias');
const imagens = document.querySelectorAll('.imagens-giratorias img');
I also tried to use from multiple selectors with document.querySelectorAll. No luck.
But all these solutions did not work.
JSFiddle
Please pay attention to two elements. While one element will always animate, another will stop of animating.
https://jsfiddle.net/gusbemacbe/mbp84u6r/2/
If I understand you correctly you're trying to grab elements that have a class name starting with imagens-giratorias. If that's the case, use the ^ attribute selector as shown below:
document.querySelectorAll("[class^="imagens-giratorias"]")
Update:
Based on your update it appears that only one of your two divs' images is animating but in reality they're stacked on top of each of other. Feel free to use whatever layout method you want but for demonstration's sake I floated one left and the other right. Other that it was a matter of looping through your divs and assigning your function to their child images as so:
var divs = document.querySelectorAll('.imagens-giratórias');
var contador = 1;
var mostrarPróximo = function(div) {
contador++;
if (contador > 3) contador = 1;
div.classList.remove('imagem1', 'imagem2', 'imagem3')
div.classList.add('imagem' + contador);
};
Array.from(divs).forEach(function(div, index) {
var images = div.querySelectorAll('img');
Array.from(images).forEach(function(img) {
img.addEventListener('animationend', mostrarPróximo.bind(null, div));
});
});
https://jsfiddle.net/1r6yjf5s/

Isotope appended broke remaining jQuery

I have an instance of Isotope on my website that seems to have broken the remainder of my javascript functions after converting it to use the appended method. When I had all of my images were initially in the markup on my index.html, both isotope's filtering as well as a lightbox plugin I had for each image were working beautifully. Now I have implemented it as follows (using most of Desandro's code for Isotope:
HTML:
<div class="main">
<div id="filters" class="button-group">
<p>FILTER:</p>
<button class="selected" data-filter="*">SHOW ALL</button>
<button class="" data-filter=".photography">PHOTOGRAPHY</button>
<button class="" data-filter=".film">FILM</button>
<button class="" data-filter=".design">DESIGN</button>
</div>
<div class="isotope">
<div class="grid-sizer"></div>
</div>
</div>
Javascript:
$(function() {
var $container = $('.isotope');
$container.isotope({
"itemSelector": ".item",
"columnWidth": ".grid-sizer"
});
function getItemPhotography(i) {
var item = '<div class="item photography"><a class = "fluidbox" href = "img/photography/' + i + 'big.jpg" title = "Click to enlarge"><img src = "img/photography/' + i + '.jpg" class = "image"/></a></div >';
return item;
}
function getItemDesign(i) {
var item = '<div class="item design"><a class = "fluidbox" href = "img/design/' + i + 'big.png" title = "Click to enlarge"><img src = "img/design/' + i + '.png" class = "image"/></a></div >';
return item;
}
var $items = getItems();
// hide by default
$items.hide();
// append to container
$container.append($items);
$items.imagesLoaded().progress(function(imgLoad, image) {
// image is imagesLoaded class, not <img>
// <img> is image.img
var $item = $(image.img).parents('.item');
$item.show();
$container.isotope('appended', $item);
});
function getItems() {
var items = '';
for (var i = 1; i < 38; i++) {
items += getItemPhotography(i);
}
for (var i = 1; i < 4; i++) {
items += getItemDesign(i);
}
// return jQuery object
return $(items);
}
});
This part was broken after adding in the above:
//Filtering for isotope
$(function() {
$('#filters').on('click', 'button', function() {
var filterValue = $(this).attr('data-filter');
$container.isotope({
filter: filterValue
});
});
$("button").click(function() {
// Reset them
$("button").removeClass("selected");
// Add to the clicked one only
$(this).addClass("selected");
});
});
//Fluidbox lightbox plugin
$(function() {
$('.fluidbox').fluidbox();
});
The images are appending to the Isotope container and laying out as expected. However, now filtering is broken for Isotope, and the Fluidbox lightbox instance is not working either.
Thanks so much for any help. I have been struggling with this for the past few hours and am starting to think it may be as simple as my function initializations or a semicolon somewhere.
Resolved. Missing a reference for $container in the function for isotope filters.

issue is with clone, splice, remove, append jquery function

There are multiple images in HTML.
<ul class="ice-navigator">
<li>
<a href="javascript:void(0);" class="thumb" id = "26">
<img src="images/123.png" alt="Title #0" width="75" height="75"/>
</a>
</li>
<li>
<a href="javascript:void(0);" class="thumb" id = "28">
<img src="images/456.png" alt="Title #0" width="75" height="75"/>
</a>
</li>
.
.
.
</ul>
I want to show only 5 images at a time, so i am using this code "onload" to hide image if it is more than 5.
stPt = 0, elToShow = 5; //showing 5 elements
$ul = $('ul.ice-navigator');
$li = $('ul.ice-navigator li'); //get the list of li's
$copy_li = [];
copy_lgt = $li.length - elToShow;
for (var i = elToShow; i < $li.length; i++)
{
var tmp;
tmp = $li.eq(i);
$copy_li.push(tmp.clone());
tmp.remove();
}
To show prev and next, i am using this code.
$('.ice-next').click (function ()
{
$li = $('ul.ice-navigator li'); //get the list of li's
$copy_li.splice(copy_lgt, 0, $li.eq(0).clone() ); //move the 1st element clone to the last position in copy_li
$li.eq(0).remove(); //kill the 1st element in the UL
$ul.append($copy_li.shift()); //add to the last
});
$('.ice-previous').click (function ()
{
$li = $('ul.ice-navigator li'); //get the list of li's
$copy_li.splice(0, 0, $li.eq(elToShow-1).clone()); //move the 1st element clone to the last position in copy_li
$li.eq(elToShow-1).remove();//kill the 1st element in the UL
$ul.prepend($copy_li.pop());//add to the last
});
Everything works fine, except this:
There is one click event associated with thumb class.
jQuery(document).ready(function($) {
$(".thumb").click(function(){
alert ("Reaching here");
)};
)}:
This is working in beginning. but once we have used
$('.ice-previous').click (function () or $('.ice-next').click (function ()
then
$(".thumb").click(function(){ is not working.
I mean now click on image will not print Reaching here.
What is causing this issue??
Because you are removing and re-attaching DOM elements, you need to delegate your events on those elements like this:
$('.ice-navigator').on('click', '.thumb', function() {
alert('Reaching here');
});
More info: http://api.jquery.com/on/

Carousel with image map linked to next image

The long and short of it is I'm trying to use a carousel, and instead of using next and previous buttons to navigate to other images, I want to use image mapping to link to other images. I'm quite stuck, so I appreciate any advice!
My carousel is from this site's tutorial (https://christianheilmann.com/2015/04/08/keeping-it-simple-coding-a-carousel/
). Here's my html code:
<ol class="content">
<li>
<img src="http://lorempixel.com/200/200" alt="mag" usemap="#map" class="img-responsive">
<map name="map">
<area shape=poly coords="500,80,1080,80,1080,550,500,550" href="img2" title="vent1" > <!--where should href link to?? -->
</map>
</li>
<li><img src="http://lorempixel.com/199/200" alt="2"></li>
<li><img src="http://lorempixel.com/200/199" alt="3"></li>
</ol>
My javascript:
carousel = (function(){
// Read necessary elements from the DOM once
var box = document.querySelector('.simbox');
var next = box.querySelector('.next');
var prev = box.querySelector('.prev');
// Define the global counter, the items and the
// current item
var counter = 0;
var items = box.querySelectorAll('.content li');
var amount = items.length;
var current = items[0];
box.classList.add('active');
// navigate through the carousel
function navigate(direction) {
// hide the old current list item
current.classList.remove('current');
// calculate the new position
counter = (counter + direction) % amount;
counter = counter < 0 ? amount - 1 : counter;
// set new current element
// and add CSS class
current = items[counter];
current.classList.add('current');
}
// add event handlers to buttons
next.addEventListener('click', function(ev) {
navigate(1);
});
prev.addEventListener('click', function(ev) {
navigate(-1);
});
// show the first element
// (when direction is 0 counter doesn't change)
navigate(0);})();
You asked "where should href link to?"
you can link it to href="javascript:navigate(1)" that way, when you click on the area, it will fire the navigate(1) function that will cause the carousel go to the next item.

Categories

Resources