jQuery lazyload on carouFredSel - javascript

Im using jquery lazyload to load my images
but a part of my website has carouFredSel
when i click on next button the next images are not loaded because require to scroll the page, so is there any way to get images loaded on every slide?
jQuery(".foo4").carouFredSel({
auto: !1,
prev: ".prev4",
next: ".next4",
pagination: ".pager4",
mousewheel: !0,
swipe: {
onMouse: !0,
onTouch: !0
}
}),
above code is the javascript to slide the carousel and below I have my lazyscript
jQuery("img.lazy").lazyload();
Any help is very appreciated!

In carouFredSel, you provide the image url in data-src like
<img data-src="image-url"/>
So to show the image in you need to configure, in OnBefore of carouFredSel like.
scroll: {
onBefore: function( data ) {
var $current = data.items.visible.first(),
visible = data.items.visible,
src = visible.data('src');
visible.attr('src', src);
}
}
Add this lines in your carouFredSel code like
jQuery(".foo4").carouFredSel({
auto: !1,
prev: ".prev4",
next: ".next4",
pagination: ".pager4",
mousewheel: !0,
swipe: {
onMouse: !0,
onTouch: !0
},
scroll: {
onBefore: function( data ) {
var $current = data.items.visible.first(),
visible = data.items.visible,
src = visible.data('src');
visible.attr('src', src);
}
}
});

I believe I solved this issue for lazy loading images with caroufredsel
$('#youtube-playlist').carouFredSel({
width: '100%',
height: "variable",
circular: false,
infinite: false,
responsive: true,
items: {
visible: {
min: 2,
max: 4
}
},
onCreate: function(data) {
// Swap data-src for first 4 items
// console.log(data);
$(this).find("img[data-src]").each(function (i, item) {
$(this).attr('src', $(this).attr('data-src')).removeAttr('data-src');
return i < data.items.length-1;
});
},
scroll: {
onBefore: function(data) {
// Lazyload next visible thumbnails
// console.log(data.items.visible.length);
for ( i = 0; i < data.items.visible.length; i++ ) {
var $img = data.items.visible.eq(i).find('img');
$img.attr('src', $img.attr('data-src') ).removeAttr('data-src');
}
}
},
align: 'center',
auto: false,
prev: '#prev',
next: '#next'
});
onCreate : find first visible images and swap data-src to src attribute.
Scroll onBefore : Iterate through the next visible items and swap attributes.
Inspect the Network [filter img] tab in chrome dev tools and watch as the lazyload happens.
I tried adding a width value to my items to remove the console log notice from caroufredsel but it doesn't like the lazyload onCreate.

Related

How do I get the current element id which triggered horizonSwiper event in javascript?

I have implemented horizonSwiper in my php(Yii2) website for loading images of one album in one row with left and right scroll as well as swipe and having multiple albums in that page each have different id. And now I need to add lazyloading when scroll to left/right or swipe to left/right. But I didn't get the current selected div id to find the scrolling images album id.
I have used the following link for implementing swiper,
http://horizon-swiper.sebsauer.de/
And my javascript code as follows,
$('.horizon-swiper.fix-item-width').horizonSwiper({
showItems: 7,
arrows: true,
onSlideStart: function(){
alert('slide started');
},
onDragStart: function(){
alert('drag started');
}
});
I have added my album id with one '.horizon-swiper.fix-item-width' div and to get that inside onSlideStart and onDragStart function
My html is like follows,
<div class="horizon-swiper fix-item-width" id="alb_<?php echo $album['albumId']; ?>">
<div class="horizon-item" data-horizon-index="0" id="img_<?php echo $album['albumId']; ?>_<?php echo $count; ?>">
<div class="card view view-second">
<img class="img responsive " src="<?php echo $baseurl; ?>/images/uploaded_images/profile/<?php echo $img['img']; ?>" width="100%;" height="350px;">
</div>
</div>
</div>
Please note that this html is in a for loop
Can anyone help to find out one solution for this?
Thank you in advance...
I have seen the source code horizon-swiper.js. But as far as I think It doesn't have any functionality by which you can get the reference of current element on which swiper is going on (Sorry I may be wrong, I didn't have enough time to check it deeply). So I have slightly modified the horizon-swiper.js file, and now you can get the reference of current element on which swiper is going on.
in top of horizon-swiper.js file replace
var settings = {
// Default settings
item: '.horizon-item',
showItems: 'auto',
dots: false,
numberedDots: false,
arrows: true,
arrowPrevText: '',
arrowNextText: '',
animationSpeed: 500,
mouseDrag: true,
// Methods and callbacks
onStart: function onStart() {},
onEnd: function onEnd() {},
onSlideStart: function onSlideStart() {},
onSlideEnd: function onSlideEnd() {},
onDragStart: function onDragStart() {},
onDragEnd: function onDragEnd() {},
};
with
var settings = {
// Default settings
item: '.horizon-item',
showItems: 'auto',
dots: false,
numberedDots: false,
arrows: true,
arrowPrevText: '',
arrowNextText: '',
animationSpeed: 500,
mouseDrag: true,
// Methods and callbacks
onStart: function onStart() {},
onEnd: function onEnd() {},
onSlideStart: function onSlideStart() {},
onSlideEnd: function onSlideEnd() {},
onDragStart: function onDragStart() {},
onDragEnd: function onDragEnd() {},
currentElm:""
};
I have just added one more value in settings object named "currentElm"
and add following function
Plugin.prototype.getElem=function(){
this.settings.currentElm=this.$element;
}
after Plugin.prototype.init function
and replace
Plugin.prototype.init = function () {
var that = this;
that._setWrapper();
that._addArrows();
that._addDots();
that._mouseDrag();
that._setSizes();
that._resize();
that._checkPosition();
that.initialized = true;
};
with
Plugin.prototype.init = function () {
var that = this;
that._setWrapper();
that._addArrows();
that._addDots();
that._mouseDrag();
that._setSizes();
that._resize();
that._checkPosition();
that.getElem(); //call here our newly made function
that.initialized = true;
};
Now you can get the reference of element like following.
$('.horizon-swiper.fix-item-width').horizonSwiper({
arrows: true,
dots:true,
onSlideStart: function(){
console.log($(this)[0].currentElm.attr('id'));
},
onDragStart: function(){
}
});
ensure that you have id attribute for each div.
I hope this will help.

slick slider will not instantiate when content is loaded via ajax

What I am trying to do is load in a portfolio item on the click of a div that pertains to that portfolio item. It will load the portfolio single page and populate the view. However the slick slider is not being instantiated and does not work when loaded via ajax.
This is the code that instantiates the slick slider (usually wrapped in $(document).ready. If I enter it in the console after it the ajax gets loaded it works, however if I add it to the end of the .click() function (which will load the content via ajax) it seems to not be intantiated - and nothing in the console to tell me why not:
$('.slick-slider').slick({
lazyLoad: 'ondemand',
centerMode: true,
centerPadding: '60px',
variableWidth: true,
speed: 300,
slidesToShow: 1,
adaptiveHeight: true,
responsive: [
{
breakpoint: 1024,
settings: {
slidesToShow: 3,
slidesToScroll: 3,
infinite: true,
dots: true
}
},
{
breakpoint: 600,
settings: {
slidesToShow: 2,
slidesToScroll: 2
}
},
{
breakpoint: 480,
settings: {
slidesToShow: 1,
slidesToScroll: 1
}
}
// You can unslick at a given breakpoint now by adding:
// settings: "unslick"
// instead of a settings object
]
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Then here is my code for the click of
$(document).ready(function() {
$('#gallery-view > div').click(function() {
var toLoad = $(this).attr('id')+' #portfolio-single';
$('#ajax-view').hide('fast',loadContent);
$('#load').remove();
$('#ajax-wrapper').append('<span id="load">LOADING...</span>');
$('#load').fadeIn('normal');
//window.location.hash = $(this).attr('id').substr(0,$(this).attr('href'));
function loadContent() {
$('#ajax-view').delay(1000).load(toLoad,'',showNewContent());
}
function showNewContent() {
$('#ajax-view').show('normal',hideLoader());
}
function hideLoader() {
$('#load').delay(1000).fadeOut('normal');
}
});
});
The link for which I am trying to accomplish this can be found at:
http://april.philiparudy.com/gallery/
If you click on a div with a circle image you will see it loading without slick slider.
I have the single slick slider working here: http://april.philiparudy.com/portfolio/abby-warner/
Is there some type of callback function I could be running to instantiate the slick slider after ajax is loaded?
Your code it's almost ok. The problem is you are assigning the click to the #gallery-view > div.
You must get an existing element, not an element you have added after the function click.so try to change that and get the parent or show me the ajax call to see where are you adding the new item.
Also change the click to onclick and the functions should not be inside the $(document).ready
Take a look below.
$(document).ready(function() {
$('#gallery-view > div').on('click', function() {
var toLoad = $(this).attr('id')+' #portfolio-single';
$('#ajax-view').hide('fast',loadContent);
$('#load').remove();
$('#ajax-wrapper').append('<span id="load">LOADING...</span>');
$('#load').fadeIn('normal');
});
});
function loadContent() {
$('#ajax-view').delay(1000).load(toLoad,'',showNewContent());
}
function showNewContent() {
$('#ajax-view').show('normal',hideLoader());
}
function hideLoader() {
$('#load').delay(1000).fadeOut('normal');
}
Hope it's helps!

CarouFredSel add content dynamically

I try to add content on the fly to a CarouFredSel slider. The content is inserted fine but CourFredSel does not recognize the new content. Is there a way to tell the slider that the slide count has changed?
jQuery(document).ready(function() {
jQuery('#carousel').carouFredSel({
items: 4,
direction: "left",
responsive: true,
infinite: false,
circular: false,
scroll: {
items: 2,
duration: 1000
},
next: {
button: "#slider-button-next",
key: "right",
onBefore: function () {
loadAdditionalContent();
}
},
prev: {
button: "#slider-button-prev",
key: "left"
},
auto: {
play: false
}
});
});
function loadAdditionalContent () {
jQuery('#carousel').trigger('insertItem', ['<img src="http://dummyimage.com/200x200" class="added" />']);
}
Here is a fiddle that describes the problem: http://jsfiddle.net/bg0xyj8k/
there is nothing wrong with your code:
fix this in jsfidle: use external reference without https: http://cdnjs.cloudflare.com/ajax/libs/jquery.caroufredsel/6.2.1/jquery.carouFredSel.packed.js
I did some changes in your code, did not understanding what are you trying to do there.
jQuery( "#slider-add-items" ).click(function() {
loadAdditionalContent();
});
function loadAdditionalContent () {
id++;
jQuery('#carousel').trigger('insertItem', ['<img src="http://dummyimage.com/200x200" class="added" id="'+ id +'" />']);
}
http://jsfiddle.net/bg0xyj8k/2/
UPDATE
- be more precise when you are asking someting
FIX 1: insert at next click before fist visible element - http://jsfiddle.net/bg0xyj8k/3/
FIX 2: insert on last position of the slider when next clicked - http://jsfiddle.net/bg0xyj8k/4/ - result => infinite next click

Rails turbolinks - window.load not document.load

I have such code in one .js file:
var ready;
ready = function() {
var galleries = $('.car-gallery').adGallery({
loader_image: '../assets/loader.gif',
slideshow: {
enable: false,
autostart: false,
speed: 5000,
start_label: 'Start',
stop_label: 'Stop',
// Should the slideshow stop if the user scrolls the thumb list?
stop_on_scroll: true,
// Wrap around the countdown
countdown_prefix: '(',
countdown_sufix: ')',
onStart: function() {
// Do something wild when the slideshow starts
},
onStop: function() {
// Do something wild when the slideshow stops
}
}});
};
$(document).ready(ready);
$(document).on('page:load', ready);
but in my rails 4 app i use turbolinks, and sometimes is so,that images are not loaded, but document is ready and i can't start ('.car-gallery').adGallery
maybe there are any ways to don't reload page, and use window.load with turbolinks? and how?
Apart from JQueryTurbolinks, as shown in the comments, it seems your JQuery is not binding to the page load events as it should
I would recommend this code (if you want to keep a native solution):
var galleries = function() {
$('.car-gallery').adGallery({
loader_image: '../assets/loader.gif',
slideshow: {
enable: false,
autostart: false,
speed: 5000,
start_label: 'Start',
stop_label: 'Stop',
// Should the slideshow stop if the user scrolls the thumb list?
stop_on_scroll: true,
// Wrap around the countdown
countdown_prefix: '(',
countdown_sufix: ')',
onStart: function() {
// Do something wild when the slideshow starts
},
onStop: function() {
// Do something wild when the slideshow stops
}
});
};
$(document).on('page:load ready', galleries);
Can you try adding this:
var alert = function(){
alert("loaded");
};
$(document).on("page:load ready", alert);
Update
After a conversation, we found this was the solution which worked best:
#JS
$('.car-gallery').adGallery({
loader_image: '../assets/loader.gif',
slideshow: {
enable: false,
autostart: false,
speed: 5000,
start_label: 'Start',
stop_label: 'Stop',
// Should the slideshow stop if the user scrolls the thumb list?
stop_on_scroll: true,
// Wrap around the countdown
countdown_prefix: '(',
countdown_sufix: ')',
onStart: function() {
// Do something wild when the slideshow starts
},
onStop: function() {
// Do something wild when the slideshow stops
}
});
#view
<%= link_to "link", path, data: { no-turbolink: true } %>

Adding you tube player (iFrame) in jQuery modal dialog

I have some images in my HTML and _I need to play embedded you tube video videos on click of each image which should load/play in a jQuery UI dialog. Basically like a pop up video player.
So here is what i have done to play/attach video with each image. I have three images and i have added the unique video id in my custom data-attribute which i taken from you tube.
HTML
<div id="ImageBox">
<img src="img1.png" class="playVideo" alt="" id="image1" data-videoId="v6jg8g"/>
<img src="img2.png" class="playVideo" alt="" id="image2" data-videoId="re84hj"/>
<img src="img3.png" class="playVideo" alt="" id="image3" data-videoId="dhj3fk"/>
</div>
<!-- HTML for jQuery modal dialog -->
<div id="MyVideoPlayer">
<div>
<strong id="videoTitle">title for video</strong>
<img src="closeButton.png" id="Close" alt="Close" />
</div>
<iframe src="https://www.youtube.com/embed/MyVideoId?wmode=opaque&autoplay=1&autohide=1&showinfo=0&controls=2&rel=0&enablejsapi=1" id="Player" width="100%" height="100%"></iframe>
</div>
Note: I am using iframe embed method from you tube player
API
to embed videos.
For JavaScript/jQuery section, I came up with two choices here.
1. Because i am working in a ASP.NET MVC 3 app, i can set the unique video id to #ViewBag in script and assign to iFrame like this...
$('#ImagesBlock .playVideo').click(function(){
var myId = $(this).attr('data-videoId');
'#ViewBag.VideoId' = myId;
$('#MyVideoPlayer').dialog(
{ width: 'auto' },
{ height: 'auto' },
{ draggable: false },
{ resizable: false },
{ closeOnEscape: false },
{ modal: true },
{ show: { effect: "fade", duration: 200} }
});
});
2. Assign the updated iFrame src with new video id each time dialog
opens.
$('#imagesBlock .playVideo').click(function(){
var myId = $(this).attr('data-videoId');
var src = 'https://www.youtube.com/embed/'+ myId +'?wmode=opaque&autoplay=1&autohide=1
&showinfo=0&controls=2&rel=0&enablejsapi=1';
$('#MyVideoPlayeriframe').attr('src', src);
$('#MyVideoPlayer').dialog(
{ width: 'auto' },
{ height: 'auto' },
{ draggable: false },
{ resizable: false },
{ closeOnEscape: false },
{ modal: true },
{ show: { effect: "fade", duration: 200} }
});
});
Which one should I go with. I found some references though,
Embedded jwplayer into jQuery Dialog
https://stackoverflow.com/questions/15887106/how-to-get-embedded-video-into-modal-dialog
jQuery mb.YTPlayer
Is there any way i can make it little more simplified and re-usable in future. Please advise with your wise opinion.
I am little late updating this thread but I managed to create a method or more of a plugin by extending jQuery's prototype object. This is a nice link to start learning.
// following is the method by extending the jQuery's prototype object
// to convert and embed an element into a video pop-up
(function ($) {
$.fn.videoPlayer = function (options) {
var defaults = $.extend({
title: "",
videoId: "",
autoplay: 1
}, options);
var videoBox = this.find('#VideoBox');
var videoElement = document.createElement('iframe');
var src = 'https://www.youtube.com/embed/' + defaults.videoId + '?wmode=opaque&autoplay=' + defaults.autoplay + '&autohide=1&showinfo=0&controls=2&rel=0&enablejsapi=1';
this.find('#VideoTitle').text(defaults.title);
$(videoElement).attr({
'src': src,
'frameborder': 0,
'width': '100%',
'height': '90%'
});
videoBox.html(videoElement);
this.dialog(
{ width: 'auto' },
{ height: 'auto' },
{ draggable: false },
{ resizable: false },
{ closeOnEscape: false },
{ modal: true },
{ show: { effect: "fade", duration: 200} },
{ hide: { effect: "fade", duration: 250} },
{ close: function (event, ui) {
$(videoElement).remove();
$(this).dialog('destroy');
}
});
//making the method chainable!
return this;
};
})(jQuery);
$(function(){
$('#VideoPlayerPopUp #Close').click(function () {
$("#VideoCatcher").dialog("close");
});
$('#Entertainment .launch-video').click(function () {
var element = $(this);
$('#VideoCatcher').videoPlayer({
title: element.attr('data-videoTitle'),
videoId: element.attr('data-videoId')
});
});
});
I have used custom HTML data-attributes for video title and video id. This will keep HTML clean and semantic. You can of course style/customize the pop-up accordingly.
Visit this working demo to see this in action.

Categories