Find place for callback function - javascript

I can't find where i can put my own code on resize and reposition. I need to find where to insert the callback, this is the only bit i should be looking at and i just can't find where to insert the callback function on resize
$.Isotope.prototype._getCenteredMasonryColumns = function() {
this.width = this.element.width();
var parentWidth = this.element.parent().width();
// i.e. options.masonry && options.masonry.columnWidth
var colW = this.options.masonry && this.options.masonry.columnWidth ||
// or use the size of the first item
this.$filteredAtoms.outerWidth(true) ||
// if there's no items, use size of container
parentWidth;
var cols = Math.floor( parentWidth / colW );
cols = Math.max( cols, 1 );
// i.e. this.masonry.cols = ....
this.masonry.cols = cols;
// i.e. this.masonry.columnWidth = ...
this.masonry.columnWidth = colW;
};
$.Isotope.prototype._masonryReset = function() {
// layout-specific props
this.masonry = {};
// FIXME shouldn't have to call this again
this._getCenteredMasonryColumns();
var i = this.masonry.cols;
this.masonry.colYs = [];
while (i--) {
this.masonry.colYs.push( 0 );
}
};
$.Isotope.prototype._masonryResizeChanged = function() {
var prevColCount = this.masonry.cols;
// get updated colCount
this._getCenteredMasonryColumns();
return ( this.masonry.cols !== prevColCount );
};
$.Isotope.prototype._masonryGetContainerSize = function() {
var unusedCols = 0,
i = this.masonry.cols;
// count unused columns
while ( --i ) {
if ( this.masonry.colYs[i] !== 0 ) {
break;
}
unusedCols++;
}
return {
height : Math.max.apply( Math, this.masonry.colYs ),
// fit container to columns that have been used;
width : (this.masonry.cols - unusedCols) * this.masonry.columnWidth
}
};
Any idea?

Solution was to simply do a window.resize an apply a timer in it:
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
$(window).resize(function() {
delay(function(){
if ($("#head").width() != $("#container").width()){
var myLeft = $("#container").offset().left;
var newWidth = $("#container").innerWidth();
var myRight = $("#container").offset().left + $("#container").outerWidth();
$("#head").animate({ width: newWidth, marginLeft: myLeft, marginRight: myRight }, "fast");
}
}, 800);
});

Related

Block a JavaScript function in a page

I have a javascript function for a slider in the JS file of my site. When we are in a page where the slider is not called or there is no trigger element, it displays an error in the console "Uncaught TypeError: Cannot read properties of null (reading 'querySelector') ", This error is not displayed when the slider is in the page.
I would like to know how to avoid this error, and how to prevent this function from loading in pages where this slider is not present?
function slider(set) {
const sliderContainer = document.querySelector(set.name),
slider = sliderContainer.querySelector('.slider'),
sliderItem = slider.querySelectorAll('.slider__item'),
sliderArrows = sliderContainer.querySelectorAll('.arrows__item');
let dotsCreate,
dotsClass,
dotsFunk,
numberSlider,
numberSliderWork,
sliderExecutionLine,
sliderExecutionLineWork;
// calculate the maximum width of all slides
function forSliderItem(t) {
t = 0;
for(let i = 0; i < sliderItem.length - 1; i++) {
t += sliderItem[i].clientWidth;
}
return t;
}
let maxWidth = forSliderItem(sliderItem), // maximum width of all slides
slidWidth = 0, // main variable for calculating the movement of the slider
count = 0; // counter
//===== flip left
sliderArrows[0].addEventListener('click', function() {
if(count !== 0) {
count--;
slidWidth -= sliderItem[count].clientWidth;
slider.style.transform = `translateX(-${slidWidth}px)`;
} else {
count = sliderItem.length - 1;
slidWidth = maxWidth;
slider.style.transform = `translateX(-${slidWidth}px)`;
}
if(set.dots) {
dotsFunk();
}
if(set.numberSlid) {
numberSliderWork(count);
}
if(set.line) {
sliderExecutionLineWork(count);
}
});
//===== flip right
sliderArrows[1].addEventListener('click', function() {
if(count < sliderItem.length - 1) {
count++;
slidWidth += sliderItem[count].clientWidth;
slider.style.transform = `translateX(-${slidWidth}px)`;
} else {
count = 0;
slidWidth = 0;
slider.style.transform = `translateX(-${slidWidth}px)`;
}
if(set.dots) {
dotsFunk();
}
if(set.numberSlid) {
numberSliderWork(count);
}
if(set.line) {
sliderExecutionLineWork(count);
}
});
//===== dots
if(set.dots) {
dotsCreate = function() {
const dotContainer = document.createElement('div'); // create dots container
dotContainer.classList.add('dots');
// create the required number of dots and insert a container into the dots
sliderItem.forEach(() => {
let dotsItem = document.createElement('span');
dotContainer.append(dotsItem);
});
sliderContainer.append(dotContainer);
};
dotsCreate();
// add the class to the desired dots, and remove from the rest
dotsClass = function(remove, add) {
remove.classList.remove('dots_active');
add.classList.add('dots_active');
};
// move slides by clicking on the dot
dotsFunk = function() {
const dotsWork = sliderContainer.querySelectorAll('.dots span'); // we get dots
dotsWork.forEach((item, i) => {
dotsClass(dotsWork[i], dotsWork[count]);
item.addEventListener('click', function() {
count = i;
// multiply the slide size by the number of the dots, and get the number by which you need to move the slider
slidWidth = sliderItem[0].clientWidth * i;
slider.style.transform = `translateX(-${slidWidth}px)`;
for(let j = 0; j < dotsWork.length; j++) {
dotsClass(dotsWork[j], dotsWork[count]);
}
if(set.dots && set.numberSlid) {
numberSliderWork(count);
}
if(set.line) {
sliderExecutionLineWork(count);
}
});
});
};
dotsFunk();
}
//===== count slider
if(set.numberSlid) {
numberSlider = function(item) {
const countContainer = document.createElement('div'),
sliderNumber = document.createElement('span'),
slash = document.createElement('span'),
allSliderNumber = document.createElement('span');
casClient = document.createElement('p');
sliderNumber.innerHTML = item + 1;
casClient.innerHTML = 'Cas client N°';
slash.innerHTML = '/';
allSliderNumber.innerHTML = sliderItem.length;
countContainer.classList.add('count-slides');
countContainer.append(casClient, sliderNumber, slash, allSliderNumber);
sliderContainer.append(countContainer);
};
numberSlider(0);
numberSliderWork = function(item) {
const sliderNumberNow = sliderContainer.querySelector('.count-slides span');
sliderNumberNow.innerHTML = item + 1;
if(set.line) {
sliderExecutionLineWork(item);
}
};
}
}
slider({
name: ".video_users",
numberSlid: true
});
<!DOCTYPE html>
<html lang="fr">
<head>
<title>Example of a page without the slider</title>
</head>
<body class="error_404">
<h1>Example of a page without the slider</h1>
<script src="media/js/faveod.js" async></script>
</body>
</html>
Just return if the element isn't present if you don't want it to show an error.
const sliderContainer = document.querySelector(set.name);
if (!sliderContainer) return;
const slider = sliderContainer.querySelector('.slider'),
sliderItem = slider.querySelectorAll('.slider__item'),
sliderArrows = sliderContainer.querySelectorAll('.arrows__item');
If you want it to only execute on certain pages, then just add:
if (location.pathname !== '/the/page/with/slider') return;
to the beginning of the function
/*
* SCROLLBAR 2 COLUMN / SOLUTIONS
*/
var ssb = {
aConts : [],
mouseY : 0,
N : 0,
asd : 0, /*active scrollbar element*/
sc : 0,
sp : 0,
to : 0,
// constructor
scrollbar : function (cont_id) {
var cont = document.getElementById(cont_id);
// perform initialization
if (! ssb.init()) return false;
var cont_clone = cont.cloneNode(false);
cont_clone.style.overflow = "hidden";
cont.parentNode.appendChild(cont_clone);
cont_clone.appendChild(cont);
cont.style.position = 'absolute';
cont.style.left = cont.style.top = '0px';
cont.style.width = cont.style.height = '100%';
// adding new container into array
ssb.aConts[ssb.N++] = cont;
cont.sg = false;
//creating scrollbar child elements
cont.st = this.create_div('ssb_st', cont, cont_clone);
cont.sb = this.create_div('ssb_sb', cont, cont_clone);
cont.su = this.create_div('ssb_up', cont, cont_clone);
cont.sd = this.create_div('ssb_down', cont, cont_clone);
// on mouse down processing
cont.sb.onmousedown = function (e) {
if (! this.cont.sg) {
if (! e) e = window.event;
ssb.asd = this.cont;
this.cont.yZ = e.screenY;
this.cont.sZ = cont.scrollTop;
this.cont.sg = true;
// new class name
this.className = 'ssb_sb ssb_sb_down';
}
return false;
}
// on mouse down on free track area - move our scroll element too
cont.st.onmousedown = function (e) {
if (! e) e = window.event;
ssb.asd = this.cont;
ssb.mouseY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
for (var o = this.cont, y = 0; o != null; o = o.offsetParent) y += o.offsetTop;
this.cont.scrollTop = (ssb.mouseY - y - (this.cont.ratio * this.cont.offsetHeight / 2) - this.cont.sw) / this.cont.ratio;
this.cont.sb.onmousedown(e);
}
// onmousedown events
cont.su.onmousedown = cont.su.ondblclick = function (e) { ssb.mousedown(this, -1); return false; }
cont.sd.onmousedown = cont.sd.ondblclick = function (e) { ssb.mousedown(this, 1); return false; }
//onmouseout events
cont.su.onmouseout = cont.su.onmouseup = ssb.clear;
cont.sd.onmouseout = cont.sd.onmouseup = ssb.clear;
// on mouse over - apply custom class name: ssb_sb_over
cont.sb.onmouseover = function (e) {
if (! this.cont.sg) this.className = 'ssb_sb ssb_sb_over';
return false;
}
// on mouse out - revert back our usual class name 'ssb_sb'
cont.sb.onmouseout = function (e) {
if (! this.cont.sg) this.className = 'ssb_sb';
return false;
}
// onscroll - change positions of scroll element
cont.ssb_onscroll = function () {
this.ratio = (this.offsetHeight - 2 * this.sw) / this.scrollHeight;
this.sb.style.top = Math.floor(this.sw + this.scrollTop * this.ratio) + 'px';
}
// scrollbar width
cont.sw = 16;
// start scrolling
cont.ssb_onscroll();
ssb.refresh();
// binding own onscroll event
cont.onscroll = cont.ssb_onscroll;
return cont;
},
// initialization
init : function () {
if (window.oper || (! window.addEventListener && ! window.attachEvent)) { return false; }
// temp inner function for event registration
function addEvent (o, e, f) {
if (window.addEventListener) { o.addEventListener(e, f, false); ssb.w3c = true; return true; }
if (window.attachEvent) return o.attachEvent('on' + e, f);
return false;
}
// binding events
addEvent(window.document, 'mousemove', ssb.onmousemove);
addEvent(window.document, 'mouseup', ssb.onmouseup);
addEvent(window, 'resize', ssb.refresh);
return true;
},
// create and append div finc
create_div : function(c, cont, cont_clone) {
var o = document.createElement('div');
o.cont = cont;
o.className = c;
cont_clone.appendChild(o);
return o;
},
// do clear of controls
clear : function () {
clearTimeout(ssb.to);
ssb.sc = 0;
return false;
},
// refresh scrollbar
refresh : function () {
for (var i = 0, N = ssb.N; i < N; i++) {
var o = ssb.aConts[i];
o.ssb_onscroll();
o.sb.style.width = o.st.style.width = o.su.style.width = o.su.style.height = o.sd.style.width = o.sd.style.height = o.sw + 'px';
o.sb.style.height = Math.ceil(Math.max(o.sw * .5, o.ratio * o.offsetHeight) + 1) + 'px';
}
},
// arrow scrolling
arrow_scroll : function () {
if (ssb.sc != 0) {
ssb.asd.scrollTop += 6 * ssb.sc / ssb.asd.ratio;
ssb.to = setTimeout(ssb.arrow_scroll, ssb.sp);
ssb.sp = 32;
}
},
/* event binded functions : */
// scroll on mouse down
mousedown : function (o, s) {
if (ssb.sc == 0) {
// new class name
o.cont.sb.className = 'ssb_sb ssb_sb_down';
ssb.asd = o.cont;
ssb.sc = s;
ssb.sp = 100;
ssb.arrow_scroll();
}
},
// on mouseMove binded event
onmousemove : function(e) {
if (! e) e = window.event;
// get vertical mouse position
ssb.mouseY = e.screenY;
if (ssb.asd.sg) ssb.asd.scrollTop = ssb.asd.sZ + (ssb.mouseY - ssb.asd.yZ) / ssb.asd.ratio;
},
// on mouseUp binded event
onmouseup : function (e) {
if (! e) e = window.event;
var tg = (e.target) ? e.target : e.srcElement;
if (ssb.asd && document.releaseCapture) ssb.asd.releaseCapture();
// new class name
if (ssb.asd) ssb.asd.sb.className = (tg.className.indexOf('scrollbar') > 0) ? 'ssb_sb ssb_sb_over' : 'ssb_sb';
document.onselectstart = '';
ssb.clear();
ssb.asd.sg = false;
}
}
window.onload = function() {
ssb.scrollbar('container'); // scrollbar initialization
}

Solution of my Mozilla browser?

It works in chrome.But when i use with Mozilla Firefox then it shows this
" A script on this page may be busy, or it may have stopped responding. You can stop the script now, open the script in the debugger, or let the script continue.
Script: http://localhost/tsdev_v2/resources/js/libs/jquery-1.8.3.js:6841"
My code is...
<script>
/*$("table").stickyTableHeaders();*/
/* $(function(){
$("table").stickyTableHeaders();
});*/
$(document).ready(function() {
$("table").stickyTableHeaders({fixedOffset:40});
});
</script>
<script>
;(function ($, window, undefined) {
'use strict';
var name = 'stickyTableHeaders',
id = 0,
defaults = {
fixedOffset: 0,
leftOffset: 0,
marginTop: 0,
objDocument: document,
objHead: 'head',
objWindow: window,
scrollableArea: window
};
function Plugin (el, options) {
// To avoid scope issues, use 'base' instead of 'this'
// to reference this class from internal events and functions.
var base = this;
// Access to jQuery and DOM versions of element
base.$el = $(el);
base.el = el;
base.id = id++;
// Listen for destroyed, call teardown
base.$el.bind('destroyed',
$.proxy(base.teardown, base));
// Cache DOM refs for performance reasons
base.$clonedHeader = null;
base.$originalHeader = null;
// Keep track of state
base.isSticky = false;
base.hasBeenSticky = false;
base.leftOffset = null;
base.topOffset = null;
base.init = function () {
base.setOptions(options);
base.$el.each(function () {
var $this = $(this);
// remove padding on <table> to fix issue #7
$this.css('padding', 0);
base.$originalHeader = $('thead:first', this);
base.$clonedHeader = base.$originalHeader.clone();
$this.trigger('clonedHeader.' + name, [base.$clonedHeader]);
base.$clonedHeader.addClass('tableFloatingHeader');
base.$clonedHeader.css('display', 'none');
base.$originalHeader.addClass('tableFloatingHeaderOriginal');
base.$originalHeader.after(base.$clonedHeader);
base.$printStyle = $('<style type="text/css" media="print">' +
'.tableFloatingHeader{display:none !important;}' +
'.tableFloatingHeaderOriginal{position:static !important;}' +
'</style>');
base.$head.append(base.$printStyle);
});
base.updateWidth();
base.toggleHeaders();
base.bind();
};
base.destroy = function (){
base.$el.unbind('destroyed', base.teardown);
base.teardown();
};
base.teardown = function(){
if (base.isSticky) {
base.$originalHeader.css('position', 'static');
}
$.removeData(base.el, 'plugin_' + name);
base.unbind();
base.$clonedHeader.remove();
base.$originalHeader.removeClass('tableFloatingHeaderOriginal');
base.$originalHeader.css('visibility', 'visible');
base.$printStyle.remove();
base.el = null;
base.$el = null;
};
base.bind = function(){
base.$scrollableArea.on('scroll.' + name, base.toggleHeaders);
if (!base.isWindowScrolling) {
base.$window.on('scroll.' + name + base.id, base.setPositionValues);
base.$window.on('resize.' + name + base.id, base.toggleHeaders);
}
base.$scrollableArea.on('resize.' + name, base.toggleHeaders);
base.$scrollableArea.on('resize.' + name, base.updateWidth);
};
base.unbind = function(){
// unbind window events by specifying handle so we don't remove too much
base.$scrollableArea.off('.' + name, base.toggleHeaders);
if (!base.isWindowScrolling) {
base.$window.off('.' + name + base.id, base.setPositionValues);
base.$window.off('.' + name + base.id, base.toggleHeaders);
}
base.$scrollableArea.off('.' + name, base.updateWidth);
};
base.toggleHeaders = function () {
if (base.$el) {
base.$el.each(function () {
var $this = $(this),
newLeft,
newTopOffset = base.isWindowScrolling ? (
isNaN(base.options.fixedOffset) ?
base.options.fixedOffset.outerHeight() :
base.options.fixedOffset
) :
base.$scrollableArea.offset().top + (!isNaN(base.options.fixedOffset) ? base.options.fixedOffset : 0),
offset = $this.offset(),
scrollTop = base.$scrollableArea.scrollTop() + newTopOffset,
scrollLeft = base.$scrollableArea.scrollLeft(),
scrolledPastTop = base.isWindowScrolling ?
scrollTop > offset.top :
newTopOffset > offset.top,
notScrolledPastBottom = (base.isWindowScrolling ? scrollTop : 0) <
(offset.top + $this.height() - base.$clonedHeader.height() - (base.isWindowScrolling ? 0 : newTopOffset));
if (scrolledPastTop && notScrolledPastBottom) {
newLeft = offset.left - scrollLeft + base.options.leftOffset;
base.$originalHeader.css({
'position': 'fixed',
'margin-top': base.options.marginTop,
'left': newLeft,
'z-index': 3 // #18: opacity bug
});
base.leftOffset = newLeft;
base.topOffset = newTopOffset;
base.$clonedHeader.css('display', '');
if (!base.isSticky) {
base.isSticky = true;
// make sure the width is correct: the user might have resized the browser while in static mode
base.updateWidth();
$this.trigger('enabledStickiness.' + name);
}
base.setPositionValues();
} else if (base.isSticky) {
base.$originalHeader.css('position', 'static');
base.$clonedHeader.css('display', 'none');
base.isSticky = false;
base.resetWidth($('td,th', base.$clonedHeader), $('td,th', base.$originalHeader));
$this.trigger('disabledStickiness.' + name);
}
});
}
};
base.setPositionValues = function () {
var winScrollTop = base.$window.scrollTop(),
winScrollLeft = base.$window.scrollLeft();
if (!base.isSticky ||
winScrollTop < 0 || winScrollTop + base.$window.height() > base.$document.height() ||
winScrollLeft < 0 || winScrollLeft + base.$window.width() > base.$document.width()) {
return;
}
base.$originalHeader.css({
'top': base.topOffset - (base.isWindowScrolling ? 0 : winScrollTop),
'left': base.leftOffset - (base.isWindowScrolling ? 0 : winScrollLeft)
});
};
base.updateWidth = function () {
if (!base.isSticky) {
return;
}
// Copy cell widths from clone
if (!base.$originalHeaderCells) {
base.$originalHeaderCells = $('th,td', base.$originalHeader);
}
if (!base.$clonedHeaderCells) {
base.$clonedHeaderCells = $('th,td', base.$clonedHeader);
}
var cellWidths = base.getWidth(base.$clonedHeaderCells);
base.setWidth(cellWidths, base.$clonedHeaderCells, base.$originalHeaderCells);
// Copy row width from whole table
base.$originalHeader.css('width', base.$clonedHeader.width());
};
base.getWidth = function ($clonedHeaders) {
var widths = [];
$clonedHeaders.each(function (index) {
var width, $this = $(this);
if ($this.css('box-sizing') === 'border-box') {
var boundingClientRect = $this[0].getBoundingClientRect();
if(boundingClientRect.width) {
width = boundingClientRect.width; // #39: border-box bug
} else {
width = boundingClientRect.right - boundingClientRect.left; // ie8 bug: getBoundingClientRect() does not have a width property
}
} else {
var $origTh = $('th', base.$originalHeader);
if ($origTh.css('border-collapse') === 'collapse') {
if (window.getComputedStyle) {
width = parseFloat(window.getComputedStyle(this, null).width);
} else {
// ie8 only
var leftPadding = parseFloat($this.css('padding-left'));
var rightPadding = parseFloat($this.css('padding-right'));
// Needs more investigation - this is assuming constant border around this cell and it's neighbours.
var border = parseFloat($this.css('border-width'));
width = $this.outerWidth() - leftPadding - rightPadding - border;
}
} else {
width = $this.width();
}
}
widths[index] = width;
});
return widths;
};
base.setWidth = function (widths, $clonedHeaders, $origHeaders) {
$clonedHeaders.each(function (index) {
var width = widths[index];
$origHeaders.eq(index).css({
'min-width': width,
'max-width': width
});
});
};
base.resetWidth = function ($clonedHeaders, $origHeaders) {
$clonedHeaders.each(function (index) {
var $this = $(this);
$origHeaders.eq(index).css({
'min-width': $this.css('min-width'),
'max-width': $this.css('max-width')
});
});
};
base.setOptions = function (options) {
base.options = $.extend({}, defaults, options);
base.$window = $(base.options.objWindow);
base.$head = $(base.options.objHead);
base.$document = $(base.options.objDocument);
base.$scrollableArea = $(base.options.scrollableArea);
base.isWindowScrolling = base.$scrollableArea[0] === base.$window[0];
};
base.updateOptions = function (options) {
base.setOptions(options);
// scrollableArea might have changed
base.unbind();
base.bind();
base.updateWidth();
base.toggleHeaders();
};
// Run initializer
base.init();
}
// A plugin wrapper around the constructor,
// preventing against multiple instantiations
$.fn[name] = function ( options ) {
return this.each(function () {
var instance = $.data(this, 'plugin_' + name);
if (instance) {
if (typeof options === 'string') {
instance[options].apply(instance);
} else {
instance.updateOptions(options);
}
} else if(options !== 'destroy') {
$.data(this, 'plugin_' + name, new Plugin( this, options ));
}
});
};
})(jQuery, window);
</script>
In my jquery-1.8.3.js:6841
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
How to recover this ? Please help.

Scolling a div up and down

I have set up a fiddle
http://jsfiddle.net/austinind/aadcd/1/
what I am trying to achieve is a parallax effect.
the div should scoll up and down based on the scolling.
in my case the div only scrolls up:
function parallax(){
var scrolled = $(window).scrollTop();
var elempos=$(".bg2").position().top;
$('.bg2').css('top', elempos-(scrolled * 0.2) + 'px');
}
$(window).scroll(function(e){
parallax();
});
Take a look at following Js fiddle
Javscript for scroll
(function($) {
var types = ['DOMMouseScroll', 'mousewheel'];
if ($.event.fixHooks) {
for ( var i=types.length; i; ) {
$.event.fixHooks[ types[--i] ] = $.event.mouseHooks;
}
}
$.event.special.mousewheel = {
setup: function() {
if ( this.addEventListener ) {
for ( var i=types.length; i; ) {
this.addEventListener( types[--i], handler, false );
}
} else {
this.onmousewheel = handler;
}
},
teardown: function() {
if ( this.removeEventListener ) {
for ( var i=types.length; i; ) {
this.removeEventListener( types[--i], handler, false );
}
} else {
this.onmousewheel = null;
}
}
};
$.fn.extend({
mousewheel: function(fn) {
return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
},
unmousewheel: function(fn) {
return this.unbind("mousewheel", fn);
}
});
function handler(event) {
var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0;
event = $.event.fix(orgEvent);
event.type = "mousewheel";
// Old school scrollwheel delta
if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta/120; }
if ( orgEvent.detail ) { delta = -orgEvent.detail/3; }
// New school multidimensional scroll (touchpads) deltas
deltaY = delta;
// Gecko
if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
deltaY = 0;
deltaX = -1*delta;
}
// Webkit
if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; }
if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; }
// Add event and delta to the front of the arguments
args.unshift(event, delta, deltaX, deltaY);
return ($.event.dispatch || $.event.handle).apply(this, args);
}
})(jQuery);
// OUR CODE
var winH = $(window).height();
$('.page').height(winH);
var c = 0;
var pagesN = $('.page').length;
$(document).bind('mousewheel', function(ev, delta) {
delta>0 ? --c : ++c ;
if(c===-1){
c=0;
}else if(c===pagesN){
c=pagesN-1;
}
var pagePos = $('.page').eq(c).position().top;
$('html, body').stop().animate({scrollTop: pagePos},1000);
return false;
});
Your script is working fine, your actual problem is your CSS
Remove
position:Fixed
for the class bg2, And it will work fine
Fiddle
http://jsfiddle.net/AmarnathRShenoy/aadcd/2/

HammerJS pull to refresh

I know very little about Javascript but need to use hammer.js in a project I'm working on.
Instead of replacing/refreshing the image im trying to use the pull to refresh scrit to refresh the page.
Ive tried adding
location.reload();
to the script but to no avail, can anyone shed any light on this.
http://eightmedia.github.io/hammer.js/
This is the code im using
/**
* requestAnimationFrame and cancel polyfill
*/
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame =
window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}());
/**
* pull to refresh
* #type {*}
*/
var PullToRefresh = (function() {
function Main(container, slidebox, slidebox_icon, handler) {
var self = this;
this.breakpoint = 80;
this.container = container;
this.slidebox = slidebox;
this.slidebox_icon = slidebox_icon;
this.handler = handler;
this._slidedown_height = 0;
this._anim = null;
this._dragged_down = false;
this.hammertime = Hammer(this.container)
.on("touch dragdown release", function(ev) {
self.handleHammer(ev);
});
};
/**
* Handle HammerJS callback
* #param ev
*/
Main.prototype.handleHammer = function(ev) {
var self = this;
switch(ev.type) {
// reset element on start
case 'touch':
this.hide();
break;
// on release we check how far we dragged
case 'release':
if(!this._dragged_down) {
return;
}
// cancel animation
cancelAnimationFrame(this._anim);
// over the breakpoint, trigger the callback
if(ev.gesture.deltaY >= this.breakpoint) {
container_el.className = 'pullrefresh-loading';
pullrefresh_icon_el.className = 'icon loading';
this.setHeight(60);
this.handler.call(this);
}
// just hide it
else {
pullrefresh_el.className = 'slideup';
container_el.className = 'pullrefresh-slideup';
this.hide();
}
break;
// when we dragdown
case 'dragdown':
this._dragged_down = true;
// if we are not at the top move down
var scrollY = window.scrollY;
if(scrollY > 5) {
return;
} else if(scrollY !== 0) {
window.scrollTo(0,0);
}
// no requestAnimationFrame instance is running, start one
if(!this._anim) {
this.updateHeight();
}
// stop browser scrolling
ev.gesture.preventDefault();
// update slidedown height
// it will be updated when requestAnimationFrame is called
this._slidedown_height = ev.gesture.deltaY * 0.4;
break;
}
};
/**
* when we set the height, we just change the container y
* #param {Number} height
*/
Main.prototype.setHeight = function(height) {
if(Modernizr.csstransforms3d) {
this.container.style.transform = 'translate3d(0,'+height+'px,0) ';
this.container.style.oTransform = 'translate3d(0,'+height+'px,0)';
this.container.style.msTransform = 'translate3d(0,'+height+'px,0)';
this.container.style.mozTransform = 'translate3d(0,'+height+'px,0)';
this.container.style.webkitTransform = 'translate3d(0,'+height+'px,0) scale3d(1,1,1)';
}
else if(Modernizr.csstransforms) {
this.container.style.transform = 'translate(0,'+height+'px) ';
this.container.style.oTransform = 'translate(0,'+height+'px)';
this.container.style.msTransform = 'translate(0,'+height+'px)';
this.container.style.mozTransform = 'translate(0,'+height+'px)';
this.container.style.webkitTransform = 'translate(0,'+height+'px)';
}
else {
this.container.style.top = height+"px";
}
};
/**
* hide the pullrefresh message and reset the vars
*/
Main.prototype.hide = function() {
container_el.className = '';
this._slidedown_height = 0;
this.setHeight(0);
cancelAnimationFrame(this._anim);
this._anim = null;
this._dragged_down = false;
};
/**
* hide the pullrefresh message and reset the vars
*/
Main.prototype.slideUp = function() {
var self = this;
cancelAnimationFrame(this._anim);
pullrefresh_el.className = 'slideup';
container_el.className = 'pullrefresh-slideup';
this.setHeight(0);
setTimeout(function() {
self.hide();
}, 500);
};
/**
* update the height of the slidedown message
*/
Main.prototype.updateHeight = function() {
var self = this;
this.setHeight(this._slidedown_height);
if(this._slidedown_height >= this.breakpoint){
this.slidebox.className = 'breakpoint';
this.slidebox_icon.className = 'icon arrow arrow-up';
}
else {
this.slidebox.className = '';
this.slidebox_icon.className = 'icon arrow';
}
this._anim = requestAnimationFrame(function() {
self.updateHeight();
});
};
return Main;
})();
function getEl(id) {
return document.getElementById(id);
}
var container_el = getEl('container');
var pullrefresh_el = getEl('pullrefresh');
var pullrefresh_icon_el = getEl('pullrefresh-icon');
var image_el = getEl('random-image');
var refresh = new PullToRefresh(container_el, pullrefresh_el, pullrefresh_icon_el);
// update image onrefresh
refresh.handler = function() {
var self = this;
// a small timeout to demo the loading state
setTimeout(function() {
var preload = new Image();
preload.onload = function() {
image_el.src = this.src;
self.slideUp();
};
preload.src = 'http://lorempixel.com/800/600/?'+ (new Date().getTime());
}, 1000);
};
There is a Beer involved for anyone that can fix this :)
http://jsfiddle.net/zegermens/PDcr9/1/
You're assigning the return value of the location.reload function to the src attribute of an Image element. I'm not sure if the function even has a return value, https://developer.mozilla.org/en-US/docs/Web/API/Location.reload
Try this:
// update image onrefresh
refresh.handler = function() {
var self = this;
// a small timeout to demo the loading state
setTimeout(function() {
window.location.reload();
}, 1000);
};

Isotope js detect first/last child in a row

How to detect first/last child in a row via isotope js?
I want to remove margins between elements.
This is layout.` // ====================== fitRows ======================
_fitRowsReset : function() {
this.fitRows = {
x : 0,
y : 0,
height : 0
};
},
_fitRowsLayout : function( $elems ) {
var instance = this,
containerWidth = this.element.width(),
props = this.fitRows;
$elems.each( function() {
var $this = $(this),
atomW = $this.outerWidth(true),
atomH = $this.outerHeight(true);
if ( props.x !== 0 && atomW + props.x > containerWidth ) {
// if this element cannot fit in the current row
props.x = 0;
props.y = props.height;
}
// position the atom
instance._pushPosition( $this, props.x, props.y );
props.height = Math.max( props.y + atomH, props.height );
props.x += atomW;
});
},
_fitRowsGetContainerSize : function () {
return { height : this.fitRows.height };
},
_fitRowsResizeChanged : function() {
return true;
},
`
Solution is simple
// ====================== fitRows ======================
_fitRowsReset : function() {
this.fitRows = {
x : 0,
y : 0,
height : 0
};
},
_fitRowsLayout : function( $elems ) {
var instance = this,
containerWidth = this.element.width(),
props = this.fitRows;
$elems.each( function() {
var $this = $(this),
atomW = $this.outerWidth(true),
atomH = $this.outerHeight(true);
$(this).removeClass('first last');
if (props.x == 0) {
$(this).addClass('first');
$(this).prev().addClass('last');
}
if ( props.x !== 0 && atomW + props.x > containerWidth ) {
// if this element cannot fit in the current row
props.x = 0;
props.y = props.height;
$(this).addClass('first');
$(this).prev().addClass('last');
}
// position the atom
instance._pushPosition( $this, props.x, props.y );
props.height = Math.max( props.y + atomH, props.height );
props.x += atomW;
});
},
_fitRowsGetContainerSize : function () {
return { height : this.fitRows.height };
},
_fitRowsResizeChanged : function() {
return true;
},

Categories