I'm working on an existing popunder script and it works great but the problem is that it triggers even if the cookie is set, its not supposed to trigger if the cookie is set and I can't figure it out how to solve this, I want it to trigger once every 1 hour, thanks
/**
* Smart Popunder maker.
* This class provides an easy way to make a popunder.
* Avoid blocked on Google Chrome
*
* Note: For Google Chrome, to avoid blocked so each popunder will be fired by each click.
*
* #author: Phan Thanh Cong aka chiplove <ptcong90#gmail.com>
* #license: MIT
*
* Edit by: Rafel Sansó <rafel.sanso#gmail.com>
*
* Changelog
*
* version 2.3.2.1; Apr 23, 2015
* - Eventually, the popup doesn't launch. To prevent this I comment lines 174, 180 and 208
*
*/
(function(window){
"use strict";
var Popunder = function(url, options){ this.__construct(url, options); },
counter = 0,
lastPopTime = 0,
alertCalled = false,
baseName = 'ChipPopunder',
parent = top != self ? top : self,
userAgent = navigator.userAgent.toLowerCase(),
browser = {
webkit: /webkit/.test(userAgent),
mozilla: /mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent),
chrome: /chrome/.test(userAgent),
msie: /msie|trident\//.test(userAgent) && !/opera/.test(userAgent),
firefox: /firefox/.test(userAgent),
safari: /safari/.test(userAgent) && !/chrome/.test(userAgent),
opera: /opera/.test(userAgent),
version: parseInt(userAgent.match(/(?:[^\s]+(?:ri|ox|me|ra)\/|trident\/.*?rv:)([\d]+)/i)[1], 10)
},
helper = {
simulateClick: function(url) {
var a = document.createElement("a"),
nothing = "",
evt = document.createEvent("MouseEvents");
a.href = url || "data:text/html,<script>window.close();<\/script>;";
document.body.appendChild(a);
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, true, 0, null);
a.dispatchEvent(evt);
a.parentNode.removeChild(a);
},
blur: function(popunder) {
try {
popunder.blur();
popunder.opener.window.focus();
window.self.window.focus();
window.focus();
if (browser.firefox) {
this.openCloseWindow(popunder);
} else if (browser.webkit) {
// try to blur popunder window on chrome
// but not works on chrome 41
// so we should wrap this to avoid chrome display warning
if (!browser.chrome || (browser.chrome && browser.version < 41)) {
this.openCloseTab();
}
} else if (browser.msie) {
setTimeout(function() {
popunder.blur();
popunder.opener.window.focus();
window.self.window.focus();
window.focus();
}, 1000);
}
} catch(err) {}
},
openCloseWindow: function(popunder) {
var tmp = popunder.window.open("about:blank");
tmp.focus();
tmp.close();
setTimeout(function() {
try {
tmp = popunder.window.open("about:blank");
tmp.focus();
tmp.close();
} catch (e) {}
}, 1);
},
openCloseTab: function() {
this.simulateClick();
},
detachEvent: function(event, callback, object) {
var object = object || window;
if (!object.removeEventListener) {
return object.detachEvent("on" + event, callback);
}
return object.removeEventListener(event, callback);
},
attachEvent: function(event, callback, object) {
var object = object || window;
if (!object.addEventListener) {
return object.attachEvent("on" + event, callback);
}
return object.addEventListener(event, callback);
},
mergeObject: function() {
var obj = {}, i, k;
for(i = 0; i < arguments.length; i++) {
for (k in arguments[i]) {
obj[k] = arguments[i][k];
}
}
return obj;
},
getCookie: function(name) {
var cookieMatch = document.cookie.match(new RegExp(name+"=[^;]+", "i"));
return cookieMatch ? decodeURIComponent(cookieMatch[0].split("=")[1]) : null;
},
setCookie: function(name, value, expires, path) {
// expires must be number of minutes or instance of Date;
if(expires === null || typeof expires == 'undefined') {
expires = '';
} else {
var date;
if (typeof expires == 'number') {
date = new Date();
date.setTime(date.getTime() + expires * 60 * 1e3);
} else {
date = expires;
}
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + escape(value) + expires + "; path=" + (path || '/');
}
};
Popunder.prototype = {
defaultWindowOptions: {
width : window.screen.width,
height : window.screen.height,
left : 0,
top : 0,
location : 1,
toolbar : 1,
status : 1,
menubar : 1,
scrollbars : 1,
resizable : 1
},
defaultPopOptions: {
cookieExpires : 60, // in minutes
cookiePath : '/',
newTab : true,
blur : true,
blurByAlert : false, //
chromeDelay : 500,
smart : false, // for feature, if browsers block event click to window/body
beforeOpen : function(){},
afterOpen : function(){}
},
// Must use the options to create a new window in chrome
__chromeNewWindowOptions: {
scrollbars : 0
},
__construct: function(url, options) {
this.url = url;
this.index = counter++;
this.name = baseName + '_' + (this.index);
this.executed = false;
this.setOptions(options);
this.register();
},
register: function() {
//if (this.isExecuted()) return;
var self = this, w, i,
elements = [],
eventName = 'click',
run = function(e) {
// e.preventDefault();
//if (self.shouldExecute()) {
lastPopTime = new Date().getTime();
self.setExecuted();
self.options.beforeOpen.call(undefined, this);
if (self.options.newTab) {
if (browser.chrome && browser.version > 30 && self.options.blur) {
window.open('javascript:window.focus()', '_self', '');
helper.simulateClick(self.url);
w = null;
} else {
w = parent.window.open(self.url, '_blank');
setTimeout(function(){
if (!alertCalled && self.options.blurByAlert) {
alertCalled = true;
alert();
}
}, 3);
}
} else {
w = parent.window.open(self.url, this.url, self.getParams());
}
if (self.options.blur) {
helper.blur(w);
}
self.options.afterOpen.call(undefined, this);
for(i in elements) {
helper.detachEvent(eventName, run, elements[i]);
}
//}
},
inject = function(e){
if (self.isExecuted()) {
helper.detachEvent('mousemove', inject);
return;
}
try {
if (e.originalTarget && typeof e.originalTarget[self.name] == 'undefined') {
e.originalTarget[self.name] = true;
helper.attachEvent(eventName, run, e.originalTarget);
elements.push(e.originalTarget);
}
} catch(err) {}
};
// smart injection
if (this.options.smart) {
helper.attachEvent('mousemove', inject);
} else {
helper.attachEvent(eventName, run, window);
elements.push(window);
helper.attachEvent(eventName, run, document);
elements.push(document);
}
},
shouldExecute: function() {
if (browser.chrome && lastPopTime && lastPopTime + this.options.chromeDelay > new Date().getTime()) {
return false;
}
return !this.isExecuted();
},
isExecuted: function() {
return this.executed || !!helper.getCookie(this.name);
},
setExecuted: function() {
this.executed = true;
helper.setCookie(this.name, 1, this.options.cookieExpires, this.options.cookiePath);
},
setOptions: function(options) {
this.options = helper.mergeObject(this.defaultWindowOptions, this.defaultPopOptions, options || {});
if (!this.options.newTab && browser.chrome) {
for(var k in this.__chromeNewWindowOptions) {
this.options[k] = this.__chromeNewWindowOptions[k];
}
}
},
getParams: function() {
var params = '', k;
for (k in this.options) {
if (typeof this.defaultWindowOptions[k] != 'undefined') {
params += (params ? "," : "") + k + "=" + this.options[k];
}
}
return params;
}
};
Popunder.make = function(url, options) {
return new this(url, options);
};
window.SmartPopunder = Popunder;
})(window);
I've tried in different ways to solve this but it won't work, what I need to mention is that, I'm a noob in javascript
THANKS FOR NO HELP; I miss the old times when users went here for help even if they were a noob, they would still get some help, nowadays all you get is "Suggested Editing" they fix you and "I" and nothing much, what if English is not my first language? FFS what happened to this community?
Anyways, maybe there will be noob people like me that will want to use this popunder, i fixed the problem here is the full working code.
/**
* Smart Popunder maker.
* This class provides an easy way to make a popunder.
* Avoid blocked on Google Chrome
*
* Note: For Google Chrome, to avoid blocked so each popunder will be fired by each click.
*
* #author: Phan Thanh Cong aka chiplove <ptcong90#gmail.com>
* #license: MIT
*
* Edit by: Rafel Sansó <rafel.sanso#gmail.com>
*
* Changelog
*
* version 2.3.2.1; Apr 23, 2015
* - Eventually, the popup doesn't launch. To prevent this I comment lines 174, 180 and 208
*
*/
(function(window){
"use strict";
var Popunder = function(url, options){ this.__construct(url, options); },
counter = 0,
lastPopTime = 0,
alertCalled = false,
baseName = 'ChipPopunder',
parent = top != self ? top : self,
userAgent = navigator.userAgent.toLowerCase(),
browser = {
webkit: /webkit/.test(userAgent),
mozilla: /mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent),
chrome: /chrome/.test(userAgent),
msie: /msie|trident\//.test(userAgent) && !/opera/.test(userAgent),
firefox: /firefox/.test(userAgent),
safari: /safari/.test(userAgent) && !/chrome/.test(userAgent),
opera: /opera/.test(userAgent),
version: parseInt(userAgent.match(/(?:[^\s]+(?:ri|ox|me|ra)\/|trident\/.*?rv:)([\d]+)/i)[1], 10)
},
helper = {
simulateClick: function(url) {
var a = document.createElement("a"),
nothing = "",
evt = document.createEvent("MouseEvents");
a.href = url || "data:text/html,<script>window.close();<\/script>;";
document.body.appendChild(a);
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, true, 0, null);
a.dispatchEvent(evt);
a.parentNode.removeChild(a);
},
blur: function(popunder) {
try {
popunder.blur();
popunder.opener.window.focus();
window.self.window.focus();
window.focus();
if (browser.firefox) {
this.openCloseWindow(popunder);
} else if (browser.webkit) {
// try to blur popunder window on chrome
// but not works on chrome 41
// so we should wrap this to avoid chrome display warning
if (!browser.chrome || (browser.chrome && browser.version < 41)) {
this.openCloseTab();
}
} else if (browser.msie) {
setTimeout(function() {
popunder.blur();
popunder.opener.window.focus();
window.self.window.focus();
window.focus();
}, 1000);
}
} catch(err) {}
},
openCloseWindow: function(popunder) {
var tmp = popunder.window.open("about:blank");
tmp.focus();
tmp.close();
setTimeout(function() {
try {
tmp = popunder.window.open("about:blank");
tmp.focus();
tmp.close();
} catch (e) {}
}, 1);
},
openCloseTab: function() {
this.simulateClick();
},
detachEvent: function(event, callback, object) {
var object = object || window;
if (!object.removeEventListener) {
return object.detachEvent("on" + event, callback);
}
return object.removeEventListener(event, callback);
},
attachEvent: function(event, callback, object) {
var object = object || window;
if (!object.addEventListener) {
return object.attachEvent("on" + event, callback);
}
return object.addEventListener(event, callback);
},
mergeObject: function() {
var obj = {}, i, k;
for(i = 0; i < arguments.length; i++) {
for (k in arguments[i]) {
obj[k] = arguments[i][k];
}
}
return obj;
},
getCookie: function(name) {
var cookieMatch = document.cookie.match(new RegExp(name+"=[^;]+", "i"));
return cookieMatch ? decodeURIComponent(cookieMatch[0].split("=")[1]) : null;
},
setCookie: function(name, value, expires, path) {
// expires must be number of minutes or instance of Date;
if(expires === null || typeof expires == 'undefined') {
expires = '';
} else {
var date;
if (typeof expires == 'number') {
date = new Date();
date.setTime(date.getTime() + expires * 60 * 1e3);
} else {
date = expires;
}
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + escape(value) + expires + "; path=" + (path || '/');
}
};
Popunder.prototype = {
defaultWindowOptions: {
width : window.screen.width,
height : window.screen.height,
left : 0,
top : 0,
location : 1,
toolbar : 1,
status : 1,
menubar : 1,
scrollbars : 1,
resizable : 1
},
defaultPopOptions: {
cookieExpires : 60, // in minutes
cookiePath : '/',
newTab : true,
blur : true,
blurByAlert : false, //
chromeDelay : 500,
smart : false, // for feature, if browsers block event click to window/body
beforeOpen : function(){},
afterOpen : function(){}
},
// Must use the options to create a new window in chrome
__chromeNewWindowOptions: {
scrollbars : 0
},
__construct: function(url, options) {
this.url = url;
this.index = counter++;
this.name = baseName + '_' + (this.index);
this.executed = false;
this.setOptions(options);
this.register();
},
register: function() {
if (this.isExecuted()) return;
var self = this, w, i,
elements = [],
eventName = 'click',
run = function(e) {
// e.preventDefault();
//if (self.shouldExecute()) {
lastPopTime = new Date().getTime();
self.setExecuted();
self.options.beforeOpen.call(undefined, this);
if (self.options.newTab) {
if (browser.chrome && browser.version > 30 && self.options.blur) {
window.open('javascript:window.focus()', '_self', '');
helper.simulateClick(self.url);
w = null;
} else {
w = parent.window.open(self.url, '_blank');
setTimeout(function(){
if (!alertCalled && self.options.blurByAlert) {
alertCalled = true;
alert();
}
}, 3);
}
} else {
w = parent.window.open(self.url, this.url, self.getParams());
}
if (self.options.blur) {
helper.blur(w);
}
self.options.afterOpen.call(undefined, this);
for(i in elements) {
helper.detachEvent(eventName, run, elements[i]);
}
//}
},
inject = function(e){
if (self.isExecuted()) {
helper.detachEvent('mousemove', inject);
return;
}
try {
if (e.originalTarget && typeof e.originalTarget[self.name] == 'undefined') {
e.originalTarget[self.name] = true;
helper.attachEvent(eventName, run, e.originalTarget);
elements.push(e.originalTarget);
}
} catch(err) {}
};
// smart injection
if (this.options.smart) {
helper.attachEvent('mousemove', inject);
} else {
helper.attachEvent(eventName, run, window);
elements.push(window);
helper.attachEvent(eventName, run, document);
elements.push(document);
}
},
shouldExecute: function() {
if (browser.chrome && lastPopTime && lastPopTime + this.options.chromeDelay > new Date().getTime()) {
return false;
}
return !this.isExecuted();
},
isExecuted: function() {
return this.executed || !!helper.getCookie(this.name);
},
setExecuted: function() {
this.executed = true;
helper.setCookie(this.name, 1, this.options.cookieExpires, this.options.cookiePath);
},
setOptions: function(options) {
this.options = helper.mergeObject(this.defaultWindowOptions, this.defaultPopOptions, options || {});
if (!this.options.newTab && browser.chrome) {
for(var k in this.__chromeNewWindowOptions) {
this.options[k] = this.__chromeNewWindowOptions[k];
}
}
},
getParams: function() {
var params = '', k;
for (k in this.options) {
if (typeof this.defaultWindowOptions[k] != 'undefined') {
params += (params ? "," : "") + k + "=" + this.options[k];
}
}
return params;
}
};
Popunder.make = function(url, options) {
return new this(url, options);
};
window.SmartPopunder = Popunder;
})(window);
add the code above into a js file like popunder.js and in order to trigger it you will need to use this code
<script type="text/javascript" src="https://www.website.com/js/popunder.js"></script>
<script type="text/javascript">
// use cookie expires on 1 hour * cookieExpires
SmartPopunder.make('https://www.website.com', {cookieExpires:60, newTab: true, width: window.screen.width, height: window.screen.height});
</script>
Regards
Actually I was trying to create a popunder code but it's not working correctly so searched for quite a while on online. But no luck. Here's an example from past.
function makePopunder(pUrl) {
var _parent = (top != self && typeof (top["document"]["location"].toString()) === "string") ? top : self;
var mypopunder = null;
var pName = (Math["floor"]((Math["random"]() * 1000) + 1));
var pWidth = window["innerWidth"];
var pHeight = window["innerHeight"];
var pPosX = window["screenX"];
var pPosY = window["screenY"];
var pWait = 3600;
pWait = (pWait * 1000);
var pCap = 50000;
var todayPops = 0;
var cookie = "_.mypopunder";
var browser = function () {
var n = navigator["userAgent"]["toLowerCase"]();
var b = {
webkit: /webkit/ ["test"](n),
mozilla: (/mozilla/ ["test"](n)) && (!/(compatible|webkit)/ ["test"](n)),
chrome: /chrome/ ["test"](n),
msie: (/msie/ ["test"](n)) && (!/opera/ ["test"](n)),
firefox: /firefox/ ["test"](n),
safari: (/safari/ ["test"](n) && !(/chrome/ ["test"](n))),
opera: /opera/ ["test"](n)
};
b["version"] = (b["safari"]) ? (n["match"](/.+(?:ri)[\\/: ]([\\d.]+)/) || [])[1] : (n["match"](/.+(?:ox|me|ra|ie)[\\/: ]([\\d.]+)/) || [])[1];
return b;
}();
function isCapped() {
try {
todayPops = Math["floor"](document["cookie"]["split"](cookie + "Cap=")[1]["split"](";")[0]);
} catch (err) {};
return (pCap <= todayPops || document["cookie"]["indexOf"](cookie + "=") !== -1);
};
function doPopunder(pUrl, pName, pWidth, pHeight, pPosX, pPosY) {
if (isCapped()) {
return;
};
var sOptions = "toolbar=no,scrollbars=yes,location=yes,statusbar=yes,menubar=no,resizable=1,width=" + pWidth.toString() + ",height=" + pHeight.toString() + ",screenX=" + pPosX + ",screenY=" + pPosY;
document["onclick"] = function (e) {
if (isCapped() || window["pop_clicked"] == 1 || pop_isRightButtonClicked(e)) {
//return;
};
window["pop_clicked"] = 1;
mypopunder = _parent["window"]["open"](pUrl, pName, sOptions);
if (mypopunder) {
var now = new Date();
document["cookie"] = cookie + "=1;expires=" + new Date(now["setTime"](now["getTime"]() + pWait))["toGMTString"]() + ";path=/";
now = new Date();
document["cookie"] = cookie + "Cap=" + (todayPops + 1) + ";expires=" + new Date(now["setTime"](now["getTime"]() + (84600 * 1000)))["toGMTString"]() + ";path=/";
pop2under();
};
};
};
function pop2under() {
try {
mypopunder["blur"]();
mypopunder["opener"]["window"]["focus"]();
window["self"]["window"]["blur"]();
window["focus"]();
if (browser["firefox"]) {
openCloseWindow();
};
if (browser["webkit"]) {
openCloseTab();
};
} catch (e) {};
};
function openCloseWindow() {
var ghost = window["open"]("about:blank");
ghost["focus"]();
ghost["close"]();
};
function openCloseTab() {
var ghost = document["createElement"]("a");
ghost["href"] = "about:blank";
ghost["target"] = "PopHelper";
document["getElementsByTagName"]("body")[0]["appendChild"](ghost);
ghost["parentNode"]["removeChild"](ghost);
var clk = document["createEvent"]("MouseEvents");
clk["initMouseEvent"]("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, true, 0, null);
ghost["dispatchEvent"](clk);
window["open"]("about:blank", "PopHelper")["close"]();
};
function pop_isRightButtonClicked(e) {
var rightclick = false;
e = e || window["event"];
if (e["which"]) {
rightclick = (e["which"] == 3);
} else {
if (e["button"]) {
rightclick = (e["button"] == 2);
};
};
return rightclick;
};
if (isCapped()) {
return;
} else {
doPopunder(pUrl, pName, pWidth, pHeight, pPosX, pPosY);
};
}
makePopunder("http://www.yourdomain.com/");
I actually wanted to make something similar to this site : http://popunderjs.com/
you can check the demo here it's kind of amazing : http://code.ptcong.com/demos/bjp/demo.html
Something in this Curtains.js plug-in is preventing user text selection on my page. When I comment it out, I'm able to select text, when I put it back in, I'm not. Can someone identify it and tell me how to fix it? I'm at my wit's end.
<script>
/*
* Curtain.js - Create an unique page transitioning system
* ---
* Version: 2
* Copyright 2011, Victor Coulon (http://victorcoulon.fr)
* Released under the MIT Licence
*/
(function ( $, window, document, undefined ) {
var pluginName = 'curtain',
defaults = {
scrollSpeed: 400,
bodyHeight: 0,
linksArray: [],
mobile: false,
scrollButtons: {},
controls: null,
curtainLinks: '.curtain-links',
enableKeys: true,
easing: 'swing',
disabled: false,
nextSlide: function() {},
prevSlide: function() {}
};
// The actual plugin constructor
function Plugin( element, options ) {
var self = this;
// Public attributes
this.element = element;
this.options = $.extend( {}, defaults, options) ;
this._defaults = defaults;
this._name = pluginName;
this._ignoreHashChange = false;
this.init();
}
Plugin.prototype = {
init: function () {
var self = this;
// Cache element
this.$element = $(this.element);
this.$li = $(this.element).find('>li');
this.$liLength = this.$li.length;
self.$windowHeight = $(window).height();
self.$elDatas = {};
self.$document = $(document);
self.$window = $(window);
self.webkit = (navigator.userAgent.indexOf('Chrome') > -1 || navigator.userAgent.indexOf("Safari") > -1);
$.Android = (navigator.userAgent.match(/Android/i));
$.iPhone = ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)));
$.iPad = ((navigator.userAgent.match(/iPad/i)));
$.iOs4 = (/OS [1-4]_[0-9_]+ like Mac OS X/i.test(navigator.userAgent));
if($.iPhone || $.iPad || $.Android || self.options.disabled){
this.options.mobile = true;
this.$li.css({position:'relative'});
this.$element.find('.fixed').css({position:'absolute'});
}
if(this.options.mobile){
this.scrollEl = this.$element;
} else if($.browser.mozilla || $.browser.msie) {
this.scrollEl = $('html');
} else {
this.scrollEl = $('body');
}
if(self.options.controls){
self.options.scrollButtons['up'] = $(self.options.controls).find('[href="#up"]');
self.options.scrollButtons['down'] = $(self.options.controls).find('[href="#down"]');
if(!$.iOs4 && ($.iPhone || $.iPad)){
self.$element.css({
position:'fixed',
top:0,
left:0,
right:0,
bottom:0,
'-webkit-overflow-scrolling':'touch',
overflow:'auto'
});
$(self.options.controls).css({position:'absolute'});
}
}
// When all image is loaded
var callbackImageLoaded = function(){
self.setDimensions();
self.$li.eq(0).addClass('current');
self.setCache();
if(!self.options.mobile){
if(self.$li.eq(1).length)
self.$li.eq(1).nextAll().addClass('hidden');
}
self.setEvents();
self.setLinks();
self.isHashIsOnList(location.hash.substring(1));
};
if(self.$element.find('img').length)
self.imageLoaded(callbackImageLoaded);
else
callbackImageLoaded();
},
// Events
scrollToPosition: function (direction){
var position = null,
self = this;
if(self.scrollEl.is(':animated')){
return false;
}
if(direction === 'up' || direction == 'down'){
// Keyboard event
var $next = (direction === 'up') ? self.$current.prev() : self.$current.next();
// Step in the current panel ?
if(self.$step){
if(!self.$current.find('.current-step').length){
self.$step.eq(0).addClass('current-step');
}
var $nextStep = (direction === 'up') ? self.$current.find('.current-step').prev('.step') : self.$current.find('.current-step').next('.step');
if($nextStep.length) {
position = (self.options.mobile) ? $nextStep.position().top + self.$elDatas[self.$current.index()]['data-position'] : $nextStep.position().top + self.$elDatas[self.$current.index()]['data-position'];
}
}
position = position || ((self.$elDatas[$next.index()] === undefined) ? null : self.$elDatas[$next.index()]['data-position']);
if(position !== null){
self.scrollEl.animate({
scrollTop: position
}, self.options.scrollSpeed, self.options.easing);
}
} else if(direction === 'top'){
self.scrollEl.animate({
scrollTop:0
}, self.options.scrollSpeed, self.options.easing);
} else if(direction === 'bottom'){
self.scrollEl.animate({
scrollTop:self.options.bodyHeight
}, self.options.scrollSpeed, self.options.easing);
} else {
var index = $("#"+direction).index(),
speed = Math.abs(self.currentIndex-index) * (this.options.scrollSpeed*4) / self.$liLength;
self.scrollEl.animate({
scrollTop:self.$elDatas[index]['data-position'] || null
}, (speed <= self.options.scrollSpeed) ? self.options.scrollSpeed : speed, this.options.easing);
}
},
scrollEvent: function() {
var self = this,
docTop = self.$document.scrollTop();
if(docTop < self.currentP && self.currentIndex > 0){
// Scroll to top
self._ignoreHashChange = true;
if(self.$current.prev().attr('id'))
self.setHash(self.$current.prev().attr('id'));
self.$current
.removeClass('current')
.css( (self.webkit) ? {'-webkit-transform': 'translateY(0px) translateZ(0)'} : {marginTop: 0} )
.nextAll().addClass('hidden').end()
.prev().addClass('current').removeClass('hidden');
self.setCache();
self.options.prevSlide();
} else if(docTop < (self.currentP + self.currentHeight)){
// Animate the current pannel during the scroll
if(self.webkit)
self.$current.css({'-webkit-transform': 'translateY('+(-(docTop-self.currentP))+'px) translateZ(0)' });
else
self.$current.css({marginTop: -(docTop-self.currentP) });
// If there is a fixed element in the current panel
if(self.$fixedLength){
var dataTop = parseInt(self.$fixed.attr('data-top'), 10);
if(docTop + self.$windowHeight >= self.currentP + self.currentHeight){
self.$fixed.css({
position: 'fixed'
});
} else {
self.$fixed.css({
position: 'absolute',
marginTop: Math.abs(docTop-self.currentP)
});
}
}
// If there is a step element in the current panel
if(self.$stepLength){
$.each(self.$step, function(i,el){
if(($(el).position().top+self.currentP) <= docTop+5 && $(el).position().top + self.currentP + $(el).height() >= docTop+5){
if(!$(el).hasClass('current-step')){
self.$step.removeClass('current-step');
$(el).addClass('current-step');
return false;
}
}
});
}
if(self.parallaxBg){
self.$current.css({
'background-position-y': docTop * self.parallaxBg
});
}
if(self.$fade.length){
self.$fade.css({
'opacity': 1-(docTop/ self.$fade.attr('data-fade'))
});
}
if(self.$slowScroll.length){
self.$slowScroll.css({
'margin-top' : (docTop / self.$slowScroll.attr('data-slow-scroll'))
});
}
} else {
// Scroll bottom
self._ignoreHashChange = true;
if(self.$current.next().attr('id'))
self.setHash(self.$current.next().attr('id'));
self.$current.removeClass('current')
.addClass('hidden')
.next('li').addClass('current').next('li').removeClass('hidden');
self.setCache();
self.options.nextSlide();
}
},
scrollMobileEvent: function() {
var self = this,
docTop = self.$element.scrollTop();
if(docTop+10 < self.currentP && self.currentIndex > 0){
// Scroll to top
self._ignoreHashChange = true;
if(self.$current.prev().attr('id'))
self.setHash(self.$current.prev().attr('id'));
self.$current.removeClass('current').prev().addClass('current');
self.setCache();
self.options.prevSlide();
} else if(docTop+10 < (self.currentP + self.currentHeight)){
// If there is a step element in the current panel
if(self.$stepLength){
$.each(self.$step, function(i,el){
if(($(el).position().top+self.currentP) <= docTop && (($(el).position().top+self.currentP) + $(el).outerHeight()) >= docTop){
if(!$(el).hasClass('current-step')){
self.$step.removeClass('current-step');
$(el).addClass('current-step');
}
}
});
}
} else {
// Scroll bottom
self._ignoreHashChange = true;
if(self.$current.next().attr('id'))
self.setHash(self.$current.next().attr('id'));
self.$current.removeClass('current').next().addClass('current');
self.setCache();
self.options.nextSlide();
}
},
// Setters
setDimensions: function(){
var self = this,
levelHeight = 0,
cover = false,
height = null;
self.$windowHeight = self.$window.height();
this.$li.each(function(index) {
var $self = $(this);
cover = $self.hasClass('cover');
if(cover){
$self.css({height: self.$windowHeight, zIndex: 999-index})
.attr('data-height',self.$windowHeight)
.attr('data-position',levelHeight);
self.$elDatas[$self.index()] = {
'data-height': parseInt(self.$windowHeight,10),
'data-position': parseInt(levelHeight, 10)
};
levelHeight += self.$windowHeight;
} else{
height = ($self.outerHeight() <= self.$windowHeight) ? self.$windowHeight : $self.outerHeight();
$self.css({minHeight: height, zIndex: 999-index})
.attr('data-height',height)
.attr('data-position',levelHeight);
self.$elDatas[$self.index()] = {
'data-height': parseInt(height, 10),
'data-position': parseInt(levelHeight, 10)
};
levelHeight += height;
}
if($self.find('.fixed').length){
var top = $self.find('.fixed').css('top');
$self.find('.fixed').attr('data-top', top);
}
});
if(!this.options.mobile)
this.setBodyHeight();
},
setEvents: function() {
var self = this;
$(window).on('resize', function(){
self.setDimensions();
});
if(self.options.mobile) {
self.$element.on('scroll', function(){
self.scrollMobileEvent();
});
} else {
self.$window.on('scroll', function(){
self.scrollEvent();
});
}
if(self.options.enableKeys) {
self.$document.on('keydown', function(e){
if(e.keyCode === 38 || e.keyCode === 37) {
self.scrollToPosition('up');
e.preventDefault();
return false;
}
if(e.keyCode === 40 || e.keyCode === 39){
self.scrollToPosition('down');
e.preventDefault();
return false;
}
// Home button
if(e.keyCode === 36){
self.scrollToPosition('top');
e.preventDefault();
return false;
}
// End button
if(e.keyCode === 35){
self.scrollToPosition('bottom');
e.preventDefault();
return false;
}
});
}
if(self.options.scrollButtons){
if(self.options.scrollButtons.up){
self.options.scrollButtons.up.on('click', function(e){
e.preventDefault();
self.scrollToPosition('up');
});
}
if(self.options.scrollButtons.down){
self.options.scrollButtons.down.on('click', function(e){
e.preventDefault();
self.scrollToPosition('down');
});
}
}
if(self.options.curtainLinks){
$(self.options.curtainLinks).on('click', function(e){
e.preventDefault();
var href = $(this).attr('href');
if(!self.isHashIsOnList(href.substring(1)) && position)
return false;
var position = self.$elDatas[$(href).index()]['data-position'] || null;
if(position){
self.scrollEl.animate({
scrollTop:position
}, self.options.scrollSpeed, self.options.easing);
}
return false;
});
}
self.$window.on("hashchange", function(event){
if(self._ignoreHashChange === false){
self.isHashIsOnList(location.hash.substring(1));
}
self._ignoreHashChange = false;
});
},
setBodyHeight: function(){
var h = 0;
for (var key in this.$elDatas) {
var obj = this.$elDatas[key];
h += obj['data-height'];
}
this.options.bodyHeight = h;
$('body').height(h);
},
setLinks: function(){
var self = this;
this.$li.each(function() {
var id = $(this).attr('id') || 0;
self.options.linksArray.push(id);
});
},
setHash: function(hash){
// "HARD FIX"
el = $('[href=#'+hash+']');
el.parent().siblings('li').removeClass('active');
el.parent().addClass('active');
if(history.pushState) {
history.pushState(null, null, '#'+hash);
}
else {
location.hash = hash;
}
},
setCache: function(){
var self = this;
self.$current = self.$element.find('.current');
self.$fixed = self.$current.find('.fixed');
self.$fixedLength = self.$fixed.length;
self.$step = self.$current.find('.step');
self.$stepLength = self.$step.length;
self.currentIndex = self.$current.index();
self.currentP = self.$elDatas[self.currentIndex]['data-position'];
self.currentHeight = self.$elDatas[self.currentIndex]['data-height'];
self.parallaxBg = self.$current.attr('data-parallax-background');
self.$fade = self.$current.find('[data-fade]');
self.$slowScroll = self.$current.find('[data-slow-scroll]');
},
// Utils
isHashIsOnList: function(hash){
var self = this;
$.each(self.options.linksArray, function(i,val){
if(val === hash){
self.scrollToPosition(hash);
return false;
}
});
},
readyElement: function(el,callback){
var interval = setInterval(function(){
if(el.length){
callback(el.length);
clearInterval(interval);
}
},60);
},
imageLoaded: function(callback){
var self = this,
elems = self.$element.find('img'),
len = elems.length,
blank = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
elems.bind('load.imgloaded',function(){
if (--len <= 0 && this.src !== blank || $(this).not(':visible')){
elems.unbind('load.imgloaded');
callback.call(elems,this);
}
}).each(function(){
if (this.complete || this.complete === undefined){
var src = this.src;
this.src = blank;
this.src = src;
}
});
}
};
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName, new Plugin( this, options ));
}
});
};
})( jQuery, window, document );
</script>
First you would have to tell us how you are trying to select text (mouse, keyboard, touchscreen, etc.)
I bet my bitcoins on keyboard (but I don't have any).
Must be one of those
self.$document.on('keydown', function(e){
...
e.preventDefault();
which don't even document which keys these numbers stand for.
It's e.preventDefault() which prevents the default browser action from being performed.
If you're in Chrome devtools, you can use
monitorEvents(window, 'key')
to make sense of these.
Of course this bit may help a bit:
keyCode: 38
keyIdentifier: "Up"
So the code could be written readably by use of keyIdentifier instead of keyCode.
I don't know how compatible that would be across browsers.
Be warned that keydown keyCode values are different from keypress values (which actually insert real characters). keydown key codes will vary between keyboard layouts and locales.
See http://unixpapa.com/js/key.html for disgust and enlightenment, but mostly disgust.
Ok! I'm working on a wordpress site, and everything this javascript add on is supposed to do, it does...But, when I inspect element via safari develop, I notice that it's loading all of my headers scripts,meta,styles etc. into the body as well as the head. I can't figure out why. Here's what the script looks like:
function ft(params) {
var ol= document.addEventListener?"DOMContentLoaded":"load"; //on load event
var navB = params.navB || "reverse slide"; //backbrowser button effect, default empty
var but = params.but || false; //Allow transitions on input type button
var cBa = params.cBa || function() {};
function aDL(url, t, o) { //Ajax Div Load
if (window.XMLHttpRequest) {
r = new XMLHttpRequest();
} else if (window.ActiveXObject) {
r = new ActiveXObject("Microsoft.XMLHTTP");
}
if (r != undefined) {
r.onreadystatechange = function() {Ol(r, t, o);};
r.open("GET", url, true);
r.send("");
}
}
function Ol(r, t, o) { //On load div
if (r.readyState == 4) {
if (r.status == 200 || r.status == 0) {
t.innerHTML = r.responseText;
o();
} else {
t.innerHTML="Error:\n"+ r.status + "\n" +r.statusText;
}
}
}
function DE() //Div Effect
{
var dochtml = document.body.innerHTML;
document.body.innerHTML = "";
var d1 = document.createElement("div");
d1.id = "d1";
d1.style.zIndex = 2;
d1.style.position = "absolute";
d1.style.width = "100%";
d1.style.height = "100%";
d1.style.left = "0px";
d1.style.top = "0px";
document.body.appendChild(d1);
d1.innerHTML = dochtml;
var d2 = document.createElement("div");
d2.id = "d2";
d2.style.zIndex = 1;
d2.style.position = "absolute";
d2.style.width = "100%";
d2.style.height = "100%";
d2.style.left = "0px";
d2.style.top = "0px";
document.body.appendChild(d2);
return {d1: d1, d2: d2 };
}
function timeOuts(e, d1,d2)
{
setTimeout(function() { d1.className = e + " out"; }, 1);
setTimeout(function() { d2.className = e + " in"; }, 1);
setTimeout(function() {
document.body.innerHTML = d2.innerHTML;
cBa();
}, 706);
}
function slideTo(href, effect, pushstate)
{
var d = DE();
var d1 = d.d1;
var d2 = d.d2;
aDL(href, d2,
function() {
if (pushstate && window.history.pushState) window.history.pushState("", "", href);
timeOuts(effect,d1,d2);
}
);
}
function dC(e){ //Detect click event
var o;
var o=e.srcElement || e.target;
var tn = o.tagName.toLowerCase();
if (!but || tn!="input" || o.getAttribute("type")!="button") //if it is not a button
{
//try to find an anchor parent
while (tn!=="a" && tn!=="body")
{
o = o.parentNode;
tn = o.tagName.toLowerCase();
}
if (tn==="body") return;
}
var t = o.getAttribute("data-ftrans");
if (t)
{
e.preventDefault();
var hr = o.getAttribute("href") || o.getAttribute("data-href");
if (hr) slideTo(hr, t, true);
}
}
function aE(ev, el, f) { //Add event
if (el.addEventListener) // W3C DOM
el.addEventListener(ev,f,false);
else if (el.attachEvent) { // IE DOM
var r = el.attachEvent("on"+ev, f);
return r;
}
}
aE("click", window, dC);
aE(ol, document, //On load
function(ev)
{
aE("popstate", window, function(e) { //function to reload when back button is clicked
slideTo(location.pathname, navB, false);
});
}
);
}
here is the link to the site: http://www.fasw.ws/faswwp/non-jquery-page-transitions-lightweight/
I assume that thats not supposed to happen. So im trying to figure out how to keep it clean, and keep the head files loaded in the head, and only load the page content. I cannot figure this one out, some help from the pros is needed :)
FASW comes with two functions that serves as "hooks" both before and after initializing the component. you can do it like this:
(function inittrans()
{
initComponents();
var params = { /*put your options here*/ };
new ft(params);
})();
function onTransitionFinished()
{
initComponents();
}
function initComponents() {
// here is where you put your "other" javascript codes
}
Notice how your javascript codes are executed after loading your initial page and once again after the transition happened. Anyway, this is how I got the work around on it 'coz javascript codes just won't work as they are loaded by FASW via Ajax on-the-fly.