I got a really great script found here : http://beeker.io/exit-intent-popup-script-tutorial
Here is the js (bioep.js) code :
window.bioEp = {
// Private variables
bgEl: {},
popupEl: {},
closeBtnEl: {},
shown: false,
overflowDefault: "visible",
transformDefault: "",
// Popup options
width: 400,
height: 220,
html: "",
css: "",
fonts: [],
delay: 1,
showOnDelay: false,
cookieExp: 1,
cookieManager: {
// Create a cookie
create: function(name, value, days) {
var expires = "";
if(days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
document.cookie = name + "=" + value + expires + "; path=/";
},
// Get the value of a cookie
get: function(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(";");
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == " ") c = c.substring(1, c.length);
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
}
return null;
},
// Delete a cookie
erase: function(name) {
this.create(name, "", -1);
}
},
// Handle the bioep_shown cookie
// If present and true, return true
// If not present or false, create and return false
checkCookie: function() {
// Handle cookie reset
if(this.cookieExp <= 0) {
this.cookieManager.erase("bioep_shown");
return false;
}
// If cookie is set to true
if(this.cookieManager.get("bioep_shown") == "true")
return true;
// Otherwise, create the cookie and return false
this.cookieManager.create("bioep_shown", "true", this.cookieExp);
return false;
},
// Add font stylesheets and CSS for the popup
addCSS: function() {
// Add font stylesheets
for(var i = 0; i < this.fonts.length; i++) {
var font = document.createElement("link");
font.href = this.fonts[i];
font.type = "text/css";
font.rel = "stylesheet";
document.head.appendChild(font);
}
// Base CSS styles for the popup
var css = document.createTextNode(
"#bio_ep_bg {display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: #000; opacity: 0.3; z-index: 10001;}" +
"#bio_ep {display: none; position: fixed; width: " + this.width + "px; height: " + this.height + "px; font-family: 'Titillium Web', sans-serif; font-size: 16px; left: 50%; top: 50%; transform: translateX(-50%) translateY(-50%); -webkit-transform: translateX(-50%) translateY(-50%); -ms-transform: translateX(-50%) translateY(-50%); background-color: #fff; box-shadow: 0px 1px 4px 0 rgba(0,0,0,0.5); z-index: 10002;}" +
"#bio_ep_close {position: absolute; left: 100%; margin: -8px 0 0 -12px; width: 20px; height: 20px; color: #fff; font-size: 12px; font-weight: bold; text-align: center; border-radius: 50%; background-color: #5c5c5c; cursor: pointer;}" +
this.css
);
// Create the style element
var style = document.createElement("style");
style.type = "text/css";
style.appendChild(css);
// Insert it before other existing style
// elements so user CSS isn't overwritten
document.head.insertBefore(style, document.getElementsByTagName("style")[0]);
},
// Add the popup to the page
addPopup: function() {
// Add the background div
this.bgEl = document.createElement("div");
this.bgEl.id = "bio_ep_bg";
document.body.appendChild(this.bgEl);
// Add the popup
if(document.getElementById("bio_ep"))
this.popupEl = document.getElementById("bio_ep");
else {
this.popupEl = document.createElement("div");
this.popupEl.id = "bio_ep";
this.popupEl.innerHTML = this.html;
document.body.appendChild(this.popupEl);
}
// Add the close button
this.closeBtnEl = document.createElement("div");
this.closeBtnEl.id = "bio_ep_close";
this.closeBtnEl.appendChild(document.createTextNode("X"));
this.popupEl.insertBefore(this.closeBtnEl, this.popupEl.firstChild);
},
// Show the popup
showPopup: function() {
if(this.shown) return;
this.bgEl.style.display = "block";
this.popupEl.style.display = "block";
// Handle scaling
this.scalePopup();
// Save body overflow value and hide scrollbars
this.overflowDefault = document.body.style.overflow;
document.body.style.overflow = "hidden";
this.shown = true;
},
// Hide the popup
hidePopup: function() {
this.bgEl.style.display = "none";
this.popupEl.style.display = "none";
// Set body overflow back to default to show scrollbars
document.body.style.overflow = this.overflowDefault;
},
// Handle scaling the popup
scalePopup: function() {
var margins = { width: 40, height: 40 };
var popupSize = { width: bioEp.popupEl.offsetWidth, height: bioEp.popupEl.offsetHeight };
var windowSize = { width: window.innerWidth, height: window.innerHeight };
var newSize = { width: 0, height: 0 };
var aspectRatio = popupSize.width / popupSize.height;
// First go by width, if the popup is larger than the window, scale it
if(popupSize.width > (windowSize.width - margins.width)) {
newSize.width = windowSize.width - margins.width;
newSize.height = newSize.width / aspectRatio;
// If the height is still too big, scale again
if(newSize.height > (windowSize.height - margins.height)) {
newSize.height = windowSize.height - margins.height;
newSize.width = newSize.height * aspectRatio;
}
}
// If width is fine, check for height
if(newSize.height === 0) {
if(popupSize.height > (windowSize.height - margins.height)) {
newSize.height = windowSize.height - margins.height;
newSize.width = newSize.height * aspectRatio;
}
}
// Set the scale amount
var scaleTo = newSize.width / popupSize.width;
// If the scale ratio is 0 or is going to enlarge (over 1) set it to 1
if(scaleTo <= 0 || scaleTo > 1) scaleTo = 1;
// Save current transform style
if(this.transformDefault === "")
this.transformDefault = window.getComputedStyle(this.popupEl, null).getPropertyValue("transform");
// Apply the scale transformation
this.popupEl.style.transform = this.transformDefault + " scale(" + scaleTo + ")";
},
// Event listener initialisation for all browsers
addEvent: function (obj, event, callback) {
if(obj.addEventListener)
obj.addEventListener(event, callback, false);
else if(obj.attachEvent)
obj.attachEvent("on" + event, callback);
},
// Load event listeners for the popup
loadEvents: function() {
// Track mouseout event on document
this.addEvent(document, "mouseout", function(e) {
e = e ? e : window.event;
var from = e.relatedTarget || e.toElement;
// Reliable, works on mouse exiting window and user switching active program
if(!from || from.nodeName === "HTML")
bioEp.showPopup();
});
// Handle the popup close button
this.addEvent(this.closeBtnEl, "click", function() {
bioEp.hidePopup();
});
// Handle window resizing
this.addEvent(window, "resize", function() {
bioEp.scalePopup();
});
},
// Set user defined options for the popup
setOptions: function(opts) {
this.width = (typeof opts.width === 'undefined') ? this.width : opts.width;
this.height = (typeof opts.height === 'undefined') ? this.height : opts.height;
this.html = (typeof opts.html === 'undefined') ? this.html : opts.html;
this.css = (typeof opts.css === 'undefined') ? this.css : opts.css;
this.fonts = (typeof opts.fonts === 'undefined') ? this.fonts : opts.fonts;
this.delay = (typeof opts.delay === 'undefined') ? this.delay : opts.delay;
this.showOnDelay = (typeof opts.showOnDelay === 'undefined') ? this.showOnDelay : opts.showOnDelay;
this.cookieExp = (typeof opts.cookieExp === 'undefined') ? this.cookieExp : opts.cookieExp;
},
// Ensure the DOM has loaded
domReady: function(callback) {
(document.readyState === "interactive" || document.readyState === "complete") ? callback() : this.addEvent(document, "DOMContentLoaded", callback);
},
// Initialize
init: function(opts) {
// Handle options
if(typeof opts !== 'undefined')
this.setOptions(opts);
// Add CSS here to make sure user HTML is hidden regardless of cookie
this.addCSS();
// Once the DOM has fully loaded
this.domReady(function() {
// Handle the cookie
if(bioEp.checkCookie()) return;
// Add the popup
bioEp.addPopup();
// Load events
setTimeout(function() {
bioEp.loadEvents();
if(bioEp.showOnDelay)
bioEp.showPopup();
}, bioEp.delay * 1000);
});
}
}
And here is the HTML code:
<script type="text/javascript" src="bioep.js"></script>
<script type="text/javascript">
bioEp.init({
html: '<div id="#leaving-content">The content i want to print</div>',
css: '#leaving-content {padding: 5%;}'});
</script>
This script allow to open a pop-up when user try to leave the page. Pretty nice work. But i'm a great noob and for a personnal project i try to adapt this code to be able to run a pop-under with an another website inside an not only my own html code (like an iframe). Can you help me please ?
Thank you !
No need for such scripts if you only want it to work for the back button, here's some simple code to do the job (requires jQuery).
var popupWebsite = "http://seapip.com";
if (window.history && window.history.pushState) {
window.history.pushState('forward', null, './');
}
$(window).on('popstate', function() {
$("html").append("<iframe src="+popupWebsite +" style=\"position: fixed; top: 0; left: 0; width: 100%; height: 100%;\"></iframe>")
});
Related
I added in a ticker my teacher recommended me from jQuery and it works great but when the text is done, it doesn't loop immediately. The text stops coming from the right, just goes of the screen on the left and when it's completely gone the whole thing starts over. I was hoping someone knows what I have to add/change to the code to make it loop directly when the first round of text in done.
(function ($) {
$.fn.newsTicker = function(options) {
if($(this).length < 1) return this;
var opt = $.extend(true,{
base : {
width : 2100,
time : 40000
},
itemWidth : "auto",
ticker : ".ti_news",
tickerClone : "ti_clone",
wrapper : ".ti_wrapper",
slide : ".ti_slide",
content : ".ti_content",
callbacks : {
beforeLoad : function($Ticker){},
onLoad : function($current,$Ticker){},
beforeAnimation : function($old,$current){},
completeAnimation : function($old,$current){},
isPaused : function($current,$Ticker){},
isResumed : function($current,$Ticker){}
},
core : {
_getTime : function(w){
baseMargin=(typeof $contentTickers === "undefined") ? 0 : $contentTickers.first().css("margin-left");
baseMargin=(baseMargin<0)?baseMargin:0;
return opt.base.time * (w / (baseMargin + opt.base.width));
},
_contentWidth : function($tickers){
var w = 0;
if(opt.itemWidth !== "auto" && opt.itemWidth !== 0){
w = $tickers.length * opt.itemWidth;
$tickers.width(opt.itemWidth);
}else{
$tickers.each(function(){w = w + $(this).width()});
}
return Math.ceil(w+2);
}
}
},options);
$(this).each(function(){
var $Ticker = $(this);
$Ticker.data("ticker",{
stop:true,
animation:null
});
opt.callbacks.beforeLoad($(this));
var $notizieTicker = $Ticker.find(opt.ticker),
$wrapperTicker = $Ticker.find(opt.wrapper),
$ti_slide = $Ticker.find(opt.slide),
$contentTicker = $Ticker.find(opt.content);
var width_content = opt.core._contentWidth($notizieTicker),
wrapper_width = $wrapperTicker.width(),
$current,
$old = $();
if(width_content < wrapper_width){
var x = Math.ceil(wrapper_width/width_content),
$clone = $contentTicker.children().clone();
for (var i = 1; i <= x; i++) {
$contentTicker.append($clone.clone());
}
if(!opt.itemWidth || opt.itemWidth == "auto"){
width_content = width_content*i;
}else{
width_content = ($contentTicker.children().length * opt.itemWidth);
}
}
if(width_content * 3 > $ti_slide.width()) $ti_slide.width((width_content*3)+100);
$ti_slide.append($contentTicker.clone().addClass(opt.tickerClone));
$ti_slide.append($contentTicker.clone().addClass(opt.tickerClone));
var $contentTickers = $Ticker.find(opt.content);
$contentTickers.width(width_content);
$current = $contentTickers.first();
opt.callbacks.onLoad($current,$(this));
var animateTicker = function(m){
$ti_slide.append($old);
var m = (typeof m == "undefined") ? 0 : m ;
$old.css("margin-left",m);
opt.callbacks.beforeAnimation($old,$current);
$Ticker.data("stop",false);
var tickerAnimation = $current.animate({
"margin-left" : -width_content,
},{
easing : "linear",
duration : opt.core._getTime(width_content),
complete : function(){
$old = $current;
$current = $current.next();
opt.callbacks.completeAnimation($old,$current);
animateTicker.call($Ticker);
}
});
$Ticker.data("animation",tickerAnimation);
}
animateTicker.call(this);
$Ticker[0].pauseTicker = function(){
$Ticker.each(function(){
var _anim = $Ticker.data("animation"),
_stop = $Ticker.data("stop");
if(!!_stop || !_anim) return;
_anim.stop();
$Ticker.data("stop",true);
opt.callbacks.isPaused();
});
}
$Ticker[0].startTicker = function(){
$Ticker.each(function(){
if(!$Ticker.data("stop")) return;
animateTicker($Ticker);
$Ticker.data("stop",false);
opt.callbacks.isResumed();
});
}
});
return this;
};
$.fn.newsTickerPause = function(){
$(this).each(function(){
if("pauseTicker" in $(this)[0]) $(this)[0].pauseTicker();
});
}
$.fn.newsTickerResume = function(){
$(this).each(function(){
if("startTicker" in $(this)[0]) $(this)[0].startTicker();
});
}
}( jQuery ));
.TickerNews {
width: 100%;
height: 50px;
line-height: 50px;
}
.ti_wrapper {
width: 100%;
position: relative;
overflow: hidden;
height: 50px;
}
.ti_slide {
width: 30000px;
position: relative;
left: 0;
top: 0;
}
.ti_content {
width: 8000px;
position: relative;
float: left;
}
.ti_news { float: left; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="upcoming">
<div class="TickerNews" id="T3">
<div class="ti_wrapper">
<div class="ti_slide">
<div class="ti_content">
<div class="ti_news">
text
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(function(){
_Ticker = $(".TickerNews").newsTicker();
});
</script>
I am using the lightbox jquery plugin to open a lightbox when a user clicks on a product. Often the lightbox content stretches below the fold, and at the moment the right scrollbar moves the entire page when you scroll down.
I'd like it to work like the pinterest lightbox, whereby the right scrollbar only scrolls the lightbox, and the rest of the page stays fixed. I've seen a few posts on this, but nothing seems to work for me.
Problem is I want the lightbox to scroll if the content is bigger than the viewport of the browser but not the background.
CSS:
#lightbox{ position: absolute; left: 0; width: 100%; z-index: 100; text-align: center; line-height: 0;}
#lightbox img{ width: auto; height: auto;}
#lightbox a img{ border: none; }
#outerImageContainer{ position: relative; background-color: #fff; width: 250px; height: 250px; margin: 0 auto; }
#imageContainer{ padding: 10px; }
#loading{ position: absolute; top: 40%; left: 0%; height: 25%; width: 100%; text-align: center; line-height: 0; }
#hoverNav{ position: absolute; top: 0; left: 0; height: 100%; width: 100%; z-index: 10; }
#imageContainer>#hoverNav{ left: 0;}
#hoverNav a{ outline: none;}
#prevLink, #nextLink{ width: 49%; height: 100%; background-image: url(data:image2/gif;base64,AAAA); /* Trick IE into showing hover */ display: block; }
#prevLink { left: 0; float: left;}
#nextLink { right: 0; float: right;}
#prevLink:hover, #prevLink:visited:hover { background: url(../images2/prevlabel.gif) left 15% no-repeat; }
#nextLink:hover, #nextLink:visited:hover { background: url(../images2/nextlabel.gif) right 15% no-repeat; }
#imageDataContainer{ font: 10px Verdana, Helvetica, sans-serif; background-color: #fff; margin: 0 auto; line-height: 1.4em; overflow: auto; width: 100% ; }
#imageData{ padding:0 10px; color: #666; }
#imageData #imageDetails{ width: 70%; float: left; text-align: left; }
#imageData #caption{ font-weight: bold; }
#imageData #numberDisplay{ display: block; clear: left; padding-bottom: 1.0em; }
#imageData #bottomNavClose{ width: 66px; float: right; padding-bottom: 0.7em; outline: none;}
#overlay{ position: absolute; top: 0; left: 0; z-index: 90; width: 100%; height: 500px; background-color: #000; }
JS:
// -----------------------------------------------------------------------------------
//
// Lightbox v2.04
// by Lokesh Dhakar - http://www.lokeshdhakar.com
// Last Modification: 2/9/08
//
// For more information, visit:
// http://lokeshdhakar.com/projects/lightbox2/
//
// Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
// - Free for use in both personal and commercial projects
// - Attribution requires leaving author name, author link, and the license info intact.
//
// Thanks: Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.com), and Thomas Fuchs(mir.aculo.us) for ideas, libs, and snippets.
// Artemy Tregubenko (arty.name) for cleanup and help in updating to latest ver of proto-aculous.
//
// -----------------------------------------------------------------------------------
/*
Table of Contents
-----------------
Configuration
Lightbox Class Declaration
- initialize()
- updateImageList()
- start()
- changeImage()
- resizeImageContainer()
- showImage()
- updateDetails()
- updateNav()
- enableKeyboardNav()
- disableKeyboardNav()
- keyboardAction()
- preloadNeighborImages()
- end()
Function Calls
- document.observe()
*/
// -----------------------------------------------------------------------------------
//
// Configurationl
//
LightboxOptions = Object.extend({
fileLoadingImage: 'images2/loading.gif',
fileBottomNavCloseImage: 'images2/closelabel.gif',
overlayOpacity: 0.8, // controls transparency of shadow overlay
animate: true, // toggles resizing animations
resizeSpeed: 7, // controls the speed of the image resizing animations (1=slowest and 10=fastest)
borderSize: 10, //if you adjust the padding in the CSS, you will need to update this variable
// When grouping images this is used to write: Image # of #.
// Change it for non-english localization
labelImage: "Image",
labelOf: "of"
}, window.LightboxOptions || {});
// -----------------------------------------------------------------------------------
var Lightbox = Class.create();
Lightbox.prototype = {
imageArray: [],
activeImage: undefined,
// initialize()
// Constructor runs on completion of the DOM loading. Calls updateImageList and then
// the function inserts html at the bottom of the page which is used to display the shadow
// overlay and the image container.
//
initialize: function() {
this.updateImageList();
this.keyboardAction = this.keyboardAction.bindAsEventListener(this);
if (LightboxOptions.resizeSpeed > 10) LightboxOptions.resizeSpeed = 10;
if (LightboxOptions.resizeSpeed < 1) LightboxOptions.resizeSpeed = 1;
this.resizeDuration = LightboxOptions.animate ? ((11 - LightboxOptions.resizeSpeed) * 0.15) : 0;
this.overlayDuration = LightboxOptions.animate ? 0.2 : 0; // shadow fade in/out duration
// When Lightbox starts it will resize itself from 250 by 250 to the current image dimension.
// If animations are turned off, it will be hidden as to prevent a flicker of a
// white 250 by 250 box.
var size = (LightboxOptions.animate ? 250 : 1) + 'px';
// Code inserts html at the bottom of the page that looks similar to this:
//
// <div id="overlay"></div>
// <div id="lightbox">
// <div id="outerImageContainer">
// <div id="imageContainer">
// <img id="lightboxImage">
// <div style="" id="hoverNav">
//
//
// </div>
// <div id="loading">
// <a href="#" id="loadingLink">
// <img src="images/loading.gif">
// </a>
// </div>
// </div>
// </div>
// <div id="imageDataContainer">
// <div id="imageData">
// <div id="imageDetails">
// <span id="caption"></span>
// <span id="numberDisplay"></span>
// </div>
// <div id="bottomNav">
// <a href="#" id="bottomNavClose">
// <img src="images/close.gif">
// </a>
// </div>
// </div>
// </div>
// </div>
var objBody = $$('body')[0];
objBody.appendChild(Builder.node('div',{id:'overlay'}));
objBody.appendChild(Builder.node('div',{id:'lightbox'}, [
Builder.node('div',{id:'outerImageContainer'},
Builder.node('div',{id:'imageContainer'}, [
Builder.node('img',{id:'lightboxImage'}),
Builder.node('div',{id:'hoverNav'}, [
Builder.node('a',{id:'prevLink', href: '#' }),
Builder.node('a',{id:'nextLink', href: '#' })
]),
Builder.node('div',{id:'loading'},
Builder.node('a',{id:'loadingLink', href: '#' },
Builder.node('img', {src: LightboxOptions.fileLoadingImage})
)
)
])
),
Builder.node('div', {id:'imageDataContainer'},
Builder.node('div',{id:'imageData'}, [
Builder.node('div',{id:'imageDetails'}, [
Builder.node('span',{id:'caption'}),
Builder.node('span',{id:'numberDisplay'})
]),
Builder.node('div',{id:'bottomNav'},
Builder.node('a',{id:'bottomNavClose', href: '#' },
Builder.node('img', { src: LightboxOptions.fileBottomNavCloseImage })
)
)
])
)
]));
$('overlay').hide().observe('click', (function() { this.end(); }).bind(this));
$('lightbox').hide().observe('click', (function(event) { if (event.element().id == 'lightbox') this.end(); }).bind(this));
$('outerImageContainer').setStyle({ width: size, height: size });
$('prevLink').observe('click', (function(event) { event.stop(); this.changeImage(this.activeImage - 1); }).bindAsEventListener(this));
$('nextLink').observe('click', (function(event) { event.stop(); this.changeImage(this.activeImage + 1); }).bindAsEventListener(this));
$('loadingLink').observe('click', (function(event) { event.stop(); this.end(); }).bind(this));
$('bottomNavClose').observe('click', (function(event) { event.stop(); this.end(); }).bind(this));
var th = this;
(function(){
var ids =
'overlay lightbox outerImageContainer imageContainer lightboxImage hoverNav prevLink nextLink loading loadingLink ' +
'imageDataContainer imageData imageDetails caption numberDisplay bottomNav bottomNavClose';
$w(ids).each(function(id){ th[id] = $(id); });
}).defer();
},
//
// updateImageList()
// Loops through anchor tags looking for 'lightbox' references and applies onclick
// events to appropriate links. You can rerun after dynamically adding images w/ajax.
//
updateImageList: function() {
this.updateImageList = Prototype.emptyFunction;
document.observe('click', (function(event){
var target = event.findElement('a[rel^=lightbox]') || event.findElement('area[rel^=lightbox]');
if (target) {
event.stop();
this.start(target);
}
}).bind(this));
},
//
// start()
// Display overlay and lightbox. If image is part of a set, add siblings to imageArray.
//
start: function(imageLink) {
$$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden' });
// stretch overlay to fill page and fade in
var arrayPageSize = this.getPageSize();
$('overlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' });
new Effect.Appear(this.overlay, { duration: this.overlayDuration, from: 0.0, to: LightboxOptions.overlayOpacity });
this.imageArray = [];
var imageNum = 0;
if ((imageLink.rel == 'lightbox')){
// if image is NOT part of a set, add single image to imageArray
this.imageArray.push([imageLink.href, imageLink.title]);
} else {
// if image is part of a set..
this.imageArray =
$$(imageLink.tagName + '[href][rel="' + imageLink.rel + '"]').
collect(function(anchor){ return [anchor.href, anchor.title]; }).
uniq();
while (this.imageArray[imageNum][0] != imageLink.href) { imageNum++; }
}
// calculate top and left offset for the lightbox
var arrayPageScroll = document.viewport.getScrollOffsets();
var lightboxTop = arrayPageScroll[1] + (document.viewport.getHeight() / 10);
var lightboxLeft = arrayPageScroll[0];
this.lightbox.setStyle({ top: lightboxTop + 'px', left: lightboxLeft + 'px' }).show();
this.changeImage(imageNum);
},
//
// changeImage()
// Hide most elements and preload image in preparation for resizing image container.
//
changeImage: function(imageNum) {
this.activeImage = imageNum; // update global var
// hide elements during transition
if (LightboxOptions.animate) this.loading.show();
this.lightboxImage.hide();
this.hoverNav.hide();
this.prevLink.hide();
this.nextLink.hide();
// HACK: Opera9 does not currently support scriptaculous opacity and appear fx
this.imageDataContainer.setStyle({opacity: .0001});
this.numberDisplay.hide();
var imgPreloader = new Image();
// once image is preloaded, resize image container
imgPreloader.onload = (function(){
this.lightboxImage.src = this.imageArray[this.activeImage][0];
this.resizeImageContainer(imgPreloader.width, imgPreloader.height);
}).bind(this);
imgPreloader.src = this.imageArray[this.activeImage][0];
},
//
// resizeImageContainer()
//
resizeImageContainer: function(imgWidth, imgHeight) {
// get current width and height
var widthCurrent = this.outerImageContainer.getWidth();
var heightCurrent = this.outerImageContainer.getHeight();
// get new width and height
var widthNew = (imgWidth + LightboxOptions.borderSize * 2);
var heightNew = (imgHeight + LightboxOptions.borderSize * 2);
// scalars based on change from old to new
var xScale = (widthNew / widthCurrent) * 100;
var yScale = (heightNew / heightCurrent) * 100;
// calculate size difference between new and old image, and resize if necessary
var wDiff = widthCurrent - widthNew;
var hDiff = heightCurrent - heightNew;
if (hDiff != 0) new Effect.Scale(this.outerImageContainer, yScale, {scaleX: false, duration: this.resizeDuration, queue: 'front'});
if (wDiff != 0) new Effect.Scale(this.outerImageContainer, xScale, {scaleY: false, duration: this.resizeDuration, delay: this.resizeDuration});
// if new and old image are same size and no scaling transition is necessary,
// do a quick pause to prevent image flicker.
var timeout = 0;
if ((hDiff == 0) && (wDiff == 0)){
timeout = 100;
if (Prototype.Browser.IE) timeout = 250;
}
(function(){
this.prevLink.setStyle({ height: imgHeight + 'px' });
this.nextLink.setStyle({ height: imgHeight + 'px' });
this.imageDataContainer.setStyle({ width: widthNew + 'px' });
this.showImage();
}).bind(this).delay(timeout / 1000);
},
//
// showImage()
// Display image and begin preloading neighbors.
//
showImage: function(){
this.loading.hide();
new Effect.Appear(this.lightboxImage, {
duration: this.resizeDuration,
queue: 'end',
afterFinish: (function(){ this.updateDetails(); }).bind(this)
});
this.preloadNeighborImages();
},
//
// updateDetails()
// Display caption, image number, and bottom nav.
//
updateDetails: function() {
// if caption is not null
if (this.imageArray[this.activeImage][1] != ""){
this.caption.update(this.imageArray[this.activeImage][1]).show();
}
// if image is part of set display 'Image x of x'
if (this.imageArray.length > 1){
this.numberDisplay.update( LightboxOptions.labelImage + ' ' + (this.activeImage + 1) + ' ' + LightboxOptions.labelOf + ' ' + this.imageArray.length).show();
}
new Effect.Parallel(
[
new Effect.SlideDown(this.imageDataContainer, { sync: true, duration: this.resizeDuration, from: 0.0, to: 1.0 }),
new Effect.Appear(this.imageDataContainer, { sync: true, duration: this.resizeDuration })
],
{
duration: this.resizeDuration,
afterFinish: (function() {
// update overlay size and update nav
var arrayPageSize = this.getPageSize();
this.overlay.setStyle({ height: arrayPageSize[1] + 'px' });
this.updateNav();
}).bind(this)
}
);
},
//
// updateNav()
// Display appropriate previous and next hover navigation.
//
updateNav: function() {
this.hoverNav.show();
// if not first image in set, display prev image button
if (this.activeImage > 0) this.prevLink.show();
// if not last image in set, display next image button
if (this.activeImage < (this.imageArray.length - 1)) this.nextLink.show();
this.enableKeyboardNav();
},
//
// enableKeyboardNav()
//
enableKeyboardNav: function() {
document.observe('keydown', this.keyboardAction);
},
//
// disableKeyboardNav()
//
disableKeyboardNav: function() {
document.stopObserving('keydown', this.keyboardAction);
},
//
// keyboardAction()
//
keyboardAction: function(event) {
var keycode = event.keyCode;
var escapeKey;
if (event.DOM_VK_ESCAPE) { // mozilla
escapeKey = event.DOM_VK_ESCAPE;
} else { // ie
escapeKey = 27;
}
var key = String.fromCharCode(keycode).toLowerCase();
if (key.match(/x|o|c/) || (keycode == escapeKey)){ // close lightbox
this.end();
} else if ((key == 'p') || (keycode == 37)){ // display previous image
if (this.activeImage != 0){
this.disableKeyboardNav();
this.changeImage(this.activeImage - 1);
}
} else if ((key == 'n') || (keycode == 39)){ // display next image
if (this.activeImage != (this.imageArray.length - 1)){
this.disableKeyboardNav();
this.changeImage(this.activeImage + 1);
}
}
},
//
// preloadNeighborImages()
// Preload previous and next images.
//
preloadNeighborImages: function(){
var preloadNextImage, preloadPrevImage;
if (this.imageArray.length > this.activeImage + 1){
preloadNextImage = new Image();
preloadNextImage.src = this.imageArray[this.activeImage + 1][0];
}
if (this.activeImage > 0){
preloadPrevImage = new Image();
preloadPrevImage.src = this.imageArray[this.activeImage - 1][0];
}
},
//
// end()
//
end: function() {
this.disableKeyboardNav();
this.lightbox.hide();
new Effect.Fade(this.overlay, { duration: this.overlayDuration });
$$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });
},
//
// getPageSize()
//
getPageSize: function() {
var xScroll, yScroll;
if (window.innerHeight && window.scrollMaxY) {
xScroll = window.innerWidth + window.scrollMaxX;
yScroll = window.innerHeight + window.scrollMaxY;
} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
xScroll = document.body.scrollWidth;
yScroll = document.body.scrollHeight;
} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
xScroll = document.body.offsetWidth;
yScroll = document.body.offsetHeight;
}
var windowWidth, windowHeight;
if (self.innerHeight) { // all except Explorer
if(document.documentElement.clientWidth){
windowWidth = document.documentElement.clientWidth;
} else {
windowWidth = self.innerWidth;
}
windowHeight = self.innerHeight;
} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
windowWidth = document.documentElement.clientWidth;
windowHeight = document.documentElement.clientHeight;
} else if (document.body) { // other Explorers
windowWidth = document.body.clientWidth;
windowHeight = document.body.clientHeight;
}
// for small pages with total height less then height of the viewport
if(yScroll < windowHeight){
pageHeight = windowHeight;
} else {
pageHeight = yScroll;
}
// for small pages with total width less then width of the viewport
if(xScroll < windowWidth){
pageWidth = xScroll;
} else {
pageWidth = windowWidth;
}
return [pageWidth,pageHeight];
}
}
document.observe('dom:loaded', function () { new Lightbox(); });
Here's a class that'll allow you to do just that:
class ScrollLock {
constructor () {
this.pageBody = document.querySelector('body');
this.scrollY = 0;
}
saveScrollY = (num) => {
this.scrollY = num;
}
setScrollY = (num) => {
window.scroll(0, num);
}
setScrollOffset = (vOffset) => {
this.pageBody.style.top = `-${vOffset}px`;
}
freezeBodyScroll = () => {
this.saveScrollY(window.scrollY);
this.setScrollOffset(this.scrollY);
this.pageBody.classList.add('is-fixed');
}
unfreezeBodyScroll = () => {
this.pageBody.classList.remove('is-fixed');
// Don't reset scroll position if lock hasn't occurred
if (this.scrollY === 0) return;
this.setScrollOffset(0);
this.setScrollY(this.scrollY);
this.saveScrollY(0);
}
}
Include the following style declaration:
// In your CSS
body.is-fixed {
position: fixed;
max-width: 100%;
}
Use:
const { freezeBodyScroll, unfreezeBodyScroll } = new ScrollLock();
// Call when you open your modal
freezeBodyScroll();
// Call when you close your modal
unfreezeBodyScroll();
I'm trying to combine the functionality of two buttons into one. This is a program that enables/disables a text or image magnifier. If I enable the zoomer than I want both the text and image to magnify if they are hovered on and vice versa with disable.
How should I edit the function/code to reflect one button that controls the magnification of both image and text?
This is the function I believe is controlling the button and zooming:
$("button").click(function() {
var state = $(this).text(); // enable or disable
$(".zoom:eq(" + $(this).attr('data-id') + ")").anythingZoomer(state);
$(this).text((state === "disable") ? "enable" : "disable");
return false;
});
The full project is below
;
(function(factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = factory(require('jquery'));
} else {
factory(jQuery);
}
}(function($) {
"use strict";
$.anythingZoomer = function(el, options) {
var n, o, t, base = this;
base.$wrap = $(el);
base.wrap = el;
// Add a reverse reference to the DOM object
base.$wrap.data('zoomer', base);
base.version = '2.2.6';
base.init = function() {
base.options = o = $.extend({}, $.anythingZoomer.defaultOptions, options);
// default class names
n = $.anythingZoomer.classNames;
// true when small element is showing, false when large is visible
base.state = true;
base.enabled = true;
base.hovered = false;
base.$wrap.addClass(n.wrap).wrapInner('<span class="' + n.wrapInner + '"/>');
base.$inner = base.$wrap.find('.' + n.wrapInner);
base.$small = base.$wrap.find('.' + o.smallArea);
base.$large = base.$wrap.find('.' + o.largeArea);
base.update();
// Add classes after getting size
base.$large.addClass(n.large);
base.$small.addClass(n.small);
base.$inner
.bind('mouseenter' + n.namespace, function() {
if (!base.enabled) {
return;
}
base.saved = base.enabled;
base.hovered = true;
if (o.delay) {
clearTimeout(base.delay);
base.enabled = false;
base.delay = setTimeout(function() {
base.enabled = base.saved;
base.position.type = 'mousemove';
base.$inner.trigger(base.position);
base.reveal();
}, o.delay);
} else {
base.reveal();
}
})
.bind('mouseleave' + n.namespace, function() {
base.hovered = false;
if (!base.enabled) {
return;
}
if (o.delay) {
clearTimeout(base.delay);
base.enabled = base.saved;
}
if (base.state && base.enabled) {
// delay hiding to prevent flash if user hovers over it again
// i.e. moving from a link to the image
base.timer = setTimeout(function() {
if (base.$zoom.hasClass(n.windowed)) {
base.hideZoom(true);
}
}, 200);
}
})
.bind('mousemove' + n.namespace, function(e) {
if (!base.enabled) {
return;
}
base.position = e;
if (!base.hovered) {
return;
}
if (base.state && base.enabled) {
clearTimeout(base.timer);
// get current offsets in case page positioning has changed
// Double demo: expanded text demo will offset image demo zoom window
var off = base.$small.offset();
base.zoomAt(e.pageX - off.left, e.pageY - off.top, null, true);
}
})
.bind(o.switchEvent + (o.switchEvent !== '' ? n.namespace : ''), function() {
if (!base.enabled) {
return;
}
// toggle visible image
if (base.state) {
base.showLarge();
} else {
base.showSmall();
}
});
base.showSmall();
// add events
$.each('initialized zoom unzoom'.split(' '), function(i, f) {
if ($.isFunction(o[f])) {
base.$wrap.bind(f, o[f]);
}
});
base.initialized = true;
base.$wrap.trigger('initialized', base);
};
base.reveal = function() {
base.enabled = base.saved;
if (base.state && base.enabled) {
base.$zoom.stop(true, true).fadeIn(o.speed);
if (o.overlay) {
base.$overlay.addClass(n.overlay);
}
base.$smInner.addClass(n.hovered);
base.$wrap.trigger('zoom', base);
}
};
base.update = function() {
// make sure the large image is hidden
if (base.initialized) {
base.showSmall();
}
base.$smInner = (base.$small.find('.' + n.smallInner).length) ?
base.$small.find('.' + n.smallInner) :
base.$small.wrapInner('<span class="' + n.smallInner + '"/>').find('.' + n.smallInner);
base.$small.find('.' + n.overly).remove();
if (o.clone) {
t = base.$smInner.clone()
.removeAttr('id')
.removeClass(n.smallInner)
.addClass(n.largeInner);
if (base.$large.length) {
// large area exists, just add content
base.$large.html(t.html());
} else {
// no large area, so add it
t.wrap('<div class="' + o.largeArea + '">');
base.$small.after(t.parent());
// set base.$large again in case small area was cloned
base.$large = base.$wrap.find('.' + o.largeArea);
}
}
base.$lgInner = (base.$large.find('.' + n.largeInner).length) ?
base.$large.find('.' + n.largeInner) :
base.$large.wrapInner('<span class="' + n.largeInner + '"/>').find('.' + n.largeInner);
if (!base.$wrap.find('.' + n.zoom).length) {
base.$large.wrap('<div class="' + n.zoom + '"/>');
base.$zoom = base.$wrap.find('.' + n.zoom);
}
if (o.edit && !base.edit) {
base.edit = $('<span class="' + n.edit + '"></span>').appendTo(base.$zoom);
}
// wrap inner content with a span to get a more accurate width
// get height from either the inner content itself or the children of the inner content since span will need
// a "display:block" to get an accurate height, but adding that messes up the width
base.$zoom.show();
base.largeDim = [base.$lgInner.children().width(), Math.max(base.$lgInner.height(), base.$lgInner.children().height())];
base.zoomDim = base.last = [base.$zoom.width(), base.$zoom.height()];
base.$zoom.hide();
base.smallDim = [base.$smInner.children().width(), base.$small.height()];
base.$overlay = $('<div class="' + n.overly + '" style="position:absolute;left:0;top:0;" />').prependTo(base.$small);
base.ratio = [
base.largeDim[0] / (base.smallDim[0] || 1),
base.largeDim[1] / (base.smallDim[1] || 1)
];
base.$inner.add(base.$overlay).css({
width: base.smallDim[0],
height: base.smallDim[1]
});
};
// Show small image - Setup
base.showSmall = function() {
base.state = true;
base.$small.show();
base.$zoom
.removeClass(n.expanded)
.addClass(n.windowed + ' ' + n.zoom)
.css({
width: base.zoomDim[0],
height: base.zoomDim[1]
});
base.$inner.css({
width: base.smallDim[0],
height: base.smallDim[1]
});
};
// Switch small and large on double click
base.showLarge = function() {
base.state = false;
base.$small.hide();
base.$zoom
.stop(true, true)
.fadeIn(o.speed)
.addClass(n.expanded)
.removeClass(n.windowed + ' ' + n.zoom)
.css({
height: 'auto',
width: 'auto'
});
base.$inner.css({
width: base.largeDim[0],
height: base.largeDim[1]
});
base.$large.css({
left: 0,
top: 0,
width: base.largeDim[0],
height: base.largeDim[1]
});
};
// x,y coords -> George Washington in image demo
// base.setTarget( 82, 50, [200,200] );
// 'selector', [xOffset, yOffset], [zoomW, zoomH] -> Aug 26 in calendar demo
// base.setTarget( '.day[rel=2009-08-26]', [0, 0], [200, 200] );
base.setTarget = function(tar, sec, sz) {
var t, x = 0,
y = 0;
clearTimeout(base.timer);
if (!base.$zoom.hasClass(n.windowed)) {
base.showSmall();
}
// x, y coords
if (!isNaN(tar) && !isNaN(sec)) {
x = parseInt(tar, 10);
y = parseInt(sec, 10);
} else if (typeof(tar) === 'string' && $(tar).length) {
// '.selector', [xOffSet, yOffSet]
t = $(tar);
x = t.position().left + t.width() / 2 + (sec ? sec[0] || 0 : 0);
y = t.position().top + t.height() / 2 + (sec ? sec[1] || 0 : 0);
}
base.zoomAt(x, y, sz);
// add overlay
if (o.overlay) {
base.$overlay.addClass(n.overlay);
}
// hovered, but not really
base.$smInner.addClass(n.hovered);
// zoom window triggered
base.$wrap.trigger('zoom', base);
};
// x, y, [zoomX, zoomY] - zoomX, zoomY are the dimensions of the zoom window
base.zoomAt = function(x, y, sz, internal) {
var sx = (sz ? sz[0] || 0 : 0) || base.last[0],
sy = (sz ? sz[1] || sz[0] || 0 : 0) || base.last[1],
sx2 = sx / 2,
sy2 = sy / 2,
ex = o.edge || (o.edge === 0 ? 0 : sx2 * 0.66), // 2/3 of zoom window
ey = o.edge || (o.edge === 0 ? 0 : sy2 * 0.66), // allows edge to be zero
m = parseInt(base.$inner.css('margin-left'), 10) || base.$inner.position().left || 0;
// save new zoom size
base.last = [sx, sy];
// save x, y for external access
base.current = [x, y];
// show coordinates
if (o.edit) {
base.edit.html(Math.round(x) + ', ' + Math.round(y));
}
if ((x < -ex) || (x > base.smallDim[0] + ex) || (y < -ey) || (y > base.smallDim[1] + ey)) {
base.hideZoom(internal);
return;
} else {
// Sometimes the mouseenter event is delayed
base.$zoom.stop(true, true).fadeIn(o.speed);
}
// center zoom under the cursor
base.$zoom.css({
left: x - sx2 + m,
top: y - sy2,
width: sx,
height: sy
});
// match locations of small element to the large
base.$large.css({
left: -(x - o.offsetX - sx2 / 2) * base.ratio[0],
top: -(y - o.offsetY - sy2 / 2) * base.ratio[1]
});
};
base.hideZoom = function(internal) {
if (internal && base.$smInner.hasClass(n.hovered)) {
base.$wrap.trigger('unzoom', base);
}
base.last = base.zoomDim;
base.$zoom.stop(true, true).fadeOut(o.speed);
base.$overlay.removeClass(n.overlay);
base.$smInner.removeClass(n.hovered);
base.lastKey = null;
};
base.setEnabled = function(enable) {
base.enabled = enable;
if (enable) {
var off = base.$small.offset();
base.zoomAt(base.position.pageX - off.left, base.position.pageY - off.top, null, true);
} else {
base.showSmall();
base.hideZoom();
base.hovered = false;
}
};
// Initialize zoomer
base.init();
};
// class names used by anythingZoomer
$.anythingZoomer.classNames = {
namespace: '.anythingZoomer', // event namespace
wrap: 'az-wrap',
wrapInner: 'az-wrap-inner',
large: 'az-large',
largeInner: 'az-large-inner',
small: 'az-small',
smallInner: 'az-small-inner',
overlay: 'az-overlay', // toggled class name
overly: 'az-overly', // overlay unstyled class
hovered: 'az-hovered',
zoom: 'az-zoom',
windowed: 'az-windowed', // zoom window active
expanded: 'az-expanded', // zoom window inactive (large is showing)
edit: 'az-coords', // coordinate window
scrollzoom: 'az-scrollzoom'
};
$.anythingZoomer.defaultOptions = {
// content areas
smallArea: 'small', // class of small content area; the element with this class name must be inside of the wrapper
largeArea: 'large', // class of large content area; this class must exist inside of the wrapper. When the clone option is true, it will add this automatically
clone: false, // Make a clone of the small content area, use css to modify the style
// appearance
overlay: false, // set to true to apply overlay class "az-overlay"; false to not apply it
speed: 100, // fade animation speed (in milliseconds)
edge: 30, // How far outside the wrapped edges the mouse can go; previously called "expansionSize"
offsetX: 0, // adjust the horizontal position of the large content inside the zoom window as desired
offsetY: 0, // adjust the vertical position of the large content inside the zoom window as desired
// functionality
switchEvent: 'dblclick', // event that allows toggling between small and large elements - default is double click
delay: 0, // time to delay before revealing the zoom window.
// edit mode
edit: false // add x,y coordinates into zoom window to make it easier to find coordinates
};
$.fn.anythingZoomer = function(options, second, sx, sy) {
return this.each(function() {
var anyZoom = $(this).data('zoomer');
// initialize the zoomer but prevent multiple initializations
if (/object|undefined/.test(typeof options)) {
if (anyZoom) {
anyZoom.update();
} else {
(new $.anythingZoomer(this, options));
}
} else if (anyZoom && (typeof options === 'string' || (!isNaN(options) && !isNaN(second)))) {
if (/(en|dis)able/.test(options)) {
anyZoom.setEnabled(options === 'enable');
} else {
anyZoom.setTarget(options, second, sx, sy);
}
}
});
};
$.fn.getAnythingZoomer = function() {
return this.data('zoomer');
};
return $.anythingzoomer;
}));
/* AnythingZoomer */
.az-wrap,
.az-small,
.az-large {
position: relative;
}
.az-wrap-inner {
display: block;
margin: 0 auto;
/* center small & large content */
}
/* This wraps the large image and hides it */
.az-zoom {
background: #fff;
border: #333 1px solid;
position: absolute;
top: 0;
left: 0;
width: 150px;
height: 150px;
overflow: hidden;
z-index: 100;
display: none;
-moz-box-shadow: inset 0px 0px 4px #000;
-webkit-box-shadow: inset 0px 0px 4px #000;
box-shadow: inset 0px 0px 4px #000;
}
/* Class applied to az-mover when large image is windowed */
.az-windowed {
overflow: hidden;
position: absolute;
}
/* Class applied to az-mover when large image is fully shown */
.az-expanded {
height: auto;
width: auto;
position: static;
overflow: visible;
}
/* overlay small area */
.az-overlay {
background-color: #000;
opacity: 0.3;
filter: alpha(opacity=30);
z-index: 10;
}
/* edit mode coordinate styling */
.az-coords {
display: none;
/* hidden when expanded */
}
.az-zoom .az-coords {
display: block;
position: absolute;
top: 0;
right: 0;
background: #000;
background: rgba(0, 0, 0, 0.5);
color: #fff;
}
/* ZOOM CONTAINER */
.zoom {
display: block;
margin: 0 auto;
}
.large {
background: white;
}
/* FOR TEXT DEMO */
.small p {
font-size: 16px;
width: 700px
}
.large p {
font-size: 32px;
width: 1400px;
}
/* FOR IMAGE DEMO */
.small img {
width: 250px;
}
.large img {
width: 500px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Image and Text Magnifier</title>
<!-- anythingZoomer required -->
<link rel="stylesheet" href="css/anythingzoomer.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="js/jquery.anythingzoomer.js"></script>
<script>
$(function() {
// clone the text
$(".zoom:first").anythingZoomer({
clone: true
});
$(".zoom:last").anythingZoomer();
$("button").click(function() {
var state = $(this).text(); // enable or disable
$(".zoom:eq(" + $(this).attr('data-id') + ")").anythingZoomer(state);
$(this).text((state === "disable") ? "enable" : "disable");
return false;
});
});
</script>
</head>
<body id="double">
<div id="main-content">
<p>Double click within the section to toggle between the large and small versions.</p>
<p><strong>Text Demo <button data-id="0">disable</button></strong></p>
<div class="zoom">
<div class="small">
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae
est. Mauris placerat eleifend leo.</p>
</div>
<!-- the clone option will automatically make a div.large if it doesn't exist -->
</div>
<br>
<p><strong>Image Demo <button data-id="1">disable</button></strong></p>
<div class="zoom second">
<div class="small">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/Dean_Franklin_-_06.04.03_Mount_Rushmore_Monument_%28by-sa%29-3_new.jpg/1200px-Dean_Franklin_-_06.04.03_Mount_Rushmore_Monument_%28by-sa%29-3_new.jpg" alt="small rushmore">
</div>
<div class="large">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/Dean_Franklin_-_06.04.03_Mount_Rushmore_Monument_%28by-sa%29-3_new.jpg/1200px-Dean_Franklin_-_06.04.03_Mount_Rushmore_Monument_%28by-sa%29-3_new.jpg" alt="big rushmore">
</div>
</div>
</div>
</body>
</html>
This works! Just loop through each of the elements using .each and then add the scroll zoomer function to it.when the button is pressed, loop through the elements again and apply the toggle functionality.
;
(function(factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = factory(require('jquery'));
} else {
factory(jQuery);
}
}(function($) {
"use strict";
$.anythingZoomer = function(el, options) {
var n, o, t, base = this;
base.$wrap = $(el);
base.wrap = el;
// Add a reverse reference to the DOM object
base.$wrap.data('zoomer', base);
base.version = '2.2.6';
base.init = function() {
base.options = o = $.extend({}, $.anythingZoomer.defaultOptions, options);
// default class names
n = $.anythingZoomer.classNames;
// true when small element is showing, false when large is visible
base.state = true;
base.enabled = true;
base.hovered = false;
base.$wrap.addClass(n.wrap).wrapInner('<span class="' + n.wrapInner + '"/>');
base.$inner = base.$wrap.find('.' + n.wrapInner);
base.$small = base.$wrap.find('.' + o.smallArea);
base.$large = base.$wrap.find('.' + o.largeArea);
base.update();
// Add classes after getting size
base.$large.addClass(n.large);
base.$small.addClass(n.small);
base.$inner
.bind('mouseenter' + n.namespace, function() {
if (!base.enabled) {
return;
}
base.saved = base.enabled;
base.hovered = true;
if (o.delay) {
clearTimeout(base.delay);
base.enabled = false;
base.delay = setTimeout(function() {
base.enabled = base.saved;
base.position.type = 'mousemove';
base.$inner.trigger(base.position);
base.reveal();
}, o.delay);
} else {
base.reveal();
}
})
.bind('mouseleave' + n.namespace, function() {
base.hovered = false;
if (!base.enabled) {
return;
}
if (o.delay) {
clearTimeout(base.delay);
base.enabled = base.saved;
}
if (base.state && base.enabled) {
// delay hiding to prevent flash if user hovers over it again
// i.e. moving from a link to the image
base.timer = setTimeout(function() {
if (base.$zoom.hasClass(n.windowed)) {
base.hideZoom(true);
}
}, 200);
}
})
.bind('mousemove' + n.namespace, function(e) {
if (!base.enabled) {
return;
}
base.position = e;
if (!base.hovered) {
return;
}
if (base.state && base.enabled) {
clearTimeout(base.timer);
// get current offsets in case page positioning has changed
// Double demo: expanded text demo will offset image demo zoom window
var off = base.$small.offset();
base.zoomAt(e.pageX - off.left, e.pageY - off.top, null, true);
}
})
.bind(o.switchEvent + (o.switchEvent !== '' ? n.namespace : ''), function() {
if (!base.enabled) {
return;
}
// toggle visible image
if (base.state) {
base.showLarge();
} else {
base.showSmall();
}
});
base.showSmall();
// add events
$.each('initialized zoom unzoom'.split(' '), function(i, f) {
if ($.isFunction(o[f])) {
base.$wrap.bind(f, o[f]);
}
});
base.initialized = true;
base.$wrap.trigger('initialized', base);
};
base.reveal = function() {
base.enabled = base.saved;
if (base.state && base.enabled) {
base.$zoom.stop(true, true).fadeIn(o.speed);
if (o.overlay) {
base.$overlay.addClass(n.overlay);
}
base.$smInner.addClass(n.hovered);
base.$wrap.trigger('zoom', base);
}
};
base.update = function() {
// make sure the large image is hidden
if (base.initialized) {
base.showSmall();
}
base.$smInner = (base.$small.find('.' + n.smallInner).length) ?
base.$small.find('.' + n.smallInner) :
base.$small.wrapInner('<span class="' + n.smallInner + '"/>').find('.' + n.smallInner);
base.$small.find('.' + n.overly).remove();
if (o.clone) {
t = base.$smInner.clone()
.removeAttr('id')
.removeClass(n.smallInner)
.addClass(n.largeInner);
if (base.$large.length) {
// large area exists, just add content
base.$large.html(t.html());
} else {
// no large area, so add it
t.wrap('<div class="' + o.largeArea + '">');
base.$small.after(t.parent());
// set base.$large again in case small area was cloned
base.$large = base.$wrap.find('.' + o.largeArea);
}
}
base.$lgInner = (base.$large.find('.' + n.largeInner).length) ?
base.$large.find('.' + n.largeInner) :
base.$large.wrapInner('<span class="' + n.largeInner + '"/>').find('.' + n.largeInner);
if (!base.$wrap.find('.' + n.zoom).length) {
base.$large.wrap('<div class="' + n.zoom + '"/>');
base.$zoom = base.$wrap.find('.' + n.zoom);
}
if (o.edit && !base.edit) {
base.edit = $('<span class="' + n.edit + '"></span>').appendTo(base.$zoom);
}
// wrap inner content with a span to get a more accurate width
// get height from either the inner content itself or the children of the inner content since span will need
// a "display:block" to get an accurate height, but adding that messes up the width
base.$zoom.show();
base.largeDim = [base.$lgInner.children().width(), Math.max(base.$lgInner.height(), base.$lgInner.children().height())];
base.zoomDim = base.last = [base.$zoom.width(), base.$zoom.height()];
base.$zoom.hide();
base.smallDim = [base.$smInner.children().width(), base.$small.height()];
base.$overlay = $('<div class="' + n.overly + '" style="position:absolute;left:0;top:0;" />').prependTo(base.$small);
base.ratio = [
base.largeDim[0] / (base.smallDim[0] || 1),
base.largeDim[1] / (base.smallDim[1] || 1)
];
base.$inner.add(base.$overlay).css({
width: base.smallDim[0],
height: base.smallDim[1]
});
};
// Show small image - Setup
base.showSmall = function() {
base.state = true;
base.$small.show();
base.$zoom
.removeClass(n.expanded)
.addClass(n.windowed + ' ' + n.zoom)
.css({
width: base.zoomDim[0],
height: base.zoomDim[1]
});
base.$inner.css({
width: base.smallDim[0],
height: base.smallDim[1]
});
};
// Switch small and large on double click
base.showLarge = function() {
base.state = false;
base.$small.hide();
base.$zoom
.stop(true, true)
.fadeIn(o.speed)
.addClass(n.expanded)
.removeClass(n.windowed + ' ' + n.zoom)
.css({
height: 'auto',
width: 'auto'
});
base.$inner.css({
width: base.largeDim[0],
height: base.largeDim[1]
});
base.$large.css({
left: 0,
top: 0,
width: base.largeDim[0],
height: base.largeDim[1]
});
};
// x,y coords -> George Washington in image demo
// base.setTarget( 82, 50, [200,200] );
// 'selector', [xOffset, yOffset], [zoomW, zoomH] -> Aug 26 in calendar demo
// base.setTarget( '.day[rel=2009-08-26]', [0, 0], [200, 200] );
base.setTarget = function(tar, sec, sz) {
var t, x = 0,
y = 0;
clearTimeout(base.timer);
if (!base.$zoom.hasClass(n.windowed)) {
base.showSmall();
}
// x, y coords
if (!isNaN(tar) && !isNaN(sec)) {
x = parseInt(tar, 10);
y = parseInt(sec, 10);
} else if (typeof(tar) === 'string' && $(tar).length) {
// '.selector', [xOffSet, yOffSet]
t = $(tar);
x = t.position().left + t.width() / 2 + (sec ? sec[0] || 0 : 0);
y = t.position().top + t.height() / 2 + (sec ? sec[1] || 0 : 0);
}
base.zoomAt(x, y, sz);
// add overlay
if (o.overlay) {
base.$overlay.addClass(n.overlay);
}
// hovered, but not really
base.$smInner.addClass(n.hovered);
// zoom window triggered
base.$wrap.trigger('zoom', base);
};
// x, y, [zoomX, zoomY] - zoomX, zoomY are the dimensions of the zoom window
base.zoomAt = function(x, y, sz, internal) {
var sx = (sz ? sz[0] || 0 : 0) || base.last[0],
sy = (sz ? sz[1] || sz[0] || 0 : 0) || base.last[1],
sx2 = sx / 2,
sy2 = sy / 2,
ex = o.edge || (o.edge === 0 ? 0 : sx2 * 0.66), // 2/3 of zoom window
ey = o.edge || (o.edge === 0 ? 0 : sy2 * 0.66), // allows edge to be zero
m = parseInt(base.$inner.css('margin-left'), 10) || base.$inner.position().left || 0;
// save new zoom size
base.last = [sx, sy];
// save x, y for external access
base.current = [x, y];
// show coordinates
if (o.edit) {
base.edit.html(Math.round(x) + ', ' + Math.round(y));
}
if ((x < -ex) || (x > base.smallDim[0] + ex) || (y < -ey) || (y > base.smallDim[1] + ey)) {
base.hideZoom(internal);
return;
} else {
// Sometimes the mouseenter event is delayed
base.$zoom.stop(true, true).fadeIn(o.speed);
}
// center zoom under the cursor
base.$zoom.css({
left: x - sx2 + m,
top: y - sy2,
width: sx,
height: sy
});
// match locations of small element to the large
base.$large.css({
left: -(x - o.offsetX - sx2 / 2) * base.ratio[0],
top: -(y - o.offsetY - sy2 / 2) * base.ratio[1]
});
};
base.hideZoom = function(internal) {
if (internal && base.$smInner.hasClass(n.hovered)) {
base.$wrap.trigger('unzoom', base);
}
base.last = base.zoomDim;
base.$zoom.stop(true, true).fadeOut(o.speed);
base.$overlay.removeClass(n.overlay);
base.$smInner.removeClass(n.hovered);
base.lastKey = null;
};
base.setEnabled = function(enable) {
base.enabled = enable;
if (enable) {
var off = base.$small.offset();
base.zoomAt(base.position.pageX - off.left, base.position.pageY - off.top, null, true);
} else {
base.showSmall();
base.hideZoom();
base.hovered = false;
}
};
// Initialize zoomer
base.init();
};
// class names used by anythingZoomer
$.anythingZoomer.classNames = {
namespace: '.anythingZoomer', // event namespace
wrap: 'az-wrap',
wrapInner: 'az-wrap-inner',
large: 'az-large',
largeInner: 'az-large-inner',
small: 'az-small',
smallInner: 'az-small-inner',
overlay: 'az-overlay', // toggled class name
overly: 'az-overly', // overlay unstyled class
hovered: 'az-hovered',
zoom: 'az-zoom',
windowed: 'az-windowed', // zoom window active
expanded: 'az-expanded', // zoom window inactive (large is showing)
edit: 'az-coords', // coordinate window
scrollzoom: 'az-scrollzoom'
};
$.anythingZoomer.defaultOptions = {
// content areas
smallArea: 'small', // class of small content area; the element with this class name must be inside of the wrapper
largeArea: 'large', // class of large content area; this class must exist inside of the wrapper. When the clone option is true, it will add this automatically
clone: false, // Make a clone of the small content area, use css to modify the style
// appearance
overlay: false, // set to true to apply overlay class "az-overlay"; false to not apply it
speed: 100, // fade animation speed (in milliseconds)
edge: 30, // How far outside the wrapped edges the mouse can go; previously called "expansionSize"
offsetX: 0, // adjust the horizontal position of the large content inside the zoom window as desired
offsetY: 0, // adjust the vertical position of the large content inside the zoom window as desired
// functionality
switchEvent: 'dblclick', // event that allows toggling between small and large elements - default is double click
delay: 0, // time to delay before revealing the zoom window.
// edit mode
edit: false // add x,y coordinates into zoom window to make it easier to find coordinates
};
$.fn.anythingZoomer = function(options, second, sx, sy) {
return this.each(function() {
var anyZoom = $(this).data('zoomer');
// initialize the zoomer but prevent multiple initializations
if (/object|undefined/.test(typeof options)) {
if (anyZoom) {
anyZoom.update();
} else {
(new $.anythingZoomer(this, options));
}
} else if (anyZoom && (typeof options === 'string' || (!isNaN(options) && !isNaN(second)))) {
if (/(en|dis)able/.test(options)) {
anyZoom.setEnabled(options === 'enable');
} else {
anyZoom.setTarget(options, second, sx, sy);
}
}
});
};
$.fn.getAnythingZoomer = function() {
return this.data('zoomer');
};
return $.anythingzoomer;
}));
/* AnythingZoomer */
.az-wrap,
.az-small,
.az-large {
position: relative;
}
.az-wrap-inner {
display: block;
margin: 0 auto;
/* center small & large content */
}
/* This wraps the large image and hides it */
.az-zoom {
background: #fff;
border: #333 1px solid;
position: absolute;
top: 0;
left: 0;
width: 150px;
height: 150px;
overflow: hidden;
z-index: 100;
display: none;
-moz-box-shadow: inset 0px 0px 4px #000;
-webkit-box-shadow: inset 0px 0px 4px #000;
box-shadow: inset 0px 0px 4px #000;
}
/* Class applied to az-mover when large image is windowed */
.az-windowed {
overflow: hidden;
position: absolute;
}
/* Class applied to az-mover when large image is fully shown */
.az-expanded {
height: auto;
width: auto;
position: static;
overflow: visible;
}
/* overlay small area */
.az-overlay {
background-color: #000;
opacity: 0.3;
filter: alpha(opacity=30);
z-index: 10;
}
/* edit mode coordinate styling */
.az-coords {
display: none;
/* hidden when expanded */
}
.az-zoom .az-coords {
display: block;
position: absolute;
top: 0;
right: 0;
background: #000;
background: rgba(0, 0, 0, 0.5);
color: #fff;
}
/* ZOOM CONTAINER */
.zoom {
display: block;
margin: 0 auto;
}
.large {
background: white;
}
/* FOR TEXT DEMO */
.small p {
font-size: 16px;
width: 700px
}
.large p {
font-size: 32px;
width: 1400px;
}
/* FOR IMAGE DEMO */
.small img {
width: 250px;
}
.large img {
width: 500px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Image and Text Magnifier</title>
<!-- anythingZoomer required -->
<link rel="stylesheet" href="css/anythingzoomer.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="js/jquery.anythingzoomer.js"></script>
<script>
$(function() {
// clone the text
$(".zoom").each(function(){
$(this).anythingZoomer({clone: true});
});
$("button").click(function() {
var state = $(this).text(); // enable or disable
$(".zoom").each(function(){
$(this).anythingZoomer(state);
});
$(this).text((state === "disable") ? "enable" : "disable");
return false;
});
});
</script>
</head>
<body id="double">
<div id="main-content">
<p>Double click within the section to toggle between the large and small versions.</p>
<p><button>disable</button></p>
<p><strong>Text Demo </strong></p>
<div class="zoom">
<div class="small">
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae
est. Mauris placerat eleifend leo.</p>
</div>
<!-- the clone option will automatically make a div.large if it doesn't exist -->
</div>
<br>
<p><strong>Image Demo
<div class="zoom second">
<div class="small">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/Dean_Franklin_-_06.04.03_Mount_Rushmore_Monument_%28by-sa%29-3_new.jpg/1200px-Dean_Franklin_-_06.04.03_Mount_Rushmore_Monument_%28by-sa%29-3_new.jpg" alt="small rushmore">
</div>
<div class="large">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/Dean_Franklin_-_06.04.03_Mount_Rushmore_Monument_%28by-sa%29-3_new.jpg/1200px-Dean_Franklin_-_06.04.03_Mount_Rushmore_Monument_%28by-sa%29-3_new.jpg" alt="big rushmore">
</div>
</div>
</div>
</body>
</html>
Didn't read the code but you could create the zoom using CSS
btn:hover element{
font-size:larger;
}
I'm using http://www.gayadesign.com/scripts/queryLoader/to preload my pages. Now, it works fine with my home page, but when I put the code on any other page, the loader just stops at 90% and it won't load... I'm using the code provided in the zip file on the site. What's the problem? I added the script which initiates the plugin
QueryLoader.selectorPreload = "body";
QueryLoader.init();
In the php file and included it in my pages... Like I said, works good on my home page, but fails on any other. Why?
Code 1:
var QueryLoader = {
overlay: "",
loadBar: "",
preloader: "",
items: new Array(),
doneStatus: 0,
doneNow: 0,
selectorPreload: "body",
ieLoadFixTime: 2000,
ieTimeout: "",
init: function()
{
if (navigator.userAgent.match(/MSIE (\d+(?:\.\d+)+(?:b\d*)?)/) == "MSIE 6.0,6.0")
{
return false;
}
if (QueryLoader.selectorPreload == "body")
{
QueryLoader.spawnLoader();
QueryLoader.getImages(QueryLoader.selectorPreload);
QueryLoader.createPreloading();
}
else
{
$(document).ready(function()
{
QueryLoader.spawnLoader();
QueryLoader.getImages(QueryLoader.selectorPreload);
QueryLoader.createPreloading();
});
}
QueryLoader.ieTimeout = setTimeout("QueryLoader.ieLoadFix()", QueryLoader.ieLoadFixTime);
},
ieLoadFix: function()
{
var ie = navigator.userAgent.match(/MSIE (\d+(?:\.\d+)+(?:b\d*)?)/);
if (ie[0].match("MSIE"))
{
while ((100 / QueryLoader.doneStatus) * QueryLoader.doneNow < 100)
{
QueryLoader.imgCallback();
}
}
},
imgCallback: function()
{
QueryLoader.doneNow ++;
QueryLoader.animateLoader();
},
getImages: function(selector)
{
var everything = $(selector).find("*:not(script)").each(function()
{
var url = "";
if ($(this).css("background-image") != "none")
{
var url = $(this).css("background-image");
}
else if (typeof($(this).prop("src")) != "undefined" && $(this).prop("tagName").toLowerCase() == "img")
{
var url = $(this).prop("src");
}
url = url.replace("url(\"", "");
url = url.replace("url(", "");
url = url.replace("\")", "");
url = url.replace(")", "");
if (url.length > 0)
{
QueryLoader.items.push(url);
}
});
},
createPreloading: function()
{
QueryLoader.preloader = $("<DIV></DIV>").appendTo(QueryLoader.selectorPreload);
$(QueryLoader.preloader).css({
height: "0px",
width: "0px",
overflow:"hidden"
});
var length = QueryLoader.items.length;
QueryLoader.doneStatus = length;
for (var i = 0; i < length; i++)
{
var imgLoad = $("<IMG></IMG>");
$(imgLoad).prop("src", QueryLoader.items[i]);
$(imgLoad).unbind("load");
$(imgLoad).bind("load", function()
{
QueryLoader.imgCallback();
});
$(imgLoad).appendTo($(QueryLoader.preloader));
}
},
spawnLoader: function()
{
if (QueryLoader.selectorPreload == "body")
{
var height = $(window).height();
var width = $(window).width();
var position = "fixed";
}
else
{
var height = $(QueryLoader.selectorPreload).outerHeight();
var width = $(QueryLoader.selectorPreload).outerWidth();
var position = "absolute";
}
var left = $(QueryLoader.selectorPreload).offset()['left'];
var top = $(QueryLoader.selectorPreload).offset()['top'];
QueryLoader.overlay = $("<DIV></DIV>").appendTo($(QueryLoader.selectorPreload));
$(QueryLoader.overlay).addClass("LoadCont");
$(QueryLoader.overlay).css({
position: position,
top: top,
left: left,
width: width + "px",
height: height + "px"
});
QueryLoader.loadBar = $("<DIV></DIV>").appendTo($(QueryLoader.overlay));
$(QueryLoader.loadBar).addClass("Loading");
$(QueryLoader.loadBar).css({
position: "relative",
top: "90%",
width: "0%"
});
},
animateLoader: function()
{
var perc = (100 / QueryLoader.doneStatus) * QueryLoader.doneNow;
if (perc > 99)
{
$(QueryLoader.loadBar).stop().animate({
width: perc + "%"
}, 500, "linear", function()
{
QueryLoader.doneLoad();
});
}
else
{
$(QueryLoader.loadBar).stop().animate({
width: perc + "%"
}, 500, "linear", function() { });
}
},
doneLoad: function()
{
clearTimeout(QueryLoader.ieTimeout);
if (QueryLoader.selectorPreload == "body")
{
var height = $(window).height();
}
else
{
var height = $(QueryLoader.selectorPreload).outerHeight();
}
//The end animation, adjust to your likings
$(QueryLoader.loadBar).animate({
height: height + "px",
top: 0
}, 500, "linear", function()
{
$(QueryLoader.overlay).fadeOut(888);
$(QueryLoader.preloader).remove();
});
}
}
Code 2:
<SCRIPT>
QueryLoader.selectorPreload = "body";
QueryLoader.init();
</SCRIPT>
CSS:
.LoadCont
{
Z-INDEX: 9999 !important;
BACKGROUND: #000000;
}
.Loading
{
HEIGHT: 1px;
BACKGROUND-COLOR: #626262;
}
The page is: http://www.okultopedija.com/Ulaz?otvori=Razno
For page loader i have used the plugin. Following is js:
var QueryLoader = {
overlay: "",
loadBar: "",
preloader: "",
items: new Array(),
doneStatus: 0,
doneNow: 0,
selectorPreload: "body",
ieLoadFixTime: 2000,
ieTimeout: "",
init: function() {
if (navigator.userAgent.match(/MSIE (\d+(?:\.\d+)+(?:b\d*)?)/) == "MSIE 6.0,6.0") {
//break if IE6
return false;
}
if (QueryLoader.selectorPreload == "body") {
QueryLoader.spawnLoader();
QueryLoader.getImages(QueryLoader.selectorPreload);
QueryLoader.createPreloading();
} else {
$(document).ready(function() {
QueryLoader.spawnLoader();
QueryLoader.getImages(QueryLoader.selectorPreload);
QueryLoader.createPreloading();
});
}
//help IE drown if it is trying to die :)
QueryLoader.ieTimeout = setTimeout("QueryLoader.ieLoadFix()", QueryLoader.ieLoadFixTime);
},
ieLoadFix: function() {
var ie = navigator.userAgent.match(/MSIE (\d+(?:\.\d+)+(?:b\d*)?)/);
if (ie[0].match("MSIE")) {
while ((100 / QueryLoader.doneStatus) * QueryLoader.doneNow < 100) {
QueryLoader.imgCallback();
}
}
},
imgCallback: function() {
QueryLoader.doneNow ++;
QueryLoader.animateLoader();
},
getImages: function(selector) {
var everything = $(selector).find("*:not(script)").each(function() {
var url = "";
if ($(this).css("background-image") != "none") {
var url = $(this).css("background-image");
} else if (typeof($(this).attr("src")) != "undefined" && $(this).attr("tagName").toLowerCase() == "img") {
var url = $(this).attr("src");
}
url = url.replace("url(\"", "");
url = url.replace("url(", "");
url = url.replace("\")", "");
url = url.replace(")", "");
if (url.length > 0) {
QueryLoader.items.push(url);
}
});
},
createPreloading: function() {
QueryLoader.preloader = $("<div></div>").appendTo(QueryLoader.selectorPreload);
$(QueryLoader.preloader).css({
height: "0px",
width: "0px",
overflow: "hidden"
});
var length = QueryLoader.items.length;
QueryLoader.doneStatus = length;
for (var i = 0; i < length; i++) {
var imgLoad = $("<img></img>");
$(imgLoad).attr("src", QueryLoader.items[i]);
$(imgLoad).unbind("load");
$(imgLoad).bind("load", function() {
QueryLoader.imgCallback();
});
$(imgLoad).appendTo($(QueryLoader.preloader));
}
},
spawnLoader: function() {
if (QueryLoader.selectorPreload == "body") {
var height = $(window).height();
var width = $(window).width();
var position = "fixed";
} else {
var height = $(QueryLoader.selectorPreload).outerHeight();
var width = $(QueryLoader.selectorPreload).outerWidth();
var position = "absolute";
}
var left = $(QueryLoader.selectorPreload).offset()['left'];
var top = $(QueryLoader.selectorPreload).offset()['top'];
QueryLoader.overlay = $("<div></div>").appendTo($(QueryLoader.selectorPreload));
$(QueryLoader.overlay).addClass("QOverlay");
$(QueryLoader.overlay).css({
position: position,
top: top,
left: left,
width: width + "px",
height: height + "px"
});
QueryLoader.loadBar = $("<div></div>").appendTo($(QueryLoader.overlay));
$(QueryLoader.loadBar).addClass("QLoader");
$(QueryLoader.loadBar).css({
position: "relative",
top: "50%",
width: "0%"
});
},
animateLoader: function() {
var perc = (100 / QueryLoader.doneStatus) * QueryLoader.doneNow;
if (perc > 99) {
$(QueryLoader.loadBar).stop().animate({
width: perc + "%"
}, 500, "linear", function() {
QueryLoader.doneLoad();
});
} else {
$(QueryLoader.loadBar).stop().animate({
width: perc + "%"
}, 500, "linear", function() { });
}
},
doneLoad: function() {
//prevent IE from calling the fix
clearTimeout(QueryLoader.ieTimeout);
//determine the height of the preloader for the effect
if (QueryLoader.selectorPreload == "body") {
var height = $(window).height();
} else {
var height = $(QueryLoader.selectorPreload).outerHeight();
}
//The end animation, adjust to your likings
$(QueryLoader.loadBar).animate({
height: height + "px",
top: 0
}, 500, "linear", function() {
$(QueryLoader.overlay).fadeOut(800);
$(QueryLoader.preloader).remove();
});
}
}
In my html file, I used following Javascript:
<script type='text/javascript'>
QueryLoader.init();
</script>
And css is as following:
.QOverlay {
background-color: #000000;
z-index: 9999;
}
.QLoader {
background-color: #CCCCCC;
height: 1px;
}
I used this for simple example it works well.
But when I used this for my site it is giving error in js file as following:
TypeError: $(...).offset(...) is undefined
var left = $(QueryLoader.selectorPreload).offset()['left'];
So please can you help out from this issue:
Thanks in advance..
Your plugin is not really one. Go see the documentation to see more details.
Anyway, even if it's not a plugin, it could work as an object using some jQuery functions.
First, you shouldn't call the object inside the object function.
IE :
QueryLoader.ieTimeout = setTimeout("QueryLoader.ieLoadFix()", QueryLoader.ieLoadFixTime);
Here, you got your first error which you could have seen in the console. It should be :
this.ieTimeout = setTimeout(this.ieLoadFix, this.ieLoadFixTime);
You can start debugging like this, up to your initial error here.