Infinite scroll with photoswipe - javascript

I use infinite scroll with imagesloaded and isotope and photoswipe for a photo gallery. When I click on my button "More photos" it loads next photos. But I don't know how to declare those new photos to photoswipe cause the way I do it, when I click on a photo (of the new ones), it open another one.
I got a function to declare photos to photoswipe and this function is executed twice : the first time at the dom load, the second time when I load next photos :
// Photoswipe declaration
new_photos_lightbox();
function new_photos_lightbox() {
$('.gal-photos>ul').each( function() {
var $pic = $(this),
getItems = function() {
var items = [];
$pic.find('a').each(function() {
var $href = $(this).attr('href'),
$size = $(this).data('size').split('x'),
$width = $size[0],
$height = $size[1];
var item = {
src : $href,
w : $width,
h : $height
}
items.push(item);
});
return items;
}
var items = getItems();
var $pswp = $('.pswp')[0];
$pic.on('click','li',function(event){
event.preventDefault();
var $index = $(this).index();
console.log($(this));
var options = {
index: $index,
bgOpacity: 0.7,
showHideOpacity: true
}
// Initialisation PhotoSwipe
var lightBox = new PhotoSwipe($pswp, PhotoSwipeUI_Default, items, options);
lightBox.init();
return false;
});
});
}
And later I manage isotope :
/*
* Isotope
*/
var len = $('script[src*="js/isotope.pkgd.min.js"]').length;
if (len != 0) {
var $loaderAjax = $('.loader-ajax');
var $container = $('.grid');
$loaderAjax.show();
$container.imagesLoaded( function(){
$container.isotope({
itemSelector : '.grid-item',
masonry: {
columnWidth: 200,
isAnimated: true,
isFitWidth: true,
gutter: 20
}
});
$container.infinitescroll({
navSelector : '#ms-gallery-nav',
nextSelector : '#ms-gallery-nav a',
itemSelector : '.grid-item',
loading: {
msgText: 'loading photos...',
finishedMsg: 'No more photos',
img: '../img/aj-loader.gif'
}
},
function( newElements ) {
var $newElems = $(newElements).css({
opacity: 0
});
$newElems.imagesLoaded(function () {
$newElems.animate({
opacity: 1
});
$container.isotope('appended', $newElems, true);
});
new_photos_lightbox();
}
);
// Deactivation infinite scroll the benefit of More button
$container.infinitescroll('unbind');
$('#next-page-button').on('click', function(e) {
e.preventDefault();
$container.infinitescroll('retrieve');
$(this).blur();
});
$("ul.grid li").css({'display': 'list-item'});
$("div.filter-button-group").animate({'opacity':'1'},500);
$loaderAjax.hide();
});
}

Very easy
$pic.find('figure').each(function(e,i) {
$(i).on('click', 'a', function (e) {
var $pswp = $('.pswp')[0];
....
});
});

Related

Auto Scaling Image Annotation

Scalize is a jQuery plugin used for adding custom markers (hotspots) with custom popovers and animations to containers or images.
But now When I click one by one on pointer it show all one by one But I am trying to show only one so when click another pointer will close the other which already opened.
Here is my EXAMPLE
(function(jQuery) {
"use strict";
//----------------------------------------//
// Variable
//----------------------------------------//
var variable = {
width : 0,
height : 0,
selector : '.item-point',
styleSelector : 'circle',
animationSelector : 'pulse2',
animationPopoverIn : 'flipInY',
animationPopoverOut : 'flipOutY',
onInit : null,
getSelectorElement : null,
getValueRemove : null
}
//----------------------------------------//
// Scaling
//----------------------------------------//
var scaling = {
settings : null,
//----------------------------------------//
// Initialize
//----------------------------------------//
init: function(el, options){
this.settings = jQuery.extend(variable, options);
this.event(el);
scaling.layout(el);
jQuery(window).on('load', function(){
scaling.layout(el);
});
jQuery(el).find('.target').on('load', function(){
scaling.layout(el);
});
jQuery(window).on('resize', function(){
scaling.layout(el);
});
},
//----------------------------------------//
// Event
//----------------------------------------//
event : function(elem){
// Set Style Selector
if ( this.settings.styleSelector ) {
jQuery(this.settings.selector).addClass( this.settings.styleSelector );
}
// Set Animation
if ( this.settings.animationSelector ) {
if( this.settings.animationSelector == 'marker' ){
jQuery(this.settings.selector).addClass( this.settings.animationSelector );
jQuery(this.settings.selector).append('<div class="pin"></div>')
jQuery(this.settings.selector).append('<div class="pulse"></div>')
}else{
jQuery(this.settings.selector).addClass( this.settings.animationSelector );
}
}
// Event On Initialize
if ( jQuery.isFunction( this.settings.onInit ) ) {
this.settings.onInit();
}
// Content add class animated element
jQuery(elem).find('.content').addClass('animated');
// Wrapper selector
jQuery(this.settings.selector).wrapAll( "<div class='wrap-selector' />");
// Event Selector
jQuery(this.settings.selector).each(function(){
// Toggle
jQuery('.toggle', this).on('click', function(e){
e.preventDefault();
jQuery(this).closest(scaling.settings.selector).toggleClass('active');
// Selector Click
var content = jQuery(this).closest(scaling.settings.selector).data('popover'),
id = jQuery(content);
if(jQuery(this).closest(scaling.settings.selector).hasClass('active') && !jQuery(this).closest(scaling.settings.selector).hasClass('disabled')){
if ( jQuery.isFunction( scaling.settings.getSelectorElement ) ) {
scaling.settings.getSelectorElement(jQuery(this).closest(scaling.settings.selector));
}
id.fadeIn(500,function(){
if( getBrowserName() == "Safari" ){
setTimeout(function(){
id.removeClass('flipInY');
},125);
}
});
scaling.layout(elem);
id.removeClass(scaling.settings.animationPopoverOut);
id.addClass(scaling.settings.animationPopoverIn);
}else{
if(jQuery.isFunction( scaling.settings.getValueRemove )){
scaling.settings.getValueRemove(jQuery(this).closest(scaling.settings.selector));
}
id.removeClass(scaling.settings.animationPopoverIn);
id.addClass(scaling.settings.animationPopoverOut);
id.delay(500).fadeOut();
}
});
// Exit
var target = jQuery(this).data('popover'),
idTarget = jQuery(target);
idTarget.find('.exit').on('click', function(e){
e.preventDefault();
// selector.removeClass('active');
jQuery('[data-popover="'+ target +'"]').removeClass('active');
idTarget.removeClass(scaling.settings.animationPopoverIn);
idTarget.addClass(scaling.settings.animationPopoverOut);
idTarget.delay(500).fadeOut();
});
});
},
//----------------------------------------//
// Layout
//----------------------------------------//
layout : function(elem){
// Get Original Image
var image = new Image();
image.src = elem.find('.target').attr("src");
// Variable
var width = image.naturalWidth,
height = image.naturalHeight,
getWidthLess = jQuery(elem).width(),
setPersenWidth = getWidthLess/width * 100,
setHeight = height * setPersenWidth / 100;
// Set Heigh Element
jQuery(elem).css("height", setHeight);
// Resize Width
if( jQuery(window).width() < width ){
jQuery(elem).stop().css("width","100%");
}else{
jQuery(elem).stop().css("width",width);
}
// Set Position Selector
jQuery(this.settings.selector).each(function(){
if( jQuery(window).width() < width ){
var getTop = jQuery(this).data("top") * setPersenWidth / 100,
getLeft = jQuery(this).data("left") * setPersenWidth / 100;
}else{
var getTop = jQuery(this).data("top"),
getLeft = jQuery(this).data("left");
}
jQuery(this).css("top", getTop + "px");
jQuery(this).css("left", getLeft + "px");
// Target Position
var target = jQuery(this).data('popover'),
allSize = jQuery(target).find('.head').outerHeight() + jQuery(target).find('.body').outerHeight() + jQuery(target).find('.footer').outerHeight();
jQuery(target).css("left", getLeft + "px");
jQuery(target).css("height", allSize + "px");
if(jQuery(target).hasClass('bottom')){
var getHeight = jQuery(target).outerHeight(),
getTopBottom = getTop - getHeight;
jQuery(target).css("top", getTopBottom + "px");
}else if(jQuery(target).hasClass('center')){
var getHeight = jQuery(target).outerHeight() * 0.50,
getTopBottom = getTop - getHeight;
jQuery(target).css("top", getTopBottom + "px");
}else{
jQuery(target).css("top", getTop + "px");
}
jQuery('.toggle', this).css('width', jQuery(this).outerWidth());
jQuery('.toggle', this).css('height', jQuery(this).outerHeight());
// Toggle Size
if(jQuery(this).find('.pin')){
var widthThis = jQuery('.pin', this).outerWidth(),
heightThis = jQuery('.pin', this).outerHeight();
jQuery('.toggle', this).css('width', widthThis);
jQuery('.toggle', this).css('height', heightThis);
}
});
}
};
//----------------------------------------//
// Scalize Plugin
//----------------------------------------//
jQuery.fn.scalize = function(options){
return scaling.init(this, options);
};
}(jQuery));
function getBrowserName() {
var name = "Unknown";
if(navigator.userAgent.indexOf("MSIE")!=-1){
name = "MSIE";
}
else if(navigator.userAgent.indexOf("Firefox")!=-1){
name = "Firefox";
}
else if(navigator.userAgent.indexOf("Opera")!=-1){
name = "Opera";
}
else if(navigator.userAgent.indexOf("Chrome") != -1){
name = "Chrome";
}
else if(navigator.userAgent.indexOf("Safari")!=-1){
name = "Safari";
}
return name;
}
Add this to your initialisation:
getSelectorElement: function(el) {
$('.item-point.active').not($(el)[0]).find('.toggle').click();
}
This hooks into the getSelectorElement method in the Scalize plugin and triggers a click on any active (open) elements that don't match the most recently clicked item.
Add it like so:
$(document).ready(function(){
$('.scalize').scalize({
styleSelector: 'circle',
animationPopoverIn: 'fadeIn',
animationPopoverOut: 'fadeOut',
animationSelector: 'pulse2',
getSelectorElement: function(el) {
$('.item-point.active').not($(el)[0]).find('.toggle').click();
}
});
});
Note, because this is hooking into existing methods in the plugin it's a little safer (no unpredictable side effects, plus you get the intended transition out on the disappearing elements). Fiddle.
I've modified your jsFiddle to work.
TL;DR: Anytime an point is clicked, if there are other active siblings, loop over them and hide their popups.
It isn't a pretty way of doing it but it is working in the Fiddle.
$('.scalize').on('click', '.item-point', (function() {
$(this).siblings('.item-point.active').each(function() {
var popover = $(this).data('popover');
$(popover).removeClass('fadeIn').css({
'display': 'none'
});
$(this).removeClass('active');
});
}));

How to set the div height properly when image loading

I'm tring to build a grid webside,but it shows like first image when I 'm loading.So I use function getImageSize from this
Get Image height before its fully loaded to set the imageDiv height,but still failed.Would you please tell me why and how to fix it? Thanks.
first image
second image
$(document).ready(function(){
var $container = $('#container');
ajaxGetJson(3,1,$container); //get data from json
window.onscroll = function(){
if(scrollside()){ //if scroll
ajaxGetJson(3,2,$container); //get data from json again
}
};
});
function ajaxGetJson(actId,page,container){
$.ajax({
type: "GET",
dataType: "json",
url: "/api/posts",
data:{actid:actId,page:page},
success:function(json_data){
var items = []
$.each(json_data,function(index,value){
var box = document.createElement('div');
box.className = "box";
var $box = $(box).appendTo(container);
var content = $("<div>").addClass("content").appendTo(box);
var imgDiv = $("<div>").addClass("imgDiv").appendTo(content);
var $img = $("<img>").attr("src",$(value).attr("post_thumb_url")).appendTo(imgDiv);
getImageSize($img, function(width, height){
imgDiv.css("height",height);//console correct height in the first 15 items.
});
items.push(box);
});
jqueryMasonry(page,items);
}
});
}
//using masonry
function jqueryMasonry(page,items){
if(page==1){
var $container = $('#container');
$container.imagesLoaded(function(){
$container.masonry({
itemSelector : '.box'
});
});
}
else{
var $container = $('#container');
var $boxes = $(items);
$container.masonryImagesReveal($boxes);
}
}
// this function is tell user scroll enough height
function scrollside(){
var box = $(".box");
var lastboxHeight = box.last().get(0).offsetTop+Math.floor(box.last().height()/2);
var documentHeight = $(document).width();
var scrollHeight = $(window).scrollTop();
return (lastboxHeight<scrollHeight+documentHeight)?true:false;
}
//this function is for images show properly,I found it here https://github.com/desandro/masonry/issues/534
$.fn.masonryImagesReveal = function( $items ) {
var msnry = this.data('masonry');
var itemSelector = msnry.options.itemSelector;
// hide by default
$items.hide();
// append to container
this.append( $items );
$items.imagesLoaded().progress( function( imgLoad, image ) {
// get item
// image is imagesLoaded class, not <img>, <img> is image.img
var $item = $( image.img ).parents( itemSelector );
// un-hide item
$item.show();
// masonry does its thing
msnry.appended( $item );
});
return this;
};
//I found a solution here https://stackoverflow.com/questions/23390393/get-image-height-before-its-fully-loaded
function getImageSize(img, callback){
img = $(img);
var wait = setInterval(function(){
var w = img.width(),
h = img.height();
if(w && h){
done(w, h);
}
}, 0);
var onLoad;
img.on('load', onLoad = function(){
done(img.width(), img.height());
});
var isDone = false;
function done(){
if(isDone){
return;
}
isDone = true;
clearInterval(wait);
img.off('load', onLoad);
callback.apply(this, arguments);
}
}

What part of jquery code is responsible for jump to next image?

I'm working to adapt malihu Sideways gallery and little messed up with jquery code.
I'm trying to change functionality of (clicking on background image for next image load) to (clicking on button for next image load)
I know that it sound simple but it isn't.
I can't solve what part of the code is responsible for this function
so I can just change the selector.
Here is the code:
$( function() {
// init Isotope
var $container = $('.isotope').isotope({
itemSelector: '.element-item',
layoutMode: 'fitRows'
});
// filter functions
var filterFns = {
// show if number is greater than 50
numberGreaterThan50: function() {
var number = $(this).find('.number').text();
return parseInt( number, 10 ) > 50;
},
// show if name ends with -ium
ium: function() {
var name = $(this).find('.name').text();
return name.match( /ium$/ );
}
};
// bind filter button click
$('#filters').on( 'click', 'button', function() {
var filterValue = $( this ).attr('data-filter');
// use filterFn if matches value
filterValue = filterFns[ filterValue ] || filterValue;
$container.isotope({ filter: filterValue });
});
// change is-checked class on buttons
$('.button-group').each( function( i, buttonGroup ) {
var $buttonGroup = $( buttonGroup );
$buttonGroup.on( 'click', 'button', function() {
$buttonGroup.find('.is-checked').removeClass('is-checked');
$( this ).addClass('is-checked');
});
});
});
//set default view mode
$defaultViewMode="full"; //full (fullscreen background), fit (fit to window), original (no scale)
//cache vars
$bg=$("#bg");
$bgimg=$("#bg #bgimg");
$preloader=$("#preloader");
$outer_container=$("#outer_container");
$outer_container_a=$("#outer_container a.thumb_link");
$toolbar=$("#toolbar");
$nextimage_tip=$("#nextimage_tip");
$(window).load(function() {
$toolbar.data("imageViewMode",$defaultViewMode); //default view mode
ImageViewMode($toolbar.data("imageViewMode"));
//cache vars
$customScrollBox=$("#customScrollBox");
$customScrollBox_container=$("#customScrollBox .container");
$customScrollBox.height($customScrollBox_container.height());
//resize browser window functions
$(window).resize(function() {
FullScreenBackground("#bgimg"); //scale bg image
});
LargeImageLoad($bgimg);
});
//loading bg image
$bgimg.load(function() {
LargeImageLoad($(this));
});
function LargeImageLoad($this){
$preloader.fadeOut("fast"); //hide preloader
$this.removeAttr("width").removeAttr("height").css({ width: "", height: "" }); //lose all previous dimensions in order to rescale new image data
$bg.data("originalImageWidth",$this.width()).data("originalImageHeight",$this.height());
if($bg.data("newTitle")){
$this.attr("title",$bg.data("newTitle")); //set new image title attribute
}
FullScreenBackground($this); //scale new image
$bg.data("nextImage",$($outer_container.data("selectedThumb")).next().attr("href")); //get and store next image
if(typeof itemIndex!="undefined"){
if(itemIndex==lastItemIndex){ //check if it is the last image
$bg.data("lastImageReached","Y");
$bg.data("nextImage",$outer_container_a.first().attr("href")); //get and store next image
} else {
$bg.data("lastImageReached","N");
}
} else {
$bg.data("lastImageReached","N");
}
$this.fadeIn("slow"); //fadein background image
if($bg.data("nextImage") || $bg.data("lastImageReached")=="Y"){ //don't close thumbs pane on 1st load
SlidePanels("open"); //close the left pane
}
NextImageTip();
}
$bgimg.click(
function(){
SlidePanels("close").toggle();
});
$bgimg.click(
function(){
SlidePanels("open").toggle();
});
$("#arrow_indicator").click(
function(){ //click
SlidePanels("open");
}
);
$("#arrow_next").click(
function(){
//Code for next image will go here
}
);
//Clicking on thumbnail changes the background image
$outer_container_a.click(function(event){
event.preventDefault();
var $this=this;
$bgimg.css("display","none");
$preloader.fadeIn("fast"); //show preloader
//style clicked thumbnail
$outer_container_a.each(function() {
$(this).children(".selected").css("display","none");
});
$(this).children(".selected").css("display","block");
//get and store next image and selected thumb
$outer_container.data("selectedThumb",$this);
$bg.data("nextImage",$(this).next().attr("href"));
$bg.data("newTitle",$(this).children("img").attr("title")); //get and store new image title attribute
itemIndex=getIndex($this); //get clicked item index
lastItemIndex=($outer_container_a.length)-1; //get last item index
$bgimg.attr("src", "").attr("src", $this); //switch image
});
//clicking on large image loads the next one
$("#arrow_next").click(function(event){
var $this=$(this);
if($bg.data("nextImage")){ //if next image data is stored
$this.css("display","none");
$preloader.fadeIn("fast"); //show preloader
$($outer_container.data("selectedThumb")).children(".selected").css("display","none"); //deselect thumb
if($bg.data("lastImageReached")!="Y"){
$($outer_container.data("selectedThumb")).next().children(".selected").css("display","none"); //select new thumb
} else {
$outer_container_a.first().children(".selected").css("display","none"); //select new thumb - first
}
//store new selected thumb
var selThumb=$outer_container.data("selectedThumb");
if($bg.data("lastImageReached")!="Y"){
$outer_container.data("selectedThumb",$(selThumb).next());
} else {
$outer_container.data("selectedThumb",$outer_container_a.first());
}
$bg.data("newTitle",$($outer_container.data("selectedThumb")).children("img").attr("title")); //get and store new image title attribute
if($bg.data("lastImageReached")!="Y"){
itemIndex++;
} else {
itemIndex=0;
}
$this.attr("src", "").attr("src", $bg.data("nextImage")); //switch image
}
});
//function to get element index (IE!)
function getIndex(theItem){
for ( var i = 0, length = $outer_container_a.length; i < length; i++ ) {
if ( $outer_container_a[i] === theItem ) {
return i;
}
}
}
//toolbar (image view mode button) hover
$toolbar.hover(
function(){ //mouse over
$(this).stop().fadeTo("fast",1);
},
function(){ //mouse out
$(this).stop().fadeTo("fast",0.8);
}
);
$toolbar.stop().fadeTo("fast",0.8); //set its original state
//Clicking on toolbar changes the image view mode
$toolbar.click(function(event){
if($toolbar.data("imageViewMode")=="full"){
ImageViewMode("fit");
} else if($toolbar.data("imageViewMode")=="fit") {
ImageViewMode("original");
} else if($toolbar.data("imageViewMode")=="original"){
ImageViewMode("full");
}
});
//next image balloon tip
function NextImageTip(){
if($bg.data("nextImage")){ //check if this is the first image
$nextimage_tip.stop().css("right",20).fadeIn("fast").fadeOut(2000,"easeInExpo",function(){$nextimage_tip.css("right",$(window).width());});
}
}
//slide in/out left pane function
function SlidePanels(action){
var speed=400;
var easing="easeInBack";
if(action=="open"){
$("#arrow_indicator").fadeTo("fast",0);
$outer_container.stop().animate({left: 0}, speed,easing);
$bg.stop().animate({left: 585}, speed,easing);
} else {
$outer_container.stop().animate({left: -710}, speed,easing);
$bg.stop().animate({left: 0}, speed,easing,function(){$("#arrow_indicator").fadeTo("fast",1);});
}
}
//Image scale function
function FullScreenBackground(theItem){
var winWidth=$(window).width();
var winHeight=$(window).height();
var imageWidth=$(theItem).width();
var imageHeight=$(theItem).height();
if($toolbar.data("imageViewMode")!="original"){ //scale
$(theItem).removeClass("with_border").removeClass("with_shadow"); //remove extra styles of orininal view mode
var picHeight = imageHeight / imageWidth;
var picWidth = imageWidth / imageHeight;
if($toolbar.data("imageViewMode")!="fit"){ //image view mode: full
if ((winHeight / winWidth) < picHeight) {
$(theItem).css("width",winWidth).css("height",picHeight*winWidth);
} else {
$(theItem).css("height",winHeight).css("width",picWidth*winHeight);
};
} else { //image view mode: fit
if ((winHeight / winWidth) > picHeight) {
$(theItem).css("width",winWidth).css("height",picHeight*winWidth);
} else {
$(theItem).css("height",winHeight).css("width",picWidth*winHeight);
};
}
//center it
$(theItem).css("margin-left",((winWidth - $(theItem).width())/2)).css("margin-top",((winHeight - $(theItem).height())/2));
} else { //no scale
//add extra styles for orininal view mode
$(theItem).addClass("with_border").addClass("with_shadow");
//set original dimensions
$(theItem).css("width",$bg.data("originalImageWidth")).css("height",$bg.data("originalImageHeight"));
//center it
$(theItem).css("margin-left",((winWidth-$(theItem).outerWidth())/2)).css("margin-top",((winHeight-$(theItem).outerHeight())/2));
}
}
//image view mode function - full or fit
function ImageViewMode(theMode){
$toolbar.data("imageViewMode", theMode); //store new mode
FullScreenBackground($bgimg); //scale bg image
//re-style button
if(theMode=="full"){
$toolbar.html("<span class='lightgrey'>CATEGORY ›</span> LOGO");
} else if(theMode=="fit") {
$toolbar.html("<span class='lightgrey'>CATEGORY ›</span> APP DESIGN");
} else if(theMode=="fit") { {
$toolbar.html("<span class='lightgrey'>CATEGORY ›</span> WEB DESIGN");
}
} else {
$toolbar.html("<span class='lightgrey'>CATEGORY ›</span> 3D");
}
}
//preload script images
var images=["ajax-loader_dark.gif","round_custom_scrollbar_bg_over.png"];
$.each(images, function(i) {
images[i] = new Image();
images[i].src = this;
});
Its going to be at:
$outer_container_a.click(function(event){
You can change this to:
$(".CLASSNAME").click(function(event){
Seeing the source and how it actually works would help too.

Uncaught TypeError: Cannot read property 'alt' of null :Script stops

when i get error Uncaught TypeError: Cannot read property 'alt' of null , my script works fine in browser but sometimes i see dragged object gets stucked when i inspect via device inscept i see belwo error
my script stops executing how can i prevent that ??..
see http://liveweave.com/GknZjq
(function () {
var canvas = new fabric.Canvas('canvas');
var canvas_el = document.getElementById('canvas');
var canvas1 = new fabric.Canvas('canvas1');
var group;
fabric.Image.fromURL('img/blank.png', function (img) {
var img1 = img.set({
left: 0,
top: 0
});
fabric.Image.fromURL('img/blank.png', function (img) {
var img2 = img.set({
left: 0,
top: 0
});
group = new fabric.Group([img1, img2], {
left: 0,
top: 0
});
canvas.add(group)
});
});
fabric.Image.fromURL('img/blank.png', function (img) {
var img1 = img.set({
left: 0,
top: 0
});
fabric.Image.fromURL('img/blank.png', function (img) {
var img2 = img.set({
left: 0,
top: 0
});
group1 = new fabric.Group([img1, img2], {
left: 0,
top: 0
});
canvas1.add(group1)
});
});
$(document).ready(function () {
/* Define drag and drop zones */
var $drop = $('#canvas-drop-area,#canvas-drop-area1'),
$gallery = $('td > #image-list li'),
$draggedImage=null;
/* Define the draggable properties */
$gallery.draggable({
helper: 'clone',
start: function (e) {
$draggedImage=event.target;
$drop.css({
'display': 'block'
})
},
stop: function () {
$(this).find('img').css({
/* 'opacity': 0.4 */
});
$drop.css({
'display': 'none'
});
$draggedImage=null;
},
revert: true
});
/* Define the events for droppable properties */
$drop.droppable({
over: function (event, ui) {
$(this).addClass('active');
},
drop: function (event, ui) {
var image =$draggedImage&& $draggedImage.src;
console.log($draggedImage.alt);
img_to_canvas(image,$draggedImage.alt,$(event.target).is("#canvas-drop-area")?1:2);
},
out: function (event, ui) {
$(this).removeClass('active');
},
deactivate: function (event, ui) {
$(this).removeClass('active');
}
});
});
var img_to_canvas = function(image,sendfront,checkcanvas) {
var img = new Image();
img.src = image;
if(checkcanvas =='1'){
if(sendfront=='top'){
fabric.util.loadImage(img.src, function (img) {
group.item(0).setElement(img);
canvas.renderAll();
});
}else{
fabric.util.loadImage(img.src, function (img) {
group.item(1).setElement(img);
canvas.renderAll();
});
}
canvas.calcOffset();
}else{
if(sendfront=='top'){
fabric.util.loadImage(img.src, function (img) {
group1.item(0).setElement(img);
canvas1.renderAll();
});
}else{
fabric.util.loadImage(img.src, function (img) {
group1.item(1).setElement(img);
canvas1.renderAll();
});
}
canvas1.calcOffset();
}
}
})();
I think the issue is because you're accessing the the dragged element inside drop handler from a variable that you're setting in draggables start event, which in turn you're setting back to null in it's stop handler.
You don't need to do this, you can access the dropped elements from the drop event callbacks arguments. Also, you don't need to change the CSS of droppable from the start, stop callbacks of draggable, you can use the activate and deactivate options of droppable itself.
The code for your draggable - droppable interaction should be something along the following lines:
$(document).ready(function () {
/* Define drag and drop zones */
var $drop = $('#canvas-drop-area,#canvas-drop-area1'),
$gallery = $('td > #image-list li'),
$draggedImage=null;
/* Define the draggable properties */
$gallery.draggable({
helper: 'clone',
start: function (e) {
$drop.css('display','block')
},
stop: function () {
$(this).find('img').css({
/* 'opacity': 0.4 */
});
},
revert: true
});
/* Define the events for droppable properties */
$drop.droppable({
over: function (event, ui) {
$(this).addClass('active');
},
drop: function (event, ui) {
var image = ui.draggable.find("img").get(0);
img_to_canvas(image, image.alt,$(event.target).is("#canvas-drop-area")?1:2);
},
out: function (event, ui) {
$(this).removeClass('active');
},
deactivate: function (event, ui) {
$(this).removeClass('active').css("display","none");
}
});
});

Script doesn't work on elements loaded with infinite scrolling

I'm using this script on my tumblr page, which gives posts different random text colors:
function get_random_color() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.round(Math.random() * 15)];
}
return color;}
$(function() {
$(".post").each(function() {
$(this).css("color", get_random_color());
}); });
The thing is the script isn't working for elements loaded with infinite scrolling. Can anyone help me rewrite this code? I don't know how to write javascript sadly.
Take a look at your blog's main.js script. You can call your custom function when you grab the new elements from another page. This is my proposed revision of your main.js file.
$(window).load(function () {
var $wall = $('#content');
$wall.imagesLoaded(function () {
$wall.masonry({
itemSelector: '.post',
isAnimated: false
});
});
$wall.infinitescroll({
navSelector: '#pagination',
nextSelector: '#pagination li a.pagination_nextlink',
itemSelector: '.post',
loadingImg: "http://static.tumblr.com/kwz90l7/bIdlst7ub/transparent.png",
loadingText: " ",
donetext: " ",
bufferPx: 100,
debug: false,
errorCallback: function () {
$('#infscr-loading').animate({
opacity: .8
}, 2000).fadeOut('normal');
}
}, function (newElements) {
var $newElems = $(newElements);
$newElems.hide();
$newElems.each(function(value){
value.css("color", get_random_color());
});
$newElems.imagesLoaded(function () {
$wall.masonry('appended', $newElems, {
isAnimated: false,
animationOptions: {
duration: 900,
easing: 'linear',
queue: false
}
}, function () {
$newElems.fadeIn('slow');
});
});
$(document).ready(function () {
$("a[rel^='prettyPhoto']").prettyPhoto({
deeplinking: false,
default_width: 600,
default_height: 550,
allow_resize: true,
});
});
});
$('#content').show(500);
});
function get_random_color() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.round(Math.random() * 15)];
}
return color;
}
What I've done is add your get_random_color function and called it from within the Infinite Scroll call to add a custom color to each of the elements in $newElems so really, all I've done is taken your code and integrated it differently than what you were trying to do, which wasn't working. This should, theoretically, work. If it doesn't or you have questions, let me know.

Categories

Resources