How to set the div height properly when image loading - javascript

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);
}
}

Related

Jquery Lightbox/Modal Difficulties doubles itself onclick

I am very new to jQuery and I have a problem with my Gallery Lightbox/Modal.
Each time I click on a thumbnail, the whole modal opens itself again and I don't know where exactly I have to set a reset.
I am pleased to hear your answers.
jQuery(function($) {
$('img').click(function() {
var image = $(this).attr("src");
var caption = $(this).attr("alt");
var appear_caption = "<figcaption id=appear_caption onClick='closeImage()'>"+caption+"</figcaption>"
var appear_image = "<div id='appear_image_div' onClick='closeImage()'></div>";
appear_image = appear_image.concat("<img id='appear_image' src='"+image+"'/>");
var thumbnails = $("thumbnails");
$(".thumbnails").css("zIndex", "100");
$(".thumbnails").css("display", "flex");
$('body').append(appear_image);
$('body').append(appear_caption);
});
});
function closeImage() {
$('#appear_image_div').remove();
$('#appear_image').remove();
$('#appear_caption').remove();
$(".thumbnails").css("display", "none");
};
Call close when you click the image so you remove any previously opened Gallery Lightbox/Modal
jQuery(function($) {
$('img').click(function() {
closeImage();
var image = $(this).attr("src");
var caption = $(this).attr("alt");
var appear_caption = "<figcaption id=appear_caption onClick='closeImage()'>"+caption+"</figcaption>"
var appear_image = "<div id='appear_image_div' onClick='closeImage()'></div>";
appear_image = appear_image.concat("<img id='appear_image' src='"+image+"'/>");
var thumbnails = $("thumbnails");
$(".thumbnails").css("zIndex", "100");
$(".thumbnails").css("display", "flex");
$('body').append(appear_image);
$('body').append(appear_caption);
});
});
function closeImage() {
$('#appear_image_div').remove();
$('#appear_image').remove();
$('#appear_caption').remove();
$(".thumbnails").css("display", "none");
};

Display the current position of jqGrid scrollbar

Currently I am working on a mini jqGrid project. The last requirement of the project is that whenever I change the position of scroll bar, an event should gets triggered that should print the current position of the scrollbar on console. But every time I am getting the same response on the console.
function filljQgrid(para1,para2){
var a;
var rowData;
var pos;
var scrollLength;
var gridData=para1;
var entityId=para2;
jQuery('#list').jqGrid('clearGridData');
var elementTop;
var elementBottom;
var viewportTop;
var viewportBottom;
jQuery(document).ready(function(){
var grid_selector="#list";
var pager_selector="#page";
//responsive starts
var parent_column = $(grid_selector).closest('[class*="col-"]');
//resize to fit page size
$(window).on('resize.jqGrid', function () {
$(grid_selector).jqGrid( 'setGridWidth', parent_column.width() );
})
$(document).on('settings.ace.jqGrid' , function(ev, event_name, collapsed) {
if( event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed' ) {
setTimeout(function() {
$(grid_selector).jqGrid( 'setGridWidth', parent_column.width() );
}, 20);
}
})
jQuery("#list").jqGrid({
datatype:"local",
width:"1090",
height:"50",
colNames:["ENTITY ID","RANK","ACCOUNT NAME","BENIFIT VALUE"],
colModel:[
{name:"entity_id",index:"entity_id",sortable:false,width:90,align:"center",key:true,hidden:true},
{name:"rank",index:"rank",sortable:true,sorttype:"int",width:90,align:"center"},
{name:"account_name",index:"account_name",width:90,sortable:false,align:"center"},
{name:"incentive",index:"incentive",width:90,sortable:false,align:"center"}
],
viewrecords:true,
ignoreCase:true,
scrollrows:true,
altRows:true,
});
$(window).triggerHandler('resize.jqGrid');
for(var l=0;l<gridData.length;l++)
{
jQuery("#list").jqGrid('addRowData', l+1, gridData[l]);
}
$("#list").setGridParam({sortname:'rank', sortorder: 'asc', loadComplete:function(){
jQuery('#list').jqGrid('setSelection','50147');
jQuery('#list').find('.ui-state-highlight').css('background', '#0487BD');
jQuery('#list').find('.ui-state-highlight').css('color', 'white');
a=jQuery('#list').jqGrid('getGridParam',"selrow");
rowData = jQuery('#list').jqGrid ('getRowData',a);in json format
pos=jQuery("#list").closest(".ui-jqgrid-bdiv").scrollTop();
elementTop = jQuery("#list").closest(".ui-jqgrid-bdiv").offset().top;
elementBottom = elementTop + $('a').height();
viewportTop = $("#list").scrollTop();
viewportBottom = viewportTop + $("#list").height();
}
}).trigger('reloadGrid');
//adding search begins here
jQuery("#list").jqGrid('navGrid','#ptoolbar',{del:false,add:false,edit:false,search:false});
jQuery("#list").jqGrid('filterToolbar',{stringResult: true,searchOnEnter : false});
//adding search ends here
//if($('a').is(':visible')){}
$(".ui-jqgrid-bdiv").scroll(function(){console.log(elementTop)});
});**strong text**
}//closing brace for filljQgrid()
After the grid is created you can bind a scroll event and see the position
Try with this code
var mygrid = $("#jqGrid")[0];
$(mygrid.grid.bDiv).scroll(function(e){
console.log(this.scrollTop);
});

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');
});
}));

Infinite scroll with photoswipe

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];
....
});
});

Bind events to all elements in class instead of just to one id

I developed this interaction / script that scales whatever element is passed to it and if that element is pinched in on, it scales down / less.
This is how the script is initialised ( passing two arguments the container and the item to be scaled / transformed:
$(function(){
var zoom = new collapse('#zoom','#zoom :first');
var zoom2 = new collapse('#zoom2','#zoom2 :first');
var zoom3 = new collapse('#zoom3','#zoom3 :first');
});
It works fine as above on single IDs, but I need it to work on a class.
I tried this:
$(function(){
var zoom = new collapse('#zoom','.polaroid');
});
But that causes the whole script not to work because all the elements in that class are being passed instead of one as with an id.
This would only select the first item in the class so it won't work:
$(function(){
var zoom = new collapse('#zoom','.polaroid :first');
});
How can I change my script so that it is applied to all members of the .polaroid class in the #main container?
Here is my script:
function collapse(container, element){
container = $(container).hammer({
prevent_default: true,
scale_threshold: 0
});
element = $(element);
var displayWidth = container.width();
var displayHeight = container.height();
var MIN_ZOOM = 0;
var MAX_ZOOM = 1;
var scaleFactor = 1;
var previousScaleFactor = 1;
var startX = 0;
var startY = 0;
var translateX = 0;
var translateY = 0;
var previousTranslateX = 0;
var previousTranslateY = 0;
var time = 1;
var tch1 = 0,
tch2 = 0,
tcX = 0,
tcY = 0,
toX = 0,
toY = 0,
cssOrigin = "";
container.bind("transformstart", function(event){
e = event;
tch1 = [e.touches[0].x, e.touches[0].y],
tch2 = [e.touches[1].x, e.touches[1].y];
tcX = (tch1[0]+tch2[0])/2,
tcY = (tch1[1]+tch2[1])/2;
toX = tcX;
toY = tcY;
var left = $(element).offset().left;
var top = $(element).offset().top;
cssOrigin = (-(left) + toX)/scaleFactor +"px "+ (-(top) + toY)/scaleFactor +"px";
});
container.bind("transform", function(event){
scaleFactor = previousScaleFactor * event.scale;
scaleFactor = Math.max(MIN_ZOOM, Math.min(scaleFactor, MAX_ZOOM));
transform(event);
});
container.bind("transformend", function(event){
previousScaleFactor = scaleFactor;
if(scaleFactor > 0.42){
$(element).css('-webkit-transform', 'scaleY(1.0)').css('transform', 'scaleY(1.0)');
}
});
function transform(e){
var cssScale = "scaleY("+ scaleFactor +")";
element.css({
webkitTransform: cssScale,
webkitTransformOrigin: cssOrigin,
transform: cssScale,
transformOrigin: cssOrigin,
});
if(scaleFactor <= 0.42){
$(element).animate({height:0}, function(){
$(this).remove();
});
}
}
}
Wrap it as a jquery plugin:
$.fn.collapse = function(filter) {
return this.each(function(){
collapse(this,filter);
});
}
$("#zoom,#zoom1,#zoom2").collapse(".polaroid");
or if each of the zoom elements had a common class,
$(".zoomel").collapse(".polaroid");
You have to run collapse for each element.
element = $(element);
element.each(function(){
//each element would be this here
var $this= $(this);
//do whatever you want with $this
})

Categories

Resources