Get all photos loaded by their visibility? - javascript

I have original script: http://pastebin.com/ERWdaQym
I need to appear in the image, the image is displayed. Script worked when he was with html. But there was another problem, put this script in a separate file. But I did not get, get it to work so it worked.
I have an library.js, this file is automatically included in every page.:
var LIBRARY = {
init: function() {
$('image[itemprop = image]').each(LIBRARY.lazyLoad());
},
/**
* LazyLoad images
*/
lazyLoad: function(event) {
$(function() {
var $window = $(window),
images = [],
imagesToBeLoaded = 0,
i,
src;
function throttle(func, wait) {
var timeout;
return function() {
var context = this, args = arguments;
if(!timeout) {
timeout = setTimeout(function() {
timeout = null;
}, wait);
func.apply(context, args);
}
};
}
function inViewport($el) {
var top = $window.scrollTop(),
left = $window.scrollLeft(),
bottom = top + $window.height(),
right = left + $window.width(),
offset = $el.offset(),
thisTop = offset.top,
thisLeft = offset.left,
thisBottom = thisTop + $el.outerHeight(),
thisRight = thisLeft + $el.outerWidth();
return !(
bottom < thisTop ||
top > thisBottom ||
right < thisLeft ||
left > thisRight
);
}
// throttle so we don't do too many calls
var lazyScroll = throttle(function() {
// have all images been loaded?
if(imagesToBeLoaded > 0) {
for(i = 0; i < images.length; i++) {
// data is there if nothing has been done to it
src = images[i].data('src');
// see if the image is in the view
if(src && inViewport(images[i])) {
// create a nice closure here
(function(img, src, i, $img) {
img.onload = function() {
console.log('Loaded ' + i + ' ' + img.src);
$img.attr('src', img.src);
imagesToBeLoaded--;
};
img.onerror = function() {
console.log('Could not load ' + i + ' ' + img.src);
imagesToBeLoaded--;
};
// important to remove this to avoid duplicate calls
$img.removeData('src');
// start loading the image
img.src = src;
})(new Image(), src, i, images[i]);
}
}
} else {
// cleanup
images = void 0;
// why keep listening if there is nothing to listen
$window.off('resize scroll touchmove', lazyScroll);
// all images are loaded
console.log('Unloaded event listener');
}
}, 50);
$('image[itemprop = image]').each(function() {
var $this = $(this),
$img = $(this.innerText || $this.text()).filter('img');
// make sure we got something
if($img.length === 1) {
// remember the real image
$img.data('src', $img.attr('src'));
// use a blank image
$img.attr('src', 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
// cache a reference
images.push($img);
// replace noscript element with the image
$this.replaceWith($img);
imagesToBeLoaded++;
}
});
// only add if we need it
if(imagesToBeLoaded) {
lazyScroll();
$window.on('resize scroll touchmove', lazyScroll);
}
});
}
};
I need to connect the init: event that would run the script and images appear correctly, in other words, if a user comes to the image, then it is loaded. Tell me how to do it and what I need to fix?

You can use document ready: http://learn.jquery.com/using-jquery-core/document-ready/
something like:
$(document).ready(LIBRARY.init);

Related

How to queue based preload images for browser to cache and use in other pages

I have been searching for all available solutions
This is the best so far i could find but it doesn't work as it should be
It works for first few images then stops. Then i refresh page, works for few more images and then stops again.
So basically what i want to achieve is, give like a 100 images to a function, it starts downloading them 1 by 1
So browser caches those images and those images are not downloaded on other pages and instantly displayed
I want this images to be cached on mobile as well
Here my javascript code that i call. Actually i have more than 100 images but didn't put all here
I accept both jquery and raw javascript solutions doesn't matter
(function() {
'use strict';
var preLoader = function(images, options) {
this.options = {
pipeline: true,
auto: true,
/* onProgress: function(){}, */
/* onError: function(){}, */
onComplete: function() {}
};
options && typeof options == 'object' && this.setOptions(options);
this.addQueue(images);
this.queue.length && this.options.auto && this.processQueue();
};
preLoader.prototype.setOptions = function(options) {
// shallow copy
var o = this.options,
key;
for (key in options) options.hasOwnProperty(key) && (o[key] = options[key]);
return this;
};
preLoader.prototype.addQueue = function(images) {
// stores a local array, dereferenced from original
this.queue = images.slice();
return this;
};
preLoader.prototype.reset = function() {
// reset the arrays
this.completed = [];
this.errors = [];
return this;
};
preLoader.prototype.load = function(src, index) {
console.log("downloading image " + src);
var image = new Image(),
self = this,
o = this.options;
// set some event handlers
image.onerror = image.onabort = function() {
this.onerror = this.onabort = this.onload = null;
self.errors.push(src);
o.onError && o.onError.call(self, src);
checkProgress.call(self, src);
o.pipeline && self.loadNext(index);
};
image.onload = function() {
this.onerror = this.onabort = this.onload = null;
// store progress. this === image
self.completed.push(src); // this.src may differ
checkProgress.call(self, src, this);
o.pipeline && self.loadNext(index);
};
// actually load
image.src = src;
return this;
};
preLoader.prototype.loadNext = function(index) {
// when pipeline loading is enabled, calls next item
index++;
this.queue[index] && this.load(this.queue[index], index);
return this;
};
preLoader.prototype.processQueue = function() {
// runs through all queued items.
var i = 0,
queue = this.queue,
len = queue.length;
// process all queue items
this.reset();
if (!this.options.pipeline)
for (; i < len; ++i) this.load(queue[i], i);
else this.load(queue[0], 0);
return this;
};
function checkProgress(src, image) {
// intermediate checker for queue remaining. not exported.
// called on preLoader instance as scope
var args = [],
o = this.options;
// call onProgress
o.onProgress && src && o.onProgress.call(this, src, image, this.completed.length);
if (this.completed.length + this.errors.length === this.queue.length) {
args.push(this.completed);
this.errors.length && args.push(this.errors);
o.onComplete.apply(this, args);
}
return this;
}
if (typeof define === 'function' && define.amd) {
// we have an AMD loader.
define(function() {
return preLoader;
});
} else {
this.preLoader = preLoader;
}
}).call(this);
// Usage:
$(window).load(function() {
new preLoader([
'//static.pokemonpets.com/images/attack_animations/absorb1.png',
'//static.pokemonpets.com/images/attack_animations/bleeding1.png',
'//static.pokemonpets.com/images/attack_animations/bug_attack1.png',
'//static.pokemonpets.com/images/attack_animations/bug_attack2.png',
'//static.pokemonpets.com/images/attack_animations/bug_boost1.png',
'//static.pokemonpets.com/images/attack_animations/burned1.png',
'//static.pokemonpets.com/images/attack_animations/change_weather_cloud.png',
'//static.pokemonpets.com/images/attack_animations/confused1.png',
'//static.pokemonpets.com/images/attack_animations/copy_all_enemy_moves.png',
'//static.pokemonpets.com/images/attack_animations/copy_last_move_enemy.png',
'//static.pokemonpets.com/images/attack_animations/cringed1.png',
'//static.pokemonpets.com/images/attack_animations/critical1.png',
'//static.pokemonpets.com/images/attack_animations/cure_all_status_problems.png',
'//static.pokemonpets.com/images/attack_animations/dark_attack1.png',
'//static.pokemonpets.com/images/attack_animations/dark_attack2.png',
'//static.pokemonpets.com/images/attack_animations/dark_attack3.png',
'//static.pokemonpets.com/images/attack_animations/dark_boost1.png',
'//static.pokemonpets.com/images/attack_animations/double_effect.png',
'//static.pokemonpets.com/images/attack_animations/dragon_attack1.png',
'//static.pokemonpets.com/images/attack_animations/dragon_attack2.png',
'//static.pokemonpets.com/images/attack_animations/dragon_attack3.png',
'//static.pokemonpets.com/images/attack_animations/dragon_attack4.png'
]);
});
Something like this?
I do not have time to make it pretty.
const pref = "https://static.pokemonpets.com/images/attack_animations/";
const defa = "https://imgplaceholder.com/20x20/000/fff/fa-image";
const images=['absorb1','bleeding1','bug_attack1','bug_attack2','bug_boost1','burned1','change_weather_cloud','confused1','copy_all_enemy_moves','copy_last_move_enemy','cringed1','critical1','cure_all_status_problems','dark_attack1','dark_attack2','dark_attack3','dark_boost1','double_effect','dragon_attack1','dragon_attack2','dragon_attack3','dragon_attack4'];
let cnt = 0;
function loadIt() {
if (cnt >= images.length) return;
$("#imagecontainer > img").eq(cnt).attr("src",pref+images[cnt]+".png"); // preload next
cnt++;
}
const $cont = $("#container");
const $icont = $("#imagecontainer");
// setting up test images
$.each(images,function(_,im) {
$cont.append('<img src="'+defa+'" id="'+im+'"/>'); // actual images
$icont.append('<img src="'+defa+'" data-id="'+im+'"/>'); // preload images
});
$("#imagecontainer > img").on("load",function() {
if (this.src.indexOf("imgplaceholder") ==-1) { // not for the default image
$("#"+$(this).attr("data-id")).attr("src",this.src); // copy preloaded
loadIt(); // run for next entry
}
})
loadIt(); // run
#imagecontainer img { height:20px }
#container img { height:100px }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container"></div>
<hr/>
<div id="imagecontainer"></div>

JavaScript + jQuery + Angular: Element is not found

I have a JavaScript function defined. Inside this function, I define variables of type jQuery elements. So, the variables refer to divs on the HTML. This function returns an object that has a single function init().
In the $(document).ready function, I call init() function.
The problem is when the script loads, the DOM is not ready and hence the variables referring to jQuery items are being set to undefined.
Later, I call the init() function inside Angular ngOnInit() to make sure things are well initialized, so nothing is happening as the variables above are undefined and they are not being re-calculated again.
Seems, when a function in JavaScript is defined, its body runs, and hence the variables are run and set to undefined as the HTML elements were not in the DOM yet.
How can I re-calculate the variables when init() runs? I cannot get my mind on this thing.
Thanks
var mQuickSidebar = function() {
var topbarAside = $('#m_quick_sidebar');
console.log('Function: ', Date.now());
var topbarAsideTabs = $('#m_quick_sidebar_tabs');
var topbarAsideClose = $('#m_quick_sidebar_close');
var topbarAsideToggle = $('#m_quick_sidebar_toggle');
var topbarAsideContent = topbarAside.find('.m-quick-sidebar__content');
var initMessages = function() {
var messenger = $('#m_quick_sidebar_tabs_messenger');
if (messenger.length === 0) {
return;
}
var messengerMessages = messenger.find('.m-messenger__messages');
var init = function() {
var height = topbarAside.outerHeight(true) -
topbarAsideTabs.outerHeight(true) -
messenger.find('.m-messenger__form').outerHeight(true) - 120;
// init messages scrollable content
messengerMessages.css('height', height);
mApp.initScroller(messengerMessages, {});
}
init();
// reinit on window resize
mUtil.addResizeHandler(init);
}
var initSettings = function() {
var settings = $('#m_quick_sidebar_tabs_settings');
if (settings.length === 0) {
return;
}
// init dropdown tabbable content
var init = function() {
var height = mUtil.getViewPort().height - topbarAsideTabs.outerHeight(true) - 60;
// init settings scrollable content
settings.css('height', height);
mApp.initScroller(settings, {});
}
init();
// reinit on window resize
mUtil.addResizeHandler(init);
}
var initLogs = function() {
// init dropdown tabbable content
var logs = $('#m_quick_sidebar_tabs_logs');
if (logs.length === 0) {
return;
}
var init = function() {
var height = mUtil.getViewPort().height - topbarAsideTabs.outerHeight(true) - 60;
// init settings scrollable content
logs.css('height', height);
mApp.initScroller(logs, {});
}
init();
// reinit on window resize
mUtil.addResizeHandler(init);
}
var initOffcanvasTabs = function() {
initMessages();
initSettings();
initLogs();
}
var initOffcanvas = function() {
topbarAside.mOffcanvas({
class: 'm-quick-sidebar',
overlay: true,
close: topbarAsideClose,
toggle: topbarAsideToggle
});
// run once on first time dropdown shown
topbarAside.mOffcanvas().one('afterShow', function() {
mApp.block(topbarAside);
setTimeout(function() {
mApp.unblock(topbarAside);
topbarAsideContent.removeClass('m--hide');
initOffcanvasTabs();
}, 1000);
});
}
return {
init: function() {
console.log('Inside Init(): ', Date.now());
console.log($('#m_quick_sidebar')); // topbarAside is undefined here!
if (topbarAside.length === 0) {
return;
}
initOffcanvas();
}
}; }();
$(document).ready(function() {
console.log('document.ready: ', Date.now());
mQuickSidebar.init();
});
The problem is that you immediately invoke your function mQuickSidebar not
Seems, when a function in JavaScript is defined, its body runs
var mQuickSidebar = function() {
var topbarAside = $('#m_quick_sidebar');
console.log('Function: ', Date.now());
var topbarAsideTabs = $('#m_quick_sidebar_tabs');
var topbarAsideClose = $('#m_quick_sidebar_close');
var topbarAsideToggle = $('#m_quick_sidebar_toggle');
var topbarAsideContent = topbarAside.find('.m-quick-sidebar__content');
...
}(); // <---- this runs the function immediately
So those var declarations are run and since the DOM is not ready those selectors don't find anything. I'm actually surprised that it does not throw a $ undefined error of some sort
This looks like a broken implementation of The Module Pattern
I re-wrote your code in the Module Pattern. The changes are small. Keep in mind that everything declared inside the IIFE as a var are private and cannot be accessed through mQuickSidebar. Only the init function of mQuickSidebar is public. I did not know what you needed to be public or private. If you need further clarity just ask.
As a Module
var mQuickSidebar = (function(mUtil, mApp, $) {
console.log('Function: ', Date.now());
var topbarAside;
var topbarAsideTabs;
var topbarAsideClose;
var topbarAsideToggle;
var topbarAsideContent;
var initMessages = function() {
var messenger = $('#m_quick_sidebar_tabs_messenger');
if (messenger.length === 0) {
return;
}
var messengerMessages = messenger.find('.m-messenger__messages');
var init = function() {
var height = topbarAside.outerHeight(true) -
topbarAsideTabs.outerHeight(true) -
messenger.find('.m-messenger__form').outerHeight(true) - 120;
// init messages scrollable content
messengerMessages.css('height', height);
mApp.initScroller(messengerMessages, {});
};
init();
// reinit on window resize
mUtil.addResizeHandler(init);
};
var initSettings = function() {
var settings = $('#m_quick_sidebar_tabs_settings');
if (settings.length === 0) {
return;
}
// init dropdown tabbable content
var init = function() {
var height = mUtil.getViewPort().height - topbarAsideTabs.outerHeight(true) - 60;
// init settings scrollable content
settings.css('height', height);
mApp.initScroller(settings, {});
};
init();
// reinit on window resize
mUtil.addResizeHandler(init);
};
var initLogs = function() {
// init dropdown tabbable content
var logs = $('#m_quick_sidebar_tabs_logs');
if (logs.length === 0) {
return;
}
var init = function() {
var height = mUtil.getViewPort().height - topbarAsideTabs.outerHeight(true) - 60;
// init settings scrollable content
logs.css('height', height);
mApp.initScroller(logs, {});
};
init();
// reinit on window resize
mUtil.addResizeHandler(init);
};
var initOffcanvasTabs = function() {
initMessages();
initSettings();
initLogs();
};
var initOffcanvas = function() {
topbarAside.mOffcanvas({
class: 'm-quick-sidebar',
overlay: true,
close: topbarAsideClose,
toggle: topbarAsideToggle
});
// run once on first time dropdown shown
topbarAside.mOffcanvas().one('afterShow', function() {
mApp.block(topbarAside);
setTimeout(function() {
mApp.unblock(topbarAside);
topbarAsideContent.removeClass('m--hide');
initOffcanvasTabs();
}, 1000);
});
};
return {
init: function() {
console.log('Inside Init(): ', Date.now());
console.log($('#m_quick_sidebar')); // topbarAside is undefined here!
topbarAside = $('#m_quick_sidebar');
topbarAsideTabs = $('#m_quick_sidebar_tabs');
topbarAsideClose = $('#m_quick_sidebar_close');
topbarAsideToggle = $('#m_quick_sidebar_toggle');
topbarAsideContent = topbarAside.find('.m-quick-sidebar__content');
if (topbarAside.length === 0) {
return;
}
initOffcanvas();
}
};
})(mUtil, mApp, $);
$(document).ready(function() {
console.log('document.ready: ', Date.now());
mQuickSidebar.init();
});

"Uncaught TypeError: undefined is not a function" console error appearing

I'm getting a console error (Uncaught TypeError: undefined is not a function) on line 156 on load and I can't figure it out for the life of me. I've provided the line in question and the full context its in below. Also, I added the site link in case it helps. I would appreciate any and all help/advice.
Site link
Here is the line in question (156): if (!$imgs.length) {return $.Deferred.resolve().promise();}
Here is the full code: http://pastebin.com/Ext4TwdP#
//*********************************************************
// Let's start, shall we?
//*********************************************************
jQuery(document).ready(function($) {
//*********************************************************
// Global variables
//*********************************************************
// Morphing icons
var myIcons = new SVGMorpheus('#iconset', {
duration: 250,
rotation: 'none'
});
//*********************************************************
// Turn off all Ajax caching (IE caches $.load)
//*********************************************************
$.ajaxSetup({
cache: false
});
//*********************************************************
// Preloader
//*********************************************************
window.addEventListener('DOMContentLoaded', function() {
$('#projects-list, footer p').hide();
new QueryLoader2(document.querySelector("body"), {
barColor: "#f30",
backgroundColor: "#000",
barHeight: 1,
minimumTime: 200,
fadeOutTime: 0,
onComplete: function() {
$('.site-overlay').remove();
$('#masthead').slideDown(100, function(){
$('#projects-list, footer p').show().addClass('fadeInUp');
});
// Set a timeout because 100ms is too quick
$(function() {
setTimeout(function() {
$('#projects-list, footer p').removeClass('fadeInUp');
}, 500);
});
}
});
});
//*********************************************************
// Small features
//*********************************************************
// Set top margin for #content to always match the height of the top header
function resize() {
var headerTop = $('#masthead').outerHeight();
(headerTop != parseInt($('#content').css('margin-top').slice(0, -2))) ? $('#content').stop().animate({'margin-top': headerTop}, 150) : console.log('');
}
resize();
window.onresize = resize;
// Hide header when scrolling down and show header when scrolling up
var lastScrollTop = 0;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if (st < lastScrollTop || st === 0){
$('#masthead').removeClass('unpinned');
} else {
$('#masthead').addClass('unpinned');
}
lastScrollTop = st;
});
//*********************************************************
// Project hovers
//*********************************************************
$('#content').on('mouseenter', 'article.project', function(){
// If loading icon doesn't exist in the DOM...
if ( !$('.overlay').find('.loading-icon').length) {
// And if the project wrapper is activated...
if ( $(this).closest('#main').find('#project-wrapper').hasClass('activated') ) {
$(this).addClass('hover');
} else {
$(this).addClass('hover grayscale grayscale-fade');
}
// If loading icon exists in the DOM...
} else {
$(this).find('.post-link').hide();
}
// Dirty fix for 1px white flicker on hover (Chrome)
var overlayWidth = $('article.project').outerWidth();
$('.overlay').css({
marginLeft: -1,
width: overlayWidth + 2
});
}).on('mouseleave', 'article.project', function(){
// If #project-wrapper is activated...
if ( $(this).closest('#main').find('#project-wrapper').hasClass('activated') ) {
$(this).removeClass('hover');
$(this).find('.post-link').show();
// If #project-wrapper is not activated...
} else {
// If loading icon is present...
if ( $(this).find('.loading-icon').length ) {
// Only remove the 'hover' class
$(this).removeClass('hover');
// If loading icon is not present...
} else {
// Remove all classes
$(this).removeClass('hover grayscale grayscale-fade');
$(this).find('.post-link').show();
}
}
});
// Adjust the project titles so they always fit the container nicely
function adjustTitle() {
var thumbWidth = $('article.project > img').outerWidth();
if (thumbWidth <= 220) {
$('.overlay > h3').addClass('mobile');
} else {
$('.overlay > h3').removeClass('mobile');
}
}
$(window).on('resize', adjustTitle);
//*********************************************************
// Projects
//*********************************************************
(function($) {
// Function to allow an event to fire after all images are loaded
$.fn.imagesLoaded = function () {
$imgs = this.find('img[src!=""]');
// if there's no images, just return an already resolved promise
if (!$imgs.length) {return $.Deferred.resolve().promise();}
// for each image, add a deferred object to the array which resolves when the image is loaded
var dfds = [];
$imgs.each(function(){
var dfd = $.Deferred();
dfds.push(dfd);
var img = new Image();
img.onload = function(){dfd.resolve();}
img.src = this.src;
});
// return a master promise object which will resolve when all the deferred objects have resolved
// IE - when all the images are loaded
return $.when.apply($,dfds);
}
// Function for additional styling
function projectStyles() {
// Check the first slide input
$('#slider input:first').attr('checked', 'checked');
$('#project-wrapper').addClass('activated');
// Make the articles grey again after activation
$('article.project').addClass('grayscale grayscale-fade').css('opacity', '0.4');
// CSS effects
$('.post-container').addClass('fadeInUp');
$('.close-button').addClass('fadeInDown');
// Remove pesky, sticky 'hover' class
$('article.project').removeClass('hover');
}
// Open the project container
function openProject() {
var post_id = $(this).data('id'), // data-id attribute for .post-link
ajaxURL = site.custom_ajax; // Ajax URL localized from functions.php
// Add a loading icon
$('<span class="loading-icon"></span>').insertBefore(this);
// Add the 'active' class to make sure the div stays dark while loading
$(this).closest('article.project').addClass('active');
// Make all the articles grey when an article is clicked
$('article.project').addClass('grayscale grayscale-fade').css('opacity', '0.4');
// Remove the corner ribbon
$('article').removeClass('current');
$('.corner-ribbon').remove();
// Get the response from the Ajax function
$.ajax({
type: 'POST',
url: ajaxURL,
context: this,
data: {'action': 'load-content', post_id: post_id },
success: function(response) {
// Add a corner ribbon to note the current activated project
$(this).closest('article.project').removeClass('active').addClass('current');
$('<div class="corner-ribbon">Current</div>').prependTo('article.current');
// Wait until all images are loaded
$('#project-container').html(response).imagesLoaded().then(function() {
// Remove the loading icon
$('.loading-icon').remove();
// If the user has scrolled...
if ($(window).scrollTop() !== 0) {
// First scroll the page to the top
$('html, body').animate({
scrollTop : 0
},400, function() {
// Make the max-height of the container exact for a smoother transition
function matchContainerHeight() {
var containerHeight = $('#project-container').outerHeight();
$('#project-wrapper.activated').css('max-height', containerHeight);
}
setTimeout(matchContainerHeight, 100);
$(window).on('resize', matchContainerHeight);
projectStyles();
});
// If the user has not scrolled...
} else {
// Make the max-height of the container exact for a smoother transition
function matchContainerHeight() {
var containerHeight = $('#project-container').outerHeight();
$('#project-wrapper.activated').css('max-height', containerHeight);
}
setTimeout(matchContainerHeight, 100);
$(window).on('resize', matchContainerHeight);
projectStyles();
}
return false;
});
}
});
}
// User event
$('#content').on('click', '.post-link', function(e) {
e.preventDefault();
var projectTitle = $(this).data('title'), // data-title attribute for .post-link
projectSlug = $(this).data('slug') // data-slug attribute for .post-link
// Calls openProject() in context of 'this' (.post-link)
openProject.call(this);
$('head').find('title').text(projectTitle + ' | Keebs');
});
})(jQuery);
//*********************************************************
// Close button
//*********************************************************
(function($) {
// Close the project container
function closeProject() {
// Remove classes
$(this).removeClass('fadeInDown');
$('#project-wrapper').removeClass('activated').css('max-height', '');
$('article.project').removeClass('grayscale grayscale-fade').css('opacity', '1');
$('.post-container').removeClass('fadeInUp');
$('article').removeClass('current');
// Remove the corner ribbon since no projects are currently activated
$('.corner-ribbon').remove();
// Set the height of the project wrapper back to 0
$('body.single #project-wrapper').css('max-height', 0);
// Change the title of the document
$('head').find('title').text(site.title);
}
// User event
$('#content').on('click', '.close-button', function(e) {
e.preventDefault();
closeProject();
});
})(jQuery);
//*********************************************************
// Home button
//*********************************************************
(function($) {
// Load the Home page
function loadHome() {
var contactButton = $('#contact-button');
$('#content').fadeOut(50, function() {
$('<span class="loading-icon page-loading-icon"></span>').insertBefore('#content');
}).load(site.url + '/ #primary', function() {
$('.page-loading-icon').remove();
$(this).fadeIn(50);
$('body').removeClass('contact');
$('#contact-info, #clients').removeClass('fadeInUp');
$('#projects-list').addClass('fadeInUp');
$('body.single #project-wrapper').css('max-height', 0);
});
// Change the Projects button to 'Contact'
if ($('body').hasClass('contact')) {
$(contactButton).removeClass('project-button').addClass('contact-button').attr('data-title', 'Get in touch').css('width', '96px').text('Get in touch').shuffleLetters();
myIcons.to('mail');
}
// Change the title of the document
$('head').find('title').text(site.title);
}
// User event
$('.site-title a').on('click', function(e) {
e.preventDefault();
// Prevent accidental double clicks
if (!$(this).data('isClicked')) {
var link = $(this);
loadHome();
link.data('isClicked', true);
setTimeout(function() {
link.removeData('isClicked')
}, 1000);
}
});
})(jQuery);
//*********************************************************
// Contact button
//*********************************************************
(function($) {
var contactButton = $('#contact-button');
// Load the Contact page
function loadContact() {
$('#content').fadeOut(50, function() {
$('<span class="loading-icon page-loading-icon"></span>').insertBefore('#content');
}).load(site.url + '/contact/ #contact-keebs', function() {
$('.page-loading-icon').remove();
$(this).fadeIn(50);
$('body').addClass('contact');
$('#projects-list').removeClass('fadeInUp');
$('#contact-info, #clients').addClass('fadeInUp');
});
// Change the Contact button to 'Projects'
$(contactButton).removeClass('contact-button').addClass('project-button').attr('data-title', 'Projects').css('width', '71px').text('Projects').shuffleLetters();
myIcons.to('work');
// Change the title of the document
$('head').find('title').text('Contact | Keebs');
}
// Load the Projects page
function loadProjects() {
$('#content').fadeOut(50, function() {
$('<span class="loading-icon page-loading-icon"></span>').insertBefore('#content');
}).load(site.url + '/ #primary', function() {
$('.page-loading-icon').remove();
$(this).fadeIn(50);
$('body').removeClass('contact');
$('#contact-info, #clients').removeClass('fadeInUp');
$('#projects-list').addClass('fadeInUp');
$('body.single #project-wrapper').css('max-height', 0);
});
// Change the Projects button to 'Contact'
$(contactButton).removeClass('project-button').addClass('contact-button').attr('data-title', 'Get in touch').css('width', '96px').text('Get in touch').shuffleLetters();
myIcons.to('mail');
// Change the title of the document
$('head').find('title').text(site.title);
}
// User event
$('#mail-wrap').on('click', function(e) {
e.preventDefault();
// Prevent accidental double clicks
if (!$(this).data('isClicked')) {
var link = $(this);
if (!contactButton.hasClass('project-button')) {
loadContact();
} else {
loadProjects();
}
link.data('isClicked', true);
setTimeout(function() {
link.removeData('isClicked')
}, 500);
}
});
})(jQuery);
//*********************************************************
// Single template
//*********************************************************
// Check the first slide input
$('body.single #slider input:first').attr('checked', 'checked');
// Set the height of the project container
$('body.single #project-container').imagesLoaded().then(function() {
var containerHeight = $('#project-container').outerHeight();
$('body.single #project-wrapper').css('max-height', containerHeight);
});
// Make the projects list grayscale if the project wrapper is activated
if ( $('body.single #project-wrapper').hasClass('activated') ) {
$('article.project').addClass('grayscale grayscale-fade').css('opacity', '0.4');
}
//*********************************************************
// Shuffle Letters by Martin Angelov
//*********************************************************
(function($){
$.fn.shuffleLetters = function(prop){
var options = $.extend({
"step" : 8, // How many times should the letters be changed
"fps" : 60, // Frames Per Second
"text" : "", // Use this text instead of the contents
"callback" : function(){} // Run once the animation is complete
},prop)
return this.each(function(){
var el = $(this),
str = "";
// Preventing parallel animations using a flag;
if(el.data('animated')){
return true;
}
el.data('animated',true);
if(options.text) {
str = options.text.split('');
}
else {
str = el.text().split('');
}
// The types array holds the type for each character;
// Letters holds the positions of non-space characters;
var types = [],
letters = [];
// Looping through all the chars of the string
for(var i=0;i<str.length;i++){
var ch = str[i];
if(ch == " "){
types[i] = "space";
continue;
}
else if(/[a-z]/.test(ch)){
types[i] = "lowerLetter";
}
else if(/[A-Z]/.test(ch)){
types[i] = "upperLetter";
}
else {
types[i] = "symbol";
}
letters.push(i);
}
el.html("");
// Self executing named function expression:
(function shuffle(start){
// This code is run options.fps times per second
// and updates the contents of the page element
var i,
len = letters.length,
strCopy = str.slice(0); // Fresh copy of the string
if(start>len){
// The animation is complete. Updating the
// flag and triggering the callback;
el.data('animated',false);
options.callback(el);
return;
}
// All the work gets done here
for(i=Math.max(start,0); i < len; i++){
// The start argument and options.step limit
// the characters we will be working on at once
if( i < start+options.step){
// Generate a random character at thsi position
strCopy[letters[i]] = randomChar(types[letters[i]]);
}
else {
strCopy[letters[i]] = "";
}
}
el.text(strCopy.join(""));
setTimeout(function(){
shuffle(start+1);
},1000/options.fps);
})(-options.step);
});
};
function randomChar(type){
var pool = "";
if (type == "lowerLetter"){
pool = "abcdefghijklmnopqrstuvwxyz0123456789";
}
else if (type == "upperLetter"){
pool = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
}
else if (type == "symbol"){
pool = ",.?/\\(^)![]{}*&^%$#'\"";
}
var arr = pool.split('');
return arr[Math.floor(Math.random()*arr.length)];
}
})(jQuery);
//*********************************************************
// iPad fix for slider
//*********************************************************
var iPadLabels = function () {
function fix() {
var labels = document.getElementsByTagName('label'),
target_id,
el;
for (var i = 0; labels[i]; i++) {
if (labels[i].getAttribute('for')) {
labels[i].onclick = labelClick;
}
}
}
function labelClick() {
el = document.getElementById(this.getAttribute('for'));
if (['radio', 'checkbox'].indexOf(el.getAttribute('type')) != -1) {
el.setAttribute('selected', !el.getAttribute('selected'));
} else {
el.focus();
}
}
return {
fix: fix
}
}();
window.onload = function () {
iPadLabels.fix();
}
//*********************************************************
// Annnd, we're done!
//*********************************************************
});
There were a couple problems with this.
1) I didn't declare the imgs variable.
2) I didn't include the () after $.Deferred.
So here's the updated code block:
// Function to allow an event to fire after all images are loaded
$.fn.imagesLoaded = function () {
var imgs = this.find('img[src!=""]');
// If there are no images, just return an already resolved promise
if (!imgs.length) {
return $.Deferred().resolve().promise();
}
// For each image, add a deferred object to the array which resolves when the image is loaded
var dfds = [];
imgs.each(function(){
var dfd = $.Deferred();
dfds.push(dfd);
var img = new Image();
img.onload = function(){dfd.resolve();};
img.src = this.src;
});
// Return a master promise object which will resolve when all the deferred objects have resolved
// IE - when all the images are loaded
return $.when.apply($, dfds);
};

Javascript file "FASW transitions" duplicating my header info. How to fix

Ok! I'm working on a wordpress site, and everything this javascript add on is supposed to do, it does...But, when I inspect element via safari develop, I notice that it's loading all of my headers scripts,meta,styles etc. into the body as well as the head. I can't figure out why. Here's what the script looks like:
function ft(params) {
var ol= document.addEventListener?"DOMContentLoaded":"load"; //on load event
var navB = params.navB || "reverse slide"; //backbrowser button effect, default empty
var but = params.but || false; //Allow transitions on input type button
var cBa = params.cBa || function() {};
function aDL(url, t, o) { //Ajax Div Load
if (window.XMLHttpRequest) {
r = new XMLHttpRequest();
} else if (window.ActiveXObject) {
r = new ActiveXObject("Microsoft.XMLHTTP");
}
if (r != undefined) {
r.onreadystatechange = function() {Ol(r, t, o);};
r.open("GET", url, true);
r.send("");
}
}
function Ol(r, t, o) { //On load div
if (r.readyState == 4) {
if (r.status == 200 || r.status == 0) {
t.innerHTML = r.responseText;
o();
} else {
t.innerHTML="Error:\n"+ r.status + "\n" +r.statusText;
}
}
}
function DE() //Div Effect
{
var dochtml = document.body.innerHTML;
document.body.innerHTML = "";
var d1 = document.createElement("div");
d1.id = "d1";
d1.style.zIndex = 2;
d1.style.position = "absolute";
d1.style.width = "100%";
d1.style.height = "100%";
d1.style.left = "0px";
d1.style.top = "0px";
document.body.appendChild(d1);
d1.innerHTML = dochtml;
var d2 = document.createElement("div");
d2.id = "d2";
d2.style.zIndex = 1;
d2.style.position = "absolute";
d2.style.width = "100%";
d2.style.height = "100%";
d2.style.left = "0px";
d2.style.top = "0px";
document.body.appendChild(d2);
return {d1: d1, d2: d2 };
}
function timeOuts(e, d1,d2)
{
setTimeout(function() { d1.className = e + " out"; }, 1);
setTimeout(function() { d2.className = e + " in"; }, 1);
setTimeout(function() {
document.body.innerHTML = d2.innerHTML;
cBa();
}, 706);
}
function slideTo(href, effect, pushstate)
{
var d = DE();
var d1 = d.d1;
var d2 = d.d2;
aDL(href, d2,
function() {
if (pushstate && window.history.pushState) window.history.pushState("", "", href);
timeOuts(effect,d1,d2);
}
);
}
function dC(e){ //Detect click event
var o;
var o=e.srcElement || e.target;
var tn = o.tagName.toLowerCase();
if (!but || tn!="input" || o.getAttribute("type")!="button") //if it is not a button
{
//try to find an anchor parent
while (tn!=="a" && tn!=="body")
{
o = o.parentNode;
tn = o.tagName.toLowerCase();
}
if (tn==="body") return;
}
var t = o.getAttribute("data-ftrans");
if (t)
{
e.preventDefault();
var hr = o.getAttribute("href") || o.getAttribute("data-href");
if (hr) slideTo(hr, t, true);
}
}
function aE(ev, el, f) { //Add event
if (el.addEventListener) // W3C DOM
el.addEventListener(ev,f,false);
else if (el.attachEvent) { // IE DOM
var r = el.attachEvent("on"+ev, f);
return r;
}
}
aE("click", window, dC);
aE(ol, document, //On load
function(ev)
{
aE("popstate", window, function(e) { //function to reload when back button is clicked
slideTo(location.pathname, navB, false);
});
}
);
}
here is the link to the site: http://www.fasw.ws/faswwp/non-jquery-page-transitions-lightweight/
I assume that thats not supposed to happen. So im trying to figure out how to keep it clean, and keep the head files loaded in the head, and only load the page content. I cannot figure this one out, some help from the pros is needed :)
FASW comes with two functions that serves as "hooks" both before and after initializing the component. you can do it like this:
(function inittrans()
{
initComponents();
var params = { /*put your options here*/ };
new ft(params);
})();
function onTransitionFinished()
{
initComponents();
}
function initComponents() {
// here is where you put your "other" javascript codes
}
Notice how your javascript codes are executed after loading your initial page and once again after the transition happened. Anyway, this is how I got the work around on it 'coz javascript codes just won't work as they are loaded by FASW via Ajax on-the-fly.

how to get the copy of object which is clicked

Hello every one i am currently working with html5 and easelJS.I have a canvas and an images on it.What I want is that when I click on the image its copy is created and and when I click on some other place at canvas my images is copied there so leaving two images on my canvas.
I want to ask is there a way by which I can know that whether I am clicking on the image or or on the canvas.and How to make a copy of my image as I have wrote some code but it removes my orignal image and place it to ther place leaving only one image on the canvas
thanks
You can solve this by storing the image that your bitmaps are built from, then re-adding them when you need to paste. Also you'll need to override Stage.prototype._handleMouseDown like this:
window.Stage.prototype._handleMouseDown = function(e){
if (this.onMouseDown) {
this.onMouseDown(new MouseEvent("onMouseDown", this.mouseX, this.mouseY, this, e));
}
var target = this._getObjectsUnderPoint(this.mouseX, this.mouseY, null, (this._mouseOverIntervalID ? 3 : 1));
if (target) {
if (target.onPress instanceof Function) {
var evt = new MouseEvent("onPress", this.mouseX, this.mouseY, target, e);
target.onPress(evt);
if (evt.onMouseMove || evt.onMouseUp) { this._activeMouseEvent = evt; }
}
this._activeMouseTarget = target;
} else {
this.onPressThrough && this.onPressThrough(e);
}
}
Then in your implementation define onPressThrough like this.
stage.onPressThrough = function(event){
console.log("paste");
paste(event.x, event.y);
}
Here is a complete working example:
$(document).ready(
function(){
var canvas = document.createElement('canvas');
$(canvas).attr('width', '1000');
$(canvas).attr('height', '1000');
$('body').append(canvas);
var stage = window.stage = new Stage(canvas);
canvas.stage = stage;
function copy(target){
window.clipboard = target;
}
function addImage(image, x, y){
var bitmap = new Bitmap(image);
bitmap.image = image;
bitmap.onPress = function(event){
console.log("copy")
copy(this.image);
}
stage.addChild(bitmap);
bitmap.x = x || 0;
bitmap.y = y || 0;
}
function paste(x, y){
window.clipboard && addImage(clipboard, x, y);
}
window.Stage.prototype._handleMouseDown = function(e){
if (this.onMouseDown) {
this.onMouseDown(new MouseEvent("onMouseDown", this.mouseX, this.mouseY, this, e));
}
var target = this._getObjectsUnderPoint(this.mouseX, this.mouseY, null, (this._mouseOverIntervalID ? 3 : 1));
if (target) {
if (target.onPress instanceof Function) {
var evt = new MouseEvent("onPress", this.mouseX, this.mouseY, target, e);
target.onPress(evt);
if (evt.onMouseMove || evt.onMouseUp) { this._activeMouseEvent = evt; }
}
this._activeMouseTarget = target;
} else {
this.onPressThrough && this.onPressThrough(e);
}
}
stage.onPressThrough = function(event){
console.log("paste");
paste(event.x, event.y);
}
var image = new Image();
image.src = "assets/images/tempimage.png";
addImage(image);
window.tick = function(){
stage.update();
}
Ticker.addListener(window);
}
)

Categories

Resources