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
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>
For a photographic website and want to display panoramic photos moving side to side within a viewport. At the moment it goes left to right when the page loads but stops when it runs out of image. Instead of stopping I want it to reverse direction and go right to left, and then left to right, right to left infintum.
It is probable something very simple but I'm a complete newbie to jquery (sorry).
This is the code which I've adapted from Arnault PACHOT:
Any help would be greatly appreciated. Thanks in advance.
/* =========================================================
// jquery.panorama.js
// Author: OpenStudio (Arnault PACHOT)
// Mail: apachot#openstudio.fr
// Web: http://www.openstudio.fr
// Copyright (c) 2008 Arnault Pachot
// licence : GPL
========================================================= */
(function($) {
$.fn.panorama = function(options) {
this.each(function(){
var settings = {
viewport_width: 669,
speed: 20000,
direction: 'left',
control_display: 'auto',
start_position: 0,
auto_start: true,
mode_360: false
};
if(options) $.extend(settings, options);
var elemWidth = parseInt($(this).attr('width'));
var elemHeight = parseInt($(this).attr('height'));
var currentElement = this;
var panoramaViewport, panoramaContainer;
var bMouseMove = false;
var mouseMoveStart = 0;
var mouseMoveMarginStart = 0;
$(this).attr('unselectable','on')
.css('position', 'relative')
.css('-moz-user-select','none')
.css('-webkit-user-select','none')
.css('margin', '0')
.css('padding', '0')
.css('border', 'none')
.wrap("<div class='panorama-container'></div>");
if (settings.mode_360)
$(this).clone().insertAfter(this);
panoramaContainer = $(this).parent();
panoramaContainer.css('height', elemHeight+'px').css('overflow', 'hidden').wrap("<div class='panorama-viewport'></div>").parent().css('width',settings.viewport_width+'px')
.append("<div class='panorama-control'><a href='#' class='panorama-control-left'><<</a> <a href='#' class='panorama-control-pause'>x</a> <a href='#' class='panorama-control-right'>>></a> </div>");
panoramaViewport = panoramaContainer.parent();
panoramaViewport.mousedown(function(e){
if (!bMouseMove) {
bMouseMove = true;
mouseMoveStart = e.clientX;
}
return false;
}).mouseup(function(){
bMouseMove = false;
mouseMoveStart = 0;
return false;
}).mousemove(function(e){
if (bMouseMove){
var delta = parseInt((mouseMoveStart - e.clientX)/30);
if ((delta>10) || (delta<10)) {
var newMarginLeft = parseInt(panoramaContainer.css('marginLeft')) + (delta);
if (settings.mode_360) {
if (newMarginLeft > 0) {newMarginLeft = -elemWidth;}
if (newMarginLeft < -elemWidth) {newMarginLeft = 0;}
} else {
if (newMarginLeft > 0) {newMarginLeft = 0;}
if (newMarginLeft < -elemWidth) {newMarginLeft = -elemWidth;}
}
panoramaContainer.css('marginLeft', newMarginLeft+'px');
}
}
}).bind('contextmenu',function(){return false;});
panoramaViewport.css('height', elemHeight+'px').css('overflow', 'hidden').find('a.panorama-control-left').bind('click', function() {
$(panoramaContainer).stop();
settings.direction = 'right';
panorama_animate(panoramaContainer, elemWidth, settings);
return false;
});
panoramaViewport.bind('click', function() {
$(panoramaContainer).stop();
});
panoramaViewport.find('a.panorama-control-right').bind('click', function() {
$(panoramaContainer).stop();
settings.direction = 'left';
panorama_animate(panoramaContainer, elemWidth, settings);
return false;
});
panoramaViewport.find('a.panorama-control-pause').bind('click', function() {
$(panoramaContainer).stop();
return false;
});
if (settings.control_display == 'yes') {
panoramaViewport.find('.panorama-control').show();
} else if (settings.control_display == 'auto') {
panoramaViewport.bind('mouseover', function(){
$(this).find('.panorama-control').show();
return false;
}).bind('mouseout', function(){
$(this).find('.panorama-control').hide();
return false;
});
}
$(this).parent().css('margin-left', '-'+settings.start_position+'px');
if (settings.auto_start)
panorama_animate(panoramaContainer, elemWidth, settings);
});
function panorama_animate(element, elemWidth, settings) {
currentPosition = 0-parseInt($(element).css('margin-left'));
if (settings.direction == 'right') {
$(element).animate({marginLeft: 0}, ((settings.speed / elemWidth) * (currentPosition)) , 'linear', function (){
if (settings.mode_360) {
$(element).css('marginLeft', '-'+(parseInt(parseInt(elemWidth))+'px'));
panorama_animate(element, elemWidth, settings);
}
});
} else {
var rightlimit;
if (settings.mode_360)
rightlimit = elemWidth;
else
rightlimit = elemWidth-settings.viewport_width;
$(element).animate({marginLeft: -rightlimit}, ((settings.speed / rightlimit) * (rightlimit - currentPosition)), 'linear', function (){
if (settings.mode_360) {
$(element).css('margin-left', 0);
panorama_animate(element, elemWidth, settings);
}
});
}
}
};
$(document).ready(function(){
$("img.panorama").panorama();
});
in})(jQuery);
https://jsfiddle.net/pm6swLxa/
You code use css animations
HTML
<div id="img_container" class="pano slide"></div>
CSS
#img_container {
width:400px;
height: 200px;
overflow: hidden;
background: url('http://www.the-farm.net/piccies/pano2.jpg');
background-size: auto 100%;
background-position: right;
animation: back-and-forth 5s infinite;
}
#keyframes back-and-forth {
0% {
background-position: right;
}
50% {
background-position: left;
}
100% {
background-position: right;
}
}
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>")
});
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.
I'm trying to find a very simple and smooth, lightweight javascript or jquery marquee. I already tried silk marquee or something, but it wouldn't work with the application I was using. So the simpler and shorter, the better - and easier to debug. Does anybody know of a easy to implement javascript replacement for the marquee?
Pastebin
Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type="text/javascript">
var tWidth='300px'; // width (in pixels)
var tHeight='25px'; // height (in pixels)
var tcolour='#ffffcc'; // background colour:
var moStop=true; // pause on mouseover (true or false)
var fontfamily = 'arial,sans-serif'; // font for content
var tSpeed=3; // scroll speed (1 = slow, 5 = fast)
// enter your ticker content here (use \/ and \' in place of / and ' respectively)
var content='Are you looking for loads of useful information <a href="http:\/\/javascript.about.com\/">About Javascript<\/a>? Well now you\'ve found it.';
var cps=-tSpeed; var aw, mq; var fsz = parseInt(tHeight) - 4; function startticker(){if (document.getElementById) {var tick = '<div style="position:relative;width:'+tWidth+';height:'+tHeight+';overflow:hidden;background-color:'+tcolour+'"'; if (moStop) tick += ' onmouseover="cps=0" onmouseout="cps=-tSpeed"'; tick +='><div id="mq" style="position:absolute;right:0px;top:0px;font-family:'+fontfamily+';font-size:'+fsz+'px;white-space:nowrap;"><\/div><\/div>'; document.getElementById('ticker').innerHTML = tick; mq = document.getElementById("mq"); mq.style.right=(10+parseInt(tWidth))+"px"; mq.innerHTML='<span id="tx">'+content+'<\/span>'; aw = document.getElementById("tx").offsetWidth; lefttime=setInterval("scrollticker()",50);}} function scrollticker(){mq.style.right = (parseInt(mq.style.right)>(-10 - aw)) ?
mq.style.right = parseInt(mq.style.right)+cps+"px": parseInt(tWidth)+10+"px";} window.onload=startticker;
</script>
</head>
<body>
<div id="ticker">
this is a simple scrolling text!
</div>
</body>
</html>
hiya simple demo from recommendations in above comments: http://jsfiddle.net/FWWEn/
with pause functionality on mouseover: http://jsfiddle.net/zrW5q/
hope this helps, have a nice one, cheers!
html
<h1>Hello World!</h1>
<h2>I'll marquee twice</h2>
<h3>I go fast!</h3>
<h4>Left to right</h4>
<h5>I'll defer that question</h5>
Jquery code
(function($) {
$.fn.textWidth = function(){
var calc = '<span style="display:none">' + $(this).text() + '</span>';
$('body').append(calc);
var width = $('body').find('span:last').width();
$('body').find('span:last').remove();
return width;
};
$.fn.marquee = function(args) {
var that = $(this);
var textWidth = that.textWidth(),
offset = that.width(),
width = offset,
css = {
'text-indent' : that.css('text-indent'),
'overflow' : that.css('overflow'),
'white-space' : that.css('white-space')
},
marqueeCss = {
'text-indent' : width,
'overflow' : 'hidden',
'white-space' : 'nowrap'
},
args = $.extend(true, { count: -1, speed: 1e1, leftToRight: false }, args),
i = 0,
stop = textWidth*-1,
dfd = $.Deferred();
function go() {
if(!that.length) return dfd.reject();
if(width == stop) {
i++;
if(i == args.count) {
that.css(css);
return dfd.resolve();
}
if(args.leftToRight) {
width = textWidth*-1;
} else {
width = offset;
}
}
that.css('text-indent', width + 'px');
if(args.leftToRight) {
width++;
} else {
width--;
}
setTimeout(go, args.speed);
};
if(args.leftToRight) {
width = textWidth*-1;
width++;
stop = offset;
} else {
width--;
}
that.css(marqueeCss);
go();
return dfd.promise();
};
})(jQuery);
$('h1').marquee();
$('h2').marquee({ count: 2 });
$('h3').marquee({ speed: 5 });
$('h4').marquee({ leftToRight: true });
$('h5').marquee({ count: 1, speed: 2 }).done(function() { $('h5').css('color', '#f00'); })
I've made very simple function for marquee. See: http://jsfiddle.net/vivekw/pHNpk/2/
It pauses on mouseover & resumes on mouseleave. Speed can be varied. Easy to understand.
function marquee(a, b) {
var width = b.width();
var start_pos = a.width();
var end_pos = -width;
function scroll() {
if (b.position().left <= -width) {
b.css('left', start_pos);
scroll();
}
else {
time = (parseInt(b.position().left, 10) - end_pos) *
(10000 / (start_pos - end_pos)); // Increase or decrease speed by changing value 10000
b.animate({
'left': -width
}, time, 'linear', function() {
scroll();
});
}
}
b.css({
'width': width,
'left': start_pos
});
scroll(a, b);
b.mouseenter(function() { // Remove these lines
b.stop(); //
b.clearQueue(); // if you don't want
}); //
b.mouseleave(function() { // marquee to pause
scroll(a, b); //
}); // on mouse over
}
$(document).ready(function() {
marquee($('#display'), $('#text')); //Enter name of container element & marquee element
});
I just created a simple jQuery plugin for that. Try it ;)
https://github.com/aamirafridi/jQuery.Marquee
The following works:
http://jsfiddle.net/xAGRJ/4/
The problem with your original code was you are calling scrollticker() by passing a string to setInterval, where you should just pass the function name and treat it as a variable:
lefttime = setInterval(scrollticker, 50);
instead of
lefttime = setInterval("scrollticker()", 50);
Why write custom jQuery code for Marquee... just use a plugin for jQuery - marquee() and use it like in the example below:
First include :
<script type='text/javascript' src='//cdn.jsdelivr.net/jquery.marquee/1.3.1/jquery.marquee.min.js'></script>
and then:
//proporcional speed counter (for responsive/fluid use)
var widths = $('.marquee').width()
var duration = widths * 7;
$('.marquee').marquee({
//speed in milliseconds of the marquee
duration: duration, // for responsive/fluid use
//duration: 8000, // for fixed container
//gap in pixels between the tickers
gap: $('.marquee').width(),
//time in milliseconds before the marquee will start animating
delayBeforeStart: 0,
//'left' or 'right'
direction: 'left',
//true or false - should the marquee be duplicated to show an effect of continues flow
duplicated: true
});
If you can make it simpler and better I dare you all people :). Don't make your life more difficult than it should be. More about this plugin and its functionalities at: http://aamirafridi.com/jquery/jquery-marquee-plugin
I made my own version, based in the code presented above by #Tats_innit .
The difference is the pause function. Works a little better in that aspect.
(function ($) {
var timeVar, width=0;
$.fn.textWidth = function () {
var calc = '<span style="display:none">' + $(this).text() + '</span>';
$('body').append(calc);
var width = $('body').find('span:last').width();
$('body').find('span:last').remove();
return width;
};
$.fn.marquee = function (args) {
var that = $(this);
if (width == 0) { width = that.width(); };
var textWidth = that.textWidth(), offset = that.width(), i = 0, stop = textWidth * -1, dfd = $.Deferred(),
css = {
'text-indent': that.css('text-indent'),
'overflow': that.css('overflow'),
'white-space': that.css('white-space')
},
marqueeCss = {
'text-indent': width,
'overflow': 'hidden',
'white-space': 'nowrap'
},
args = $.extend(true, { count: -1, speed: 1e1, leftToRight: false, pause: false }, args);
function go() {
if (!that.length) return dfd.reject();
if (width <= stop) {
i++;
if (i <= args.count) {
that.css(css);
return dfd.resolve();
}
if (args.leftToRight) {
width = textWidth * -1;
} else {
width = offset;
}
}
that.css('text-indent', width + 'px');
if (args.leftToRight) {
width++;
} else {
width=width-2;
}
if (args.pause == false) { timeVar = setTimeout(function () { go() }, args.speed); };
if (args.pause == true) { clearTimeout(timeVar); };
};
if (args.leftToRight) {
width = textWidth * -1;
width++;
stop = offset;
} else {
width--;
}
that.css(marqueeCss);
timeVar = setTimeout(function () { go() }, 100);
return dfd.promise();
};
})(jQuery);
usage:
for start: $('#Text1').marquee()
pause: $('#Text1').marquee({ pause: true })
resume: $('#Text1').marquee({ pause: false })
My text marquee for more text,
and position absolute enabled
http://jsfiddle.net/zrW5q/2075/
(function($) {
$.fn.textWidth = function() {
var calc = document.createElement('span');
$(calc).text($(this).text());
$(calc).css({
position: 'absolute',
visibility: 'hidden',
height: 'auto',
width: 'auto',
'white-space': 'nowrap'
});
$('body').append(calc);
var width = $(calc).width();
$(calc).remove();
return width;
};
$.fn.marquee = function(args) {
var that = $(this);
var textWidth = that.textWidth(),
offset = that.width(),
width = offset,
css = {
'text-indent': that.css('text-indent'),
'overflow': that.css('overflow'),
'white-space': that.css('white-space')
},
marqueeCss = {
'text-indent': width,
'overflow': 'hidden',
'white-space': 'nowrap'
},
args = $.extend(true, {
count: -1,
speed: 1e1,
leftToRight: false
}, args),
i = 0,
stop = textWidth * -1,
dfd = $.Deferred();
function go() {
if (that.css('overflow') != "hidden") {
that.css('text-indent', width + 'px');
return false;
}
if (!that.length) return dfd.reject();
if (width <= stop) {
i++;
if (i == args.count) {
that.css(css);
return dfd.resolve();
}
if (args.leftToRight) {
width = textWidth * -1;
} else {
width = offset;
}
}
that.css('text-indent', width + 'px');
if (args.leftToRight) {
width++;
} else {
width--;
}
setTimeout(go, args.speed);
};
if (args.leftToRight) {
width = textWidth * -1;
width++;
stop = offset;
} else {
width--;
}
that.css(marqueeCss);
go();
return dfd.promise();
};
// $('h1').marquee();
$("h1").marquee();
$("h1").mouseover(function () {
$(this).removeAttr("style");
}).mouseout(function () {
$(this).marquee();
});
})(jQuery);
Responsive resist jQuery marquee simple plugin. Tutorial:
// start plugin
(function($){
$.fn.marque = function(options, callback){
// check callback
if(typeof callback == 'function'){
callback.call(this);
} else{
console.log("second argument (callback) is not a function");
// throw "callback must be a function"; //only if callback for some reason is required
// return this; //only if callback for some reason is required
}
//set and overwrite default functions
var defOptions = $.extend({
speedPixelsInOneSecound: 150, //speed will behave same for different screen where duration will be different for each size of the screen
select: $('.message div'),
clickSelect: '', // selector that on click will redirect user ... (optional)
clickUrl: '' //... to this url. (optional)
}, options);
//Run marque plugin
var windowWidth = $(window).width();
var textWidth = defOptions.select.outerWidth();
var duration = (windowWidth + textWidth) * 1000 / defOptions.speedPixelsInOneSecound;
var startingPosition = (windowWidth + textWidth);
var curentPosition = (windowWidth + textWidth);
var speedProportionToLocation = curentPosition / startingPosition;
defOptions.select.css({'right': -(textWidth)});
defOptions.select.show();
var animation;
function marquee(animation){
curentPosition = (windowWidth + defOptions.select.outerWidth());
speedProportionToLocation = curentPosition / startingPosition;
animation = defOptions.select.animate({'right': windowWidth+'px'}, duration * speedProportionToLocation, "linear", function(){
defOptions.select.css({'right': -(textWidth)});
});
}
var play = setInterval(marquee, 200);
//add onclick behaviour
if(defOptions.clickSelect != '' && defOptions.clickUrl != ''){
defOptions.clickSelect.click(function(){
window.location.href = defOptions.clickUrl;
});
}
return this;
};
}(jQuery));
// end plugin
Use this custom jQuery plugin as bellow:
//use example
$(window).marque({
speedPixelsInOneSecound: 150, // spped pixels/secound
select: $('.message div'), // select an object on which you want to apply marquee effects.
clickSelect: $('.message'), // select clicable object (optional)
clickUrl: 'services.php' // define redirection url (optional)
});
Marquee using CSS animations.
`<style>
.items-holder {
animation: moveSlideshow 5s linear infinite;
}
.items-holder:hover {
animation-play-state: paused;
}
#keyframes moveSlideshow {
100% {
transform: translateX(100%);
}
}
</style>`
I try use only css for it this link.
<style>
.header {
background: #212121;
overflow: hidden;
height: 65px;
position: relative;
}
.header div {
display: flex;
flex-direction: row;
align-items: center;
overflow: hidden;
height: 65px;
transform: translate(100%, 0);
}
.header div * {
font-family: "Roboto", sans-serif;
color: #fff339;
text-transform: uppercase;
text-decoration: none;
}
.header div img {
height: 60px;
margin-right: 20px;
}
.header .ticker-wrapper__container{
display: flex;
flex-direction: row;
align-items: center;
position: absolute;
top: 0;
right: 0;
animation: ticker 30s infinite linear forwards;
}
.header:hover .ticker-wrapper__container{
animation-play-state: paused;
}
.ticker-wrapper__container a{
display: flex;
margin-right: 60px;
align-items: center;
}
#keyframes ticker {
0% {
transform: translate(100%, 0);
}
50% {
transform: translate(0, 0);
}
100% {
transform: translate(-100%, 0);
}
}
</style>