Animation flickers with Firefox 18.0.1 (due to RequestAnimationFrame?) - javascript

i used this http://www.netmagazine.com/tutorials/create-interactive-street-view-jquery tutorial to create an intro for one of our customers:
http://f-bilandia.de/kunstmann/bronski/
It used to work really good on all browsers. When I updated to the newest stable version of Firefox (FF 18.0.1) however, there is heavy flickering while changing the images.
When reading the release notes of the newest version, i saw that ff has a new Javascript engine and has improved image quality with a new HTML scaling algorithm. Maybe it's because of that? Other possible solutions?
Below you can see the code i've used:
$(document).ready(function(){
var $doc = $(document);
var $win = $(window);
// dimensions - we want to cache them on window resize
var windowHeight, windowWidth;
var fullHeight, scrollHeight;
var streetImgWidth = 1024, streetImgHeight = 640;
calculateDimensions();
var currentPosition = -1, targetPosition = 0;
var $videoContainer = $('.street-view');
var video = $('.street-view > img')[0];
var $hotspotElements = $('[data-position]');
// handling resize and scroll events
function calculateDimensions() {
windowWidth = $win.width();
windowHeight = $win.height();
fullHeight = $('#main').height();
scrollHeight = fullHeight - windowHeight;
}
function handleResize() {
calculateDimensions();
resizeBackgroundImage();
handleScroll();
}
function handleScroll() {
targetPosition = $win.scrollTop() / scrollHeight;
}
// main render loop
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(/* function */ callback, /* DOMElement */ element){
window.setTimeout(callback, 1000 / 60);
};
})();
function animloop(){
if ( Math.floor(currentPosition*5000) != Math.floor(targetPosition*5000) ) {
currentPosition += (targetPosition - currentPosition) / 5;
render(currentPosition);
}
requestAnimFrame(animloop);
}
// rendering
function render( position ) {
// position the elements
var minY = -windowHeight, maxY = windowHeight;
$.each($hotspotElements,function(index,element){
var $hotspot = $(element);
var elemPosition = Number( $hotspot.attr('data-position') );
var elemSpeed = Number( $hotspot.attr('data-speed') );
var elemY = windowHeight/2 + elemSpeed * (elemPosition-position) * scrollHeight;
if ( elemY < minY || elemY > maxY ) {
$hotspot.css({'visiblity':'none', top: '-1000px','webkitTransform':'none'});
} else {
$hotspot.css({'visiblity':'visible', top: elemY, position: 'fixed'});
}
});
renderVideo( position );
}
function resizeBackgroundImage(){
// get image container size
var scale = Math.max( windowHeight/streetImgHeight , windowWidth/streetImgWidth );
var width = scale * streetImgWidth , height = scale * streetImgHeight;
var left = (windowWidth-width)/2, top = (windowHeight-height)/2;
$videoContainer
.width(width).height(height)
.css('position','fixed')
.css('left',left+'px')
.css('top',top+'px');
}
// video handling
var imageSeqLoader = new ProgressiveImageSequence( "street/vid-{index}.jpg" , 387 , {
indexSize: 4,
initialStep: 16,
onProgress: handleLoadProgress,
onComplete: handleLoadComplete,
stopAt: 1
} );
// there seems to be a problem with ie
// calling the callback several times
var loadCounterForIE = 0;
imageSeqLoader.loadPosition(currentPosition,function(){
loadCounterForIE++;
if ( loadCounterForIE == 1 ) {
renderVideo(currentPosition);
imageSeqLoader.load();
imageSeqLoader.load();
imageSeqLoader.load();
imageSeqLoader.load();
}
});
var currentSrc, currentIndex;
function renderVideo(position) {
var index = Math.round( currentPosition * (imageSeqLoader.length-1) );
var img = imageSeqLoader.getNearest( index );
var nearestIndex = imageSeqLoader.nearestIndex;
if ( nearestIndex < 0 ) nearestIndex = 0;
var $img = $(img);
var src;
if ( !!img ) {
src = img.src;
if ( src != currentSrc ) {
video.src = src;
currentSrc = src;
}
}
}
$('body').append('<div id="loading-bar" style="">Loading...</div>');
function handleLoadProgress() {
var progress = imageSeqLoader.getLoadProgress() * 100;
$('#loading-bar').css({width:progress+'%',opacity:1});
}
function handleLoadComplete() {
$('#loading-bar').css({width:'100%',opacity:0,display: "none"});
$("html, body").css("overflow", "auto");
$("html, body").css("overflow-x", "hidden");
$("nav").css("display", "block");
$("#preloader").fadeOut("slow");
$("#scroll-hint").css("display", "block");
}
$win.resize( handleResize );
$win.scroll( handleScroll );
handleResize();
animloop();
});

Inside your "render( position )" function the following lines seem like they should be refactored.
if ( elemY < minY || elemY > maxY ) {
$hotspot.css({'visiblity':'none', top: '-1000px','webkitTransform':'none'});
} else {
$hotspot.css({'visiblity':'visible', top: elemY, position: 'fixed'});
}
For one visibility is spelled wrong and there is no "none" value for it (it would be "hidden"). Just use "display" with "none" and "" values.
The "top", "webkitTransform", and "position" keys seem unnecessary. If the element is not visible there's no need to set the top, and why wouldn't the element always be fixed position?

Related

Using jQuery Pan and Zoomooz together to pan and zoom DOM element

Seen a few similar questions on here but most seem to refer to zooming and panning images, I can't find anything that answers my problem.
I'm looking to create something like https://timmywil.com/panzoom/demo/, but I want to have a DOM element zoom on click, then pan around on mouse move.
I've been able to come up with something that's very nearly there, example here. https://jsfiddle.net/kevngibsn/5okxr8n3/29/
For this I'm using Zoomooz to handle the zoom, and jQuery Pan to take care of the panning. The issue with this example is that jQuery Pan works out the size of the DOM element on page load and doesn't take into account the increased size after zoom, so mouse move doesn't pan to the edges.
Here's the code from jQuery Pan:
(function( $ ){
var getSize = function($element) {
return {
'width': $element.width(),
'height': $element.height()
};
};
var toCoords = function(x, y) {
return {'x': x, 'y': y};
};
var vectorsEqual = function(v1, v2) {
return v1.x == v2.x && v1.y == v2.y;
}
$.fn.pan = function(options) {
//Container is element this plugin is applied to;
//we're pan it's child element, content
var container = this;
var content = this.children(':first');
//Precalculate the limits of panning - offset stores
//the current amount of pan throughout
var offset = toCoords(
Number(content.css('left').replace('px', '')) | 0,
Number(content.css('top').replace('px', '')) | 0
);
var containerSize = getSize(container);
var contentSize = getSize(content);
var minOffset = toCoords(
-contentSize.width + containerSize.width,
-contentSize.height + containerSize.height
);
var maxOffset = toCoords(0, 0);
//By default, assume mouse sensitivity border
//is 25% of the smallest dimension
var defaultMouseEdge = 0.25 * Math.min(
containerSize.width,
containerSize.height
);
var settings = $.extend( {
'autoSpeedX' : 0,
'autoSpeedY' : 0,
'mouseControl' : 'kinetic',
'kineticDamping' : 0.8,
'mouseEdgeSpeed' : 5,
'mouseEdgeWidth' : defaultMouseEdge,
'proportionalSmoothing' : 0.5,
'updateInterval' : 50,
'mousePan' : null
}, options);
//Mouse state variables, set by bound mouse events below
var mouseOver = false;
var mousePanningDirection = toCoords(0, 0);
var mousePosition = toCoords(0, 0);
var dragging = false;
var lastMousePosition = null;
var kineticVelocity = toCoords(0, 0);
//Delay in ms between updating position of content
var updateInterval = settings.updateInterval;
var onInterval = function() {
if (container.hasClass('pan-off')) return false; //Temporarily disabling pan add/remove class pan-off
var mouseControlHandlers = {
'edge' : updateEdge,
'proportional' : updateProportional,
'kinetic' : updateKinetic
};
var currentHandler = settings.mouseControl;
if(!mouseControlHandlers[currentHandler]()) {
//The handler isn't active - just pan normally
offset.x += settings.autoSpeedX;
offset.y += settings.autoSpeedY;
}
//If the previous updates have take the content
//outside the allowed min/max, bring it back in
constrainToBounds();
//If we're panning automatically, make sure we're
//panning in the right direction if the content has
//moved as far as it can go
if(offset.x == minOffset.x) settings.autoSpeedX = Math.abs(settings.autoSpeedX);
if(offset.x == maxOffset.x) settings.autoSpeedX = -Math.abs(settings.autoSpeedX);
if(offset.y == minOffset.y) settings.autoSpeedY = Math.abs(settings.autoSpeedY);
if(offset.y == maxOffset.y) settings.autoSpeedY = -Math.abs(settings.autoSpeedY);
//Finally, update the position of the content
//with our carefully calculated value
content.css('left', offset.x + "px");
content.css('top', offset.y + "px");
}
var updateEdge = function() {
if(!mouseOver) return false;
//The user's possibly maybe mouse-navigating,
//so we'll find out what direction in case we need
//to handle any callbacks
var newDirection = toCoords(0, 0);
//If we're in the interaction zones to either
//end of the element, pan in response to the
//mouse position.
if(mousePosition.x < settings.mouseEdgeWidth) {
offset.x += settings.mouseEdgeSpeed;
newDirection.x = -1;
}
if (mousePosition.x > containerSize.width - settings.mouseEdgeWidth) {
offset.x -= settings.mouseEdgeSpeed;
newDirection.x = 1;
}
if(mousePosition.y < settings.mouseEdgeWidth) {
offset.y += settings.mouseEdgeSpeed;
newDirection.y = -1;
}
if (mousePosition.y > containerSize.height - settings.mouseEdgeWidth) {
offset.y -= settings.mouseEdgeSpeed;
newDirection.y = 1;
}
updateMouseDirection(newDirection);
return true;
}
var updateProportional = function() {
if(!mouseOver) return false;
var rx = mousePosition.x / containerSize.width;
var ry = mousePosition.y / containerSize.height;
targetOffset = toCoords(
(minOffset.x - maxOffset.x) * rx + maxOffset.x,
(minOffset.y - maxOffset.y) * ry + maxOffset.y
);
var damping = 1 - settings.proportionalSmoothing;
offset = toCoords(
(targetOffset.x - offset.x) * damping + offset.x,
(targetOffset.y - offset.y) * damping + offset.y
)
return true;
}
var updateKinetic = function() {
if(dragging) {
if(lastMousePosition == null) {
lastMousePosition = toCoords(mousePosition.x, mousePosition.y);
}
kineticVelocity = toCoords(
mousePosition.x - lastMousePosition.x,
mousePosition.y - lastMousePosition.y
);
lastMousePosition = toCoords(mousePosition.x, mousePosition.y);
}
offset.x += kineticVelocity.x;
offset.y += kineticVelocity.y;
kineticVelocity = toCoords(
kineticVelocity.x * settings.kineticDamping,
kineticVelocity.y * settings.kineticDamping
);
//If the kinetic velocity is still greater than a small threshold, this
//function is still controlling movement so we return true so autopanning
//doesn't interfere.
var speedSquared = Math.pow(kineticVelocity.x, 2) + Math.pow(kineticVelocity.y, 2);
return speedSquared > 0.01
}
var constrainToBounds = function() {
if(offset.x < minOffset.x) offset.x = minOffset.x;
if(offset.x > maxOffset.x) offset.x = maxOffset.x;
if(offset.y < minOffset.y) offset.y = minOffset.y;
if(offset.y > maxOffset.y) offset.y = maxOffset.y;
}
var updateMouseDirection = function(newDirection) {
if(!vectorsEqual(newDirection, mousePanningDirection)) {
mousePanningDirection = newDirection;
if(settings.mousePan) {
settings.mousePan(mousePanningDirection);
}
}
}
this.bind('mousemove', function(evt) {
mousePosition.x = evt.pageX - container.offset().left;
mousePosition.y = evt.pageY - container.offset().top;
mouseOver = true;
});
this.bind('mouseleave', function(evt) {
mouseOver = false;
dragging = false;
lastMousePosition = null;
updateMouseDirection(toCoords(0, 0));
});
this.bind('mousedown', function(evt) {
dragging = true;
return false; //Prevents FF from thumbnailing & dragging
});
this.bind('mouseup', function(evt) {
dragging = false;
lastMousePosition = null;
});
//Kick off the main panning loop and return
//this to maintain jquery chainability
setInterval(onInterval, updateInterval);
return this;
};
})( jQuery );
I'd at about my limit on this one, any advice on how to get that panning the whole element?

Run function for every repeated class on the same page

I've created the following functionality where an image is fixed on the left while scrolling the content and the quote appears for a few pixels.
It's working all right, the only problem is that I'd like to add this many times on the same page and, as it is, it just works with the first image.
The second one is not fixed while scrolling and the quote maintains hidden...
How can I make run this function for every image?
This is a working example
HTML:
<section id="cont_quote" class="maxwidth">
<article class="cont_q hasImage">
<p>Content</p>
<img class="alignleft img_quote" src="/large.jpg" alt="" width="433" height="553" />
<blockquote>
<h3>Why this training plan works</h3>
</blockquote>
<p>Content</p>
</article>
</section>
JS:
// Stick image on scroll
$(window).on('load resize', function () {
if ($(window).width() >= 769) {
var $element = $('#cont_quote');
var $follow = $element.find('.img_quote');
var followHeight = $element.find('.img_quote').outerHeight();
var height = $element.outerHeight() - 300;
var window_height = $(window).height();
$(window).scroll(function () {
var pos = $(window).scrollTop();
var top = $element.offset().top;
// Check if element is above or totally below viewport
if (top + height - followHeight < pos || top > pos + window_height) {
return;
}
var offset = parseInt($(window).scrollTop() - top);
if (offset > 0) {
$follow.css('transform', 'translateY('+ offset +'px)');
}
})
}
});
// Quote show on viewport
function inViewport( element, viewport = { top: 0, bottom: innerHeight } ){
// Get the elements position relative to the viewport
var bb = element.getBoundingClientRect();
// Check if the element is outside the viewport
// Then invert the returned value because you want to know the opposite
return !(bb.top > viewport.bottom || bb.bottom < viewport.top);
}
var myViewport = { top: innerHeight * .5, bottom: innerHeight * .6 };
var myElement = document.querySelector( '#cont_quote blockquote' );
// Listen for the scroll event
document.addEventListener( 'scroll', event => {
// Check the viewport status
if( $(window).width() >= 600 ){
if( inViewport( myElement, myViewport ) && $('.cont_q').hasClass('hasImage') ) {
if( $(window).width() >= 769 ){
myElement.style.opacity = 1;
myElement.style.left = '-25%';
} else {
myElement.style.opacity = 1;
myElement.style.left = '-5%';
}
} else if( inViewport( myElement, myViewport )) {
if( $(window).width() >= 769 ){
myElement.style.opacity = 1;
myElement.style.left = '-15%';
} else {
myElement.style.opacity = 1;
myElement.style.left = '13%';
}
} else {
myElement.style.opacity = 0;
myElement.style.left = '-40%';
}
} else {
myElement.style.opacity = 1;
myElement.style.left = '5%';
}
});

Set top of page to 340px from top with jQuery

Currently I have a script which starts a progress bar the moment a user starts scrolling.
Is it possible to change this to when the user gets to 340px from the top of the page?
Here is a demo of my site: http://pixsols.com/test/wordpress/reading-progress/
Here is my current code:
(function ( $ ) {
$.fn.progressScroll = function(options) {
var settings = $.extend({
fontSize : 20,
color : '#009ACF',
height : '5px',
textArea : 'dark',
}, options);
// element state info
var docOffset = $(this).offset().top,
elmHeight = $(this).height(),
winHeight = $(window).height();
// listen for scroll changes
$(window).on('scroll', function() {
var docScroll = $(window).scrollTop(),
windowOffset = docOffset - docScroll,
viewedPortion = winHeight + docScroll - docOffset;
if($(window).scrollTop() > 0) {
if($('.scrollWrapper').hasClass('hidden')) {
$('.scrollWrapper').removeClass('hidden').hide();
$('.scrollWrapper').slideDown('slow');
}
} else {
$('.scrollWrapper').slideUp('slow');
$('.scrollWrapper').addClass('hidden');
}
if(viewedPortion < 0) { viewedPortion = 0; }
if(viewedPortion > elmHeight) { viewedPortion = elmHeight; }
// calculate viewed percentage
var viewedPercentage = viewedPortion / elmHeight;
// set percent in progress element
$('.scroll-bar').css('width', (viewedPercentage*100)+'%' );
});
var self = this;
$(window).on('resize', function() {
docOffset = $(self).offset().top;
elmHeight = $(self).height();
winHeight = $(window).height();
$(window).trigger('scroll');
});
$(window).trigger('scroll');
var $el = $('.scroll-bar').css(settings);
return $el;
};
}( jQuery ));
My guess would be to manipulate this:
windowOffset = docOffset - docScroll,
Probably you should add or subtract 320px from windowOffset. So for example"
windowOffset = docOffset - docScroll + 320,

HTML Element Height Keeps Incrementing by the Second

Purchased an off the shelf theme for my portfolio site (yes, yes...I'm too busy to design my own right now lol). Anyway I seem to be having an issue, and I have no idea when it started, where my html height keeps growing by 30-60px every 1-2sec.
I've tried viewing the console, however I can't find anything that's triggering this. I'm assuming that some funking Javascript is at play, and need help possibly tracking it down.
Anyone wanna lend a hand here...?
My Site
UPDATE: It seems to be caused by the smoothscroll.js file. Can any JS pro help me find the offending line of code?
// SmoothScroll v1.2.1
// Licensed under the terms of the MIT license.
// People involved
// - Balazs Galambosi (maintainer)
// - Patrick Brunner (original idea)
// - Michael Herf (Pulse Algorithm)
// - Justin Force (Resurect)
// Scroll Variables (tweakable)
var framerate = 150; // [Hz]
var animtime = 800; // [px]
var stepsize = 80; // [px]
// Pulse (less tweakable)
// ratio of "tail" to "acceleration"
var pulseAlgorithm = true;
var pulseScale = 8;
var pulseNormalize = 1;
// Acceleration
var acceleration = true;
var accelDelta = 10; // 20
var accelMax = 1; // 1
// Keyboard Settings
var keyboardsupport = true; // option
var disableKeyboard = false; // other reasons
var arrowscroll = 50; // [px]
// Excluded pages
var exclude = "";
var disabled = false;
// Other Variables
var frame = false;
var direction = { x: 0, y: 0 };
var initdone = false;
var fixedback = true;
var root = document.documentElement;
var activeElement;
var key = { left: 37, up: 38, right: 39, down: 40, spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36 };
/**
* Sets up scrolls array, determines if frames are involved.
*/
function init() {
if (!document.body) return;
var body = document.body;
var html = document.documentElement;
var windowHeight = window.innerHeight;
var scrollHeight = body.scrollHeight;
// check compat mode for root element
root = (document.compatMode.indexOf('CSS') >= 0) ? html : body;
activeElement = body;
initdone = true;
// Checks if this script is running in a frame
if (top != self) {
frame = true;
}
/**
* This fixes a bug where the areas left and right to
* the content does not trigger the onmousewheel event
* on some pages. e.g.: html, body { height: 100% }
*/
else if (scrollHeight > windowHeight &&
(body.offsetHeight <= windowHeight ||
html.offsetHeight <= windowHeight)) {
// DOMChange (throttle): fix height
var pending = false;
var refresh = function() {
if (!pending && html.scrollHeight != document.height) {
pending = true; // add a new pending action
setTimeout(function(){
html.style.height = document.height + 'px';
pending = false;
}, 500); // act rarely to stay fast
}
};
html.style.height = '';
setTimeout(refresh, 10);
addEvent("DOMNodeInserted", refresh);
addEvent("DOMNodeRemoved", refresh);
// clearfix
if (root.offsetHeight <= windowHeight) {
var underlay = document.createElement("div");
underlay.style.clear = "both";
body.appendChild(underlay);
}
}
// gmail performance fix
if (document.URL.indexOf("mail.google.com") > -1) {
var s = document.createElement("style");
s.innerHTML = ".iu { visibility: hidden }";
(document.getElementsByTagName("head")[0] || html).appendChild(s);
}
// disable fixed background
if (!fixedback && !disabled) {
body.style.backgroundAttachment = "scroll";
html.style.backgroundAttachment = "scroll";
}
}
/************************************************
* SCROLLING
************************************************/
var que = [];
var pending = false;
var lastScroll = +new Date;
/**
* Pushes scroll actions to the scrolling queue.
*/
function scrollArray(elem, left, top, delay) {
delay || (delay = 1000);
directionCheck(left, top);
if (acceleration) {
var now = +new Date;
var elapsed = now - lastScroll;
if (elapsed < accelDelta) {
var factor = (1 + (30 / elapsed)) / 2;
if (factor > 1) {
factor = Math.min(factor, accelMax);
left *= factor;
top *= factor;
}
}
lastScroll = +new Date;
}
// push a scroll command
que.push({
x: left,
y: top,
lastX: (left < 0) ? 0.99 : -0.99,
lastY: (top < 0) ? 0.99 : -0.99,
start: +new Date
});
// don't act if there's a pending queue
if (pending) {
return;
}
var scrollWindow = (elem === document.body);
var step = function() {
var now = +new Date;
var scrollX = 0;
var scrollY = 0;
for (var i = 0; i < que.length; i++) {
var item = que[i];
var elapsed = now - item.start;
var finished = (elapsed >= animtime);
// scroll position: [0, 1]
var position = (finished) ? 1 : elapsed / animtime;
// easing [optional]
if (pulseAlgorithm) {
position = pulse(position);
}
// only need the difference
var x = (item.x * position - item.lastX) >> 0;
var y = (item.y * position - item.lastY) >> 0;
// add this to the total scrolling
scrollX += x;
scrollY += y;
// update last values
item.lastX += x;
item.lastY += y;
// delete and step back if it's over
if (finished) {
que.splice(i, 1); i--;
}
}
// scroll left and top
if (scrollWindow) {
window.scrollBy(scrollX, scrollY)
}
else {
if (scrollX) elem.scrollLeft += scrollX;
if (scrollY) elem.scrollTop += scrollY;
}
// clean up if there's nothing left to do
if (!left && !top) {
que = [];
}
if (que.length) {
requestFrame(step, elem, (delay / framerate + 1));
} else {
pending = false;
}
}
// start a new queue of actions
requestFrame(step, elem, 0);
pending = true;
}
/***********************************************
* EVENTS
***********************************************/
/**
* Mouse wheel handler.
* #param {Object} event
*/
function wheel(event) {
if (!initdone) {
init();
}
var target = event.target;
var overflowing = overflowingAncestor(target);
// use default if there's no overflowing
// element or default action is prevented
if (!overflowing || event.defaultPrevented ||
isNodeName(activeElement, "embed") ||
(isNodeName(target, "embed") && /\.pdf/i.test(target.src))) {
return true;
}
var deltaX = event.wheelDeltaX || 0;
var deltaY = event.wheelDeltaY || 0;
// use wheelDelta if deltaX/Y is not available
if (!deltaX && !deltaY) {
deltaY = event.wheelDelta || 0;
}
// scale by step size
// delta is 120 most of the time
// synaptics seems to send 1 sometimes
if (Math.abs(deltaX) > 1.2) {
deltaX *= stepsize / 120;
}
if (Math.abs(deltaY) > 1.2) {
deltaY *= stepsize / 120;
}
scrollArray(overflowing, -deltaX, -deltaY);
event.preventDefault();
}
/**
* Keydown event handler.
* #param {Object} event
*/
function keydown(event) {
var target = event.target;
var modifier = event.ctrlKey || event.altKey || event.metaKey ||
(event.shiftKey && event.keyCode !== key.spacebar);
// do nothing if user is editing text
// or using a modifier key (except shift)
// or in a dropdown
if ( /input|textarea|select|embed/i.test(target.nodeName) ||
target.isContentEditable ||
event.defaultPrevented ||
modifier ) {
return true;
}
// spacebar should trigger button press
if (isNodeName(target, "button") &&
event.keyCode === key.spacebar) {
return true;
}
var shift, x = 0, y = 0;
var elem = overflowingAncestor(activeElement);
var clientHeight = elem.clientHeight;
if (elem == document.body) {
clientHeight = window.innerHeight;
}
switch (event.keyCode) {
case key.up:
y = -arrowscroll;
break;
case key.down:
y = arrowscroll;
break;
case key.spacebar: // (+ shift)
shift = event.shiftKey ? 1 : -1;
y = -shift * clientHeight * 0.9;
break;
case key.pageup:
y = -clientHeight * 0.9;
break;
case key.pagedown:
y = clientHeight * 0.9;
break;
case key.home:
y = -elem.scrollTop;
break;
case key.end:
var damt = elem.scrollHeight - elem.scrollTop - clientHeight;
y = (damt > 0) ? damt+10 : 0;
break;
case key.left:
x = -arrowscroll;
break;
case key.right:
x = arrowscroll;
break;
default:
return true; // a key we don't care about
}
scrollArray(elem, x, y);
event.preventDefault();
}
/**
* Mousedown event only for updating activeElement
*/
function mousedown(event) {
activeElement = event.target;
}
/***********************************************
* OVERFLOW
***********************************************/
var cache = {}; // cleared out every once in while
setInterval(function(){ cache = {}; }, 10 * 1000);
var uniqueID = (function() {
var i = 0;
return function (el) {
return el.uniqueID || (el.uniqueID = i++);
};
})();
function setCache(elems, overflowing) {
for (var i = elems.length; i--;)
cache[uniqueID(elems[i])] = overflowing;
return overflowing;
}
function overflowingAncestor(el) {
var elems = [];
var rootScrollHeight = root.scrollHeight;
do {
var cached = cache[uniqueID(el)];
if (cached) {
return setCache(elems, cached);
}
elems.push(el);
if (rootScrollHeight === el.scrollHeight) {
if (!frame || root.clientHeight + 10 < rootScrollHeight) {
return setCache(elems, document.body); // scrolling root in WebKit
}
} else if (el.clientHeight + 10 < el.scrollHeight) {
overflow = getComputedStyle(el, "").getPropertyValue("overflow-y");
if (overflow === "scroll" || overflow === "auto") {
return setCache(elems, el);
}
}
} while (el = el.parentNode);
}
/***********************************************
* HELPERS
***********************************************/
function addEvent(type, fn, bubble) {
window.addEventListener(type, fn, (bubble||false));
}
function removeEvent(type, fn, bubble) {
window.removeEventListener(type, fn, (bubble||false));
}
function isNodeName(el, tag) {
return (el.nodeName||"").toLowerCase() === tag.toLowerCase();
}
function directionCheck(x, y) {
x = (x > 0) ? 1 : -1;
y = (y > 0) ? 1 : -1;
if (direction.x !== x || direction.y !== y) {
direction.x = x;
direction.y = y;
que = [];
lastScroll = 0;
}
}
var requestFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
function(callback, element, delay){
window.setTimeout(callback, delay || (1000/60));
};
})();
/***********************************************
* PULSE
***********************************************/
/**
* Viscous fluid with a pulse for part and decay for the rest.
* - Applies a fixed force over an interval (a damped acceleration), and
* - Lets the exponential bleed away the velocity over a longer interval
* - Michael Herf, http://stereopsis.com/stopping/
*/
function pulse_(x) {
var val, start, expx;
// test
x = x * pulseScale;
if (x < 1) { // acceleartion
val = x - (1 - Math.exp(-x));
} else { // tail
// the previous animation ended here:
start = Math.exp(-1);
// simple viscous drag
x -= 1;
expx = 1 - Math.exp(-x);
val = start + (expx * (1 - start));
}
return val * pulseNormalize;
}
function pulse(x) {
if (x >= 1) return 1;
if (x <= 0) return 0;
if (pulseNormalize == 1) {
pulseNormalize /= pulse_(1);
}
return pulse_(x);
}
addEvent("mousedown", mousedown);
addEvent("mousewheel", wheel);
addEvent("load", init);
Not sure what's going on here, but the issue with smoothscroll.js still stands. Disabling it seems to have no effect on the rest of my site though so I'm moving forward.

Rerun javascript function when screen orientation changes

I'm using a code that scale images to fit the parent div, it's called "aspectcorrect".
The problem happens on the mobile version: my parent div has 100% width, and when the user changes the orientation of the screen to landscape, the image doesn't resize to fit the new div's width.
There is a way to rerun the onload event (which scales the image), when the user changes the orientation of the screen?
Here is my website: www.mcsoftware.com.br/sitemc
I'm still working on it.
(To understand what I'm saying, open it on your cellphone, and when you change the screen orientation just click on "Continuar mesmo assim" to navigate)
Thanks!
aspectcorrect.js
function ScaleImage(srcwidth, srcheight, targetwidth, targetheight, fLetterBox) {
var result = { width: 0, height: 0, fScaleToTargetWidth: true };
if ((srcwidth <= 0) || (srcheight <= 0) || (targetwidth <= 0) || (targetheight <= 0)) {
return result;
}
// scale to the target width
var scaleX1 = targetwidth;
var scaleY1 = (srcheight * targetwidth) / srcwidth;
// scale to the target height
var scaleX2 = (srcwidth * targetheight) / srcheight;
var scaleY2 = targetheight;
// now figure out which one we should use
var fScaleOnWidth = (scaleX2 > targetwidth);
if (fScaleOnWidth) {
fScaleOnWidth = fLetterBox;
}
else {
fScaleOnWidth = !fLetterBox;
}
if (fScaleOnWidth) {
result.width = Math.floor(scaleX1);
result.height = Math.floor(scaleY1);
result.fScaleToTargetWidth = true;
}
else {
result.width = Math.floor(scaleX2);
result.height = Math.floor(scaleY2);
result.fScaleToTargetWidth = false;
}
result.targetleft = Math.floor((targetwidth - result.width) / 2);
result.targettop = Math.floor((targetheight - result.height) / 2);
return result;
}
onimageload.js
function OnImageLoad(evt) {
var img = evt.currentTarget;
// what's the size of this image and it's parent
var w = $(img).width();
var h = $(img).height();
var tw = $(img).parent().width();
var th = $(img).parent().height();
// compute the new size and offsets
var result = ScaleImage(w, h, tw, th, false);
// adjust the image coordinates and size
img.width = result.width;
img.height = result.height;
$(img).css("left", result.targetleft);
$(img).css("top", result.targettop);
}
Where onload function goes
<img onload="OnImageLoad(event);" />
https://jsfiddle.net/ffxeqq21/
You can try some javascript library like jQuery mobile and use the orientationchange event This way you could just do
$( window ).on( "orientationchange", function( event ) {
//Some code
});

Categories