PopUnder is triggering even if cookie is set - javascript

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

Related

How to create a popunder code or how it works

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

Hyperlink doesn't redirect user with jQuery

When I click the blue text Learn more I want to redirect to Google, however, it just closes the div.
The link is on Line 146 of my Javascript.
Demo
/**
*
* JQUERY EU COOKIE LAW POPUPS
* version 1.0.0
*
* Code on Github:
* https://github.com/wimagguc/jquery-eu-cookie-law-popup
*
* To see a live demo, go to:
* http://www.wimagguc.com/2015/04/jquery-eu-cookie-law-popup/
*
* by Richard Dancsi
* http://www.wimagguc.com/
*
*/
(function($) {
// for ie9 doesn't support debug console >>>
if (!window.console) window.console = {};
if (!window.console.log) window.console.log = function () { };
// ^^^
var EuCookieLawPopup = (function() {
var _self = this;
///////////////////////////////////////////////////////////////////////////////////////////////
// PARAMETERS (MODIFY THIS PART) //////////////////////////////////////////////////////////////
_self.params = {
cookiePolicyUrl : '/cookie-privacy-policy/',
popupPosition : 'bottom',
colorStyle : 'default',
compactStyle : false,
popupTitle : 'This site uses cookies to store information on your computer',
popupText : '',
buttonContinueTitle : 'Learn more',
buttonLearnmoreTitle : 'Learn more',
buttonLearnmoreOpenInNewWindow : true,
agreementExpiresInDays : 30,
autoAcceptCookiePolicy : true,
htmlMarkup : null
};
///////////////////////////////////////////////////////////////////////////////////////////////
// VARIABLES USED BY THE FUNCTION (DON'T MODIFY THIS PART) ////////////////////////////////////
_self.vars = {
INITIALISED : false,
HTML_MARKUP : null,
COOKIE_NAME : 'EU_COOKIE_LAW_CONSENT'
};
///////////////////////////////////////////////////////////////////////////////////////////////
// PRIVATE FUNCTIONS FOR MANIPULATING DATA ////////////////////////////////////////////////////
// Overwrite default parameters if any of those is present
var parseParameters = function(object, markup, settings) {
if (object) {
var className = $(object).attr('class') ? $(object).attr('class') : '';
if (className.indexOf('eupopup-top') > -1) {
_self.params.popupPosition = 'top';
}
else if (className.indexOf('eupopup-fixedtop') > -1) {
_self.params.popupPosition = 'fixedtop';
}
else if (className.indexOf('eupopup-bottomright') > -1) {
_self.params.popupPosition = 'bottomright';
}
else if (className.indexOf('eupopup-bottomleft') > -1) {
_self.params.popupPosition = 'bottomleft';
}
else if (className.indexOf('eupopup-bottom') > -1) {
_self.params.popupPosition = 'bottom';
}
else if (className.indexOf('eupopup-block') > -1) {
_self.params.popupPosition = 'block';
}
if (className.indexOf('eupopup-color-default') > -1) {
_self.params.colorStyle = 'default';
}
else if (className.indexOf('eupopup-color-inverse') > -1) {
_self.params.colorStyle = 'inverse';
}
if (className.indexOf('eupopup-style-compact') > -1) {
_self.params.compactStyle = true;
}
}
if (markup) {
_self.params.htmlMarkup = markup;
}
if (settings) {
if (typeof settings.cookiePolicyUrl !== 'undefined') {
_self.params.cookiePolicyUrl = settings.cookiePolicyUrl;
}
if (typeof settings.popupPosition !== 'undefined') {
_self.params.popupPosition = settings.popupPosition;
}
if (typeof settings.colorStyle !== 'undefined') {
_self.params.colorStyle = settings.colorStyle;
}
if (typeof settings.popupTitle !== 'undefined') {
_self.params.popupTitle = settings.popupTitle;
}
if (typeof settings.popupText !== 'undefined') {
_self.params.popupText = settings.popupText;
}
if (typeof settings.buttonContinueTitle !== 'undefined') {
_self.params.buttonContinueTitle = settings.buttonContinueTitle;
}
if (typeof settings.buttonLearnmoreTitle !== 'undefined') {
_self.params.buttonLearnmoreTitle = settings.buttonLearnmoreTitle;
}
if (typeof settings.buttonLearnmoreOpenInNewWindow !== 'undefined') {
_self.params.buttonLearnmoreOpenInNewWindow = settings.buttonLearnmoreOpenInNewWindow;
}
if (typeof settings.agreementExpiresInDays !== 'undefined') {
_self.params.agreementExpiresInDays = settings.agreementExpiresInDays;
}
if (typeof settings.autoAcceptCookiePolicy !== 'undefined') {
_self.params.autoAcceptCookiePolicy = settings.autoAcceptCookiePolicy;
}
if (typeof settings.htmlMarkup !== 'undefined') {
_self.params.htmlMarkup = settings.htmlMarkup;
}
}
};
var createHtmlMarkup = function() {
if (_self.params.htmlMarkup) {
return _self.params.htmlMarkup;
}
var html =
'<div class="eupopup-container' +
' eupopup-container-' + _self.params.popupPosition +
(_self.params.compactStyle ? ' eupopup-style-compact' : '') +
' eupopup-color-' + _self.params.colorStyle + '">' +
'<div class="eupopup-head">' + _self.params.popupTitle + '</div>' +
'<div class="eupopup-body">' + _self.params.popupText + '</div>' +
'<div class="eupopup-buttons">' +
'' + _self.params.buttonContinueTitle + '' +
'<a href="' + _self.params.cookiePolicyUrl + '"' +
(_self.params.buttonLearnmoreOpenInNewWindow ? ' target=_blank ' : '') +
' class="eupopup-button eupopup-button_2">' + _self.params.buttonLearnmoreTitle + '</a>' +
'<div class="clearfix"></div>' +
'</div>' +
'<img src="/images/icons/svg/close.svg">' +
'</div>';
return html;
};
// Storing the consent in a cookie
var setUserAcceptsCookies = function(consent) {
var d = new Date();
var expiresInDays = _self.params.agreementExpiresInDays * 24 * 60 * 60 * 1000;
d.setTime( d.getTime() + expiresInDays );
var expires = "expires=" + d.toGMTString();
document.cookie = _self.vars.COOKIE_NAME + '=' + consent + "; " + expires + ";path=/";
$(document).trigger("user_cookie_consent_changed", {'consent' : consent});
};
// Let's see if we have a consent cookie already
var userAlreadyAcceptedCookies = function() {
var userAcceptedCookies = false;
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
var c = cookies[i].trim();
if (c.indexOf(_self.vars.COOKIE_NAME) == 0) {
userAcceptedCookies = c.substring(_self.vars.COOKIE_NAME.length + 1, c.length);
}
}
return userAcceptedCookies;
};
var hideContainer = function() {
// $('.eupopup-container').slideUp(200);
$('.eupopup-container').animate({
opacity: 0,
height: 0
}, 200, function() {
$('.eupopup-container').hide(0);
});
};
///////////////////////////////////////////////////////////////////////////////////////////////
// PUBLIC FUNCTIONS //////////////////////////////////////////////////////////////////////////
var publicfunc = {
// INITIALIZE EU COOKIE LAW POPUP /////////////////////////////////////////////////////////
init : function(settings) {
parseParameters(
$(".eupopup").first(),
$(".eupopup-markup").html(),
settings);
// No need to display this if user already accepted the policy
if (userAlreadyAcceptedCookies()) {
return;
}
// We should initialise only once
if (_self.vars.INITIALISED) {
return;
}
_self.vars.INITIALISED = true;
// Markup and event listeners >>>
_self.vars.HTML_MARKUP = createHtmlMarkup();
if ($('.eupopup-block').length > 0) {
$('.eupopup-block').append(_self.vars.HTML_MARKUP);
} else {
$('BODY').append(_self.vars.HTML_MARKUP);
}
$('.eupopup-button_1').click(function() {
setUserAcceptsCookies(true);
hideContainer();
return false;
});
$('.eupopup-closebutton').click(function() {
setUserAcceptsCookies(true);
hideContainer();
return false;
});
// ^^^ Markup and event listeners
// Ready to start!
$('.eupopup-container').show();
// In case it's alright to just display the message once
if (_self.params.autoAcceptCookiePolicy) {
setUserAcceptsCookies(true);
}
}
};
return publicfunc;
});
$(document).ready( function() {
if ($(".eupopup").length > 0) {
(new EuCookieLawPopup()).init({
'info' : 'YOU_CAN_ADD_MORE_SETTINGS_HERE',
'popupTitle' : 'This site uses cookies to store information on your computer',
'popupText' : '',
'buttonLearnmoreTitle' : ''
});
}
});
}(jQuery));
.eupopup-container {
position: relative;
z-index: 190;
top: 0;
width: 100%;
height: 64px;
background: #4a4a4a;
text-align: center;
padding-top: 5px;
display: block;
}
.nav {
position:fixed;
top:0;
margin-top: 64px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="container">
<div class="nav">
<img src="http://placehold.it/1200x300">
</div>
</div>
you need to do two things
1) Comment out line number 228
$('.eupopup-button_1').click(function() {
setUserAcceptsCookies(true);
hideContainer();
//return false;
});
2) Ensure that the link that you are pointing to doesn't have X-Frame options set otherwise it will give the error like it is giving now
Refused to display
'https://www.google.co.in/?gfe_rd=cr&ei=Gb9nVtCHHu_I8AeltLGYBQ&gws_rd=ssl'
in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.
$('.eupopup-button_1').click(function() {
setUserAcceptsCookies(true);
hideContainer();
return false;
});
This return false; should be the reason, please remove it.

jQuery Taggd plugin (Edit mode) get back value in input fields

Im using the jQuery taggd plugin, so far so good.
I modified a small bit, im using it in edit mode. So when a user types in a value in the textbox it checks if it is a URL or or string, if its a URL it runs a ajax call to a php file which scrapes some data from the url. Url title, description and image. I have created 3 hidden input fields which get populated once the ajax call is finished. Once you click on the SAVE icon it saves the data to the DOM. But i want it to display again once a user clicks on the tag again. At the moment its only displaying the value of the standard input field.
This is the taggd plugin with some small modifications:
/*!
* jQuery Taggd
* A helpful plugin that helps you adding 'tags' on images.
*
* License: MIT
*/
(function($) {
'use strict';
var defaults = {
edit: false,
align: {
x: 'center',
y: 'center'
},
handlers: {},
offset: {
left: 0,
top: 0
},
strings: {
save: '✓',
delete: '×'
}
};
var methods = {
show: function() {
var $this = $(this),
$label = $this.next();
$this.addClass('active');
$label.addClass('show').find('input').focus();
},
hide: function() {
var $this = $(this);
$this.removeClass('active');
$this.next().removeClass('show');
},
toggle: function() {
var $hover = $(this).next();
if($hover.hasClass('show')) {
methods.hide.call(this);
} else {
methods.show.call(this);
}
}
};
/****************************************************************
* TAGGD
****************************************************************/
var Taggd = function(element, options, data) {
var _this = this;
if(options.edit) {
options.handlers = {
click: function() {
_this.hide();
methods.show.call(this);
}
};
}
this.element = $(element);
this.options = $.extend(true, {}, defaults, options);
this.data = data;
this.initialized = false;
if(!this.element.height() || !this.element.width()) {
this.element.on('load', _this.initialize.bind(this));
} else this.initialize();
};
/****************************************************************
* INITIALISATION
****************************************************************/
Taggd.prototype.initialize = function() {
var _this = this;
this.initialized = true;
this.initWrapper();
this.addDOM();
if(this.options.edit) {
this.element.on('click', function(e) {
var poffset = $(this).parent().offset(),
x = (e.pageX - poffset.left) / _this.element.width(),
y = (e.pageY - poffset.top) / _this.element.height();
_this.addData({
x: x,
y: y,
text: '',
url: '',
url_title: '',
url_description: '',
url_image: ''
});
_this.show(_this.data.length - 1);
});
}
$(window).resize(function() {
_this.updateDOM();
});
};
Taggd.prototype.initWrapper = function() {
var wrapper = $('<div class="taggd-wrapper" />');
this.element.wrap(wrapper);
this.wrapper = this.element.parent('.taggd-wrapper');
};
Taggd.prototype.alterDOM = function() {
var _this = this;
this.wrapper.find('.taggd-item-hover').each(function() {
var $e = $(this),
$input = $('<input id="url" type="text" size="16" />')
.val($e.text()),
$url_title = $('<input type="text" id="url_title" class="url_title" />'),
$button_ok = $('<button />')
.html(_this.options.strings.save),
$url_description = $('<input type="text" class="url_description" id="url_description" />'),
$url_image = $('<input type="text" class="url_img" id="url_img" />'),
$url_preview = $('<div id="content"></div>'),
$button_delete = $('<button />')
.html(_this.options.strings.delete);
$button_delete.on('click', function() {
var x = $e.attr('data-x'),
y = $e.attr('data-y');
_this.data = $.grep(_this.data, function(v) {
return v.x != x || v.y != y;
});
_this.addDOM();
_this.element.triggerHandler('change');
});
// Typing URL timer
var typingTimer;
var doneTypingInterval = 2000;
$input.keyup(function() {
clearTimeout(typingTimer);
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
$input.keydown(function() {
clearTimeout(typingTimer);
$url_preview.empty();
});
// Process URL scrape request
function doneTyping() {
var getUrl = $input.val();
if(isURL(getUrl)) {
console.log('Typed text is a URL');
$url_preview.append('<img src="images/loader.gif" style="width:24px; padding-top:10px; height:24px; margin:0 auto;">');
// Get url data by ajax
$.post('ajax/Crawl.php', {
'url' : getUrl
},function(data) {
$url_preview.empty();
var content = '<h3 class="url_title">' + data.title + '</h3><p class="url_description" style="font-size:11px;">' + data.description + '</p><img class="url_image" src="' + data.images + '" style="width:100%; height:auto;">';
$url_preview.append(content);
$url_title.val(data.title);
$url_description.val(data.description);
$url_image.val(data.images);
console.log(content);
}, 'json');
} else {
console.log('Typed text is a string');
}
};
function isURL(url) {
var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
'((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
'(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
'(\\#[-a-z\\d_]*)?$','i'); // fragment locator
if(!pattern.test(url)) {
return false;
} else {
if(!/^(https?|ftp):\/\//i.test(url)) {
url = 'http://'+url;
$input.val(url);
}
return true;
}
};
$button_ok.on('click', function() {
var x = $e.attr('data-x'),
y = $e.attr('data-y'),
item = $.grep(_this.data, function(v) {
return v.x == x && v.y == y;
}).pop();
if(item) item.text = $input.val();
if(isURL(item.text)) {
if(item) item.url = item.text;
} else {
if(item) item.url = null;
}
if(item) item.url_title = $url_title.val();
if(item) item.url_description = $url_description.val();
if(item) item.url_image = $url_image.val();
_this.addDOM();
_this.element.triggerHandler('change');
//_this.hide();
});
/*$input.on('change', function() {
var x = $e.attr('data-x'),
y = $e.attr('data-y'),
item = $.grep(_this.data, function(v) {
return v.x == x && v.y == y;
}).pop();
if(item) item.text = $input.val();
_this.addDOM();
_this.element.triggerHandler('change');
});
*/
$e.empty().append($input, $button_ok, $button_delete, $url_preview, $url_title, $url_description, $url_image);
});
_this.updateDOM();
};
/****************************************************************
* DATA MANAGEMENT
****************************************************************/
Taggd.prototype.addData = function(data) {
if($.isArray(data)) {
this.data = $.merge(this.data, data);
} else {
this.data.push(data);
}
if(this.initialized) {
this.addDOM();
this.element.triggerHandler('change');
}
};
Taggd.prototype.setData = function(data) {
this.data = data;
if(this.initialized) {
this.addDOM();
}
};
Taggd.prototype.clear = function() {
if(!this.initialized) return;
this.wrapper.find('.taggd-item, .taggd-item-hover').remove();
};
/****************************************************************
* EVENTS
****************************************************************/
Taggd.prototype.on = function(event, handler) {
if(
typeof event !== 'string' ||
typeof handler !== 'function'
) return;
this.element.on(event, handler);
};
/****************************************************************
* TAGS MANAGEMENT
****************************************************************/
Taggd.prototype.iterateTags = function(a, yep) {
var func;
if($.isNumeric(a)) {
func = function(i, e) { return a === i; };
} else if(typeof a === 'string') {
func = function(i, e) { return $(e).is(a); }
} else if($.isArray(a)) {
func = function(i, e) {
var $e = $(e);
var result = false;
$.each(a, function(ai, ae) {
if(
i === ai ||
e === ae ||
$e.is(ae)
) {
result = true;
return false;
}
});
return result;
}
} else if(typeof a === 'object') {
func = function(i, e) {
var $e = $(e);
return $e.is(a);
};
} else if($.isFunction(a)) {
func = a;
} else if(!a) {
func = function() { return true; }
} else return this;
this.wrapper.find('.taggd-item').each(function(i, e) {
if(typeof yep === 'function' && func.call(this, i, e)) {
yep.call(this, i, e);
}
});
return this;
};
Taggd.prototype.show = function(a) {
return this.iterateTags(a, methods.show);
};
Taggd.prototype.hide = function(a) {
return this.iterateTags(a, methods.hide);
};
Taggd.prototype.toggle = function(a) {
return this.iterateTags(a, methods.toggle);
};
/****************************************************************
* CLEANING UP
****************************************************************/
Taggd.prototype.dispose = function() {
this.clear();
this.element.unwrap(this.wrapper);
};
/****************************************************************
* SEMI-PRIVATE
****************************************************************/
Taggd.prototype.addDOM = function() {
var _this = this;
this.clear();
this.element.css({ height: 'auto', width: 'auto' });
var height = this.element.height();
var width = this.element.width();
$.each(this.data, function(i, v) {
var $item = $('<span />');
var $hover;
if(
v.x > 1 && v.x % 1 === 0 &&
v.y > 1 && v.y % 1 === 0
) {
v.x = v.x / width;
v.y = v.y / height;
}
if(typeof v.attributes === 'object') {
$item.attr(v.attributes);
}
$item.attr({
'data-x': v.x,
'data-y': v.y
});
$item.css('position', 'absolute');
$item.addClass('taggd-item');
_this.wrapper.append($item);
if(typeof v.text === 'string' && (v.text.length > 0 || _this.options.edit)) {
$hover = $('<span class="taggd-item-hover" style="position: absolute;" />').html(v.text);
$hover.attr({
'data-x': v.x,
'data-y': v.y
});
_this.wrapper.append($hover);
}
if(typeof _this.options.handlers === 'object') {
$.each(_this.options.handlers, function(event, func) {
var handler;
if(typeof func === 'string' && methods[func]) {
handler = methods[func];
} else if(typeof func === 'function') {
handler = func;
}
$item.on(event, function(e) {
if(!handler) return;
handler.call($item, e, _this.data[i]);
});
});
}
});
this.element.removeAttr('style');
if(this.options.edit) {
this.alterDOM();
}
this.updateDOM();
};
Taggd.prototype.updateDOM = function() {
var _this = this;
this.wrapper.removeAttr('style').css({
height: this.element.height(),
width: this.element.width()
});
this.wrapper.find('span').each(function(i, e) {
var $el = $(e);
var left = $el.attr('data-x') * _this.element.width();
var top = $el.attr('data-y') * _this.element.height();
if($el.hasClass('taggd-item')) {
$el.css({
left: left - $el.outerWidth(true) / 2,
top: top - $el.outerHeight(true) / 2
});
} else if($el.hasClass('taggd-item-hover')) {
if(_this.options.align.x === 'center') {
left -= $el.outerWidth(true) / 2;
} else if(_this.options.align.x === 'right') {
left -= $el.outerWidth(true);
}
if(_this.options.align.y === 'center') {
top -= $el.outerHeight(true) / 2;
} else if(_this.options.align.y === 'bottom') {
top -= $el.outerHeight(true);
}
$el.attr('data-align', $el.outerWidth(true));
$el.css({
left: left + _this.options.offset.left,
top: top + _this.options.offset.top
});
}
});
};
/****************************************************************
* JQUERY LINK
****************************************************************/
$.fn.taggd = function(options, data) {
return new Taggd(this, options, data);
};
})(jQuery);
I thought this would do what i want, since it works with the standard text input box, using .val($e.text()), works fine but as soon as i do the same to the url_title box, for example .val($e.url_title()), i get the error below.
$input = $('<input id="url" type="text" size="16" />')
.val($e.text()),
$url_title = $('<input type="text" id="url_title" class="url_title" />'),
$button_ok = $('<button />')
.html(_this.options.strings.save),
$url_description = $('<input type="text" class="url_description" id="url_description" />'),
$url_image = $('<input type="text" class="url_img" id="url_img" />'),
$url_preview = $('<div id="content"></div>'),
$button_delete = $('<button />')
.html(_this.options.strings.delete);
But if for example i change the $url_title to
$url_title = $('<input type="text" id="url_title" class="url_title" />').val($e.url_title()),
I get a error back in the console:
Uncaught TypeError: undefined is not a function
This is the init code on the main page:
$(document).ready(function() {
var options = {
edit: true,
align: {
y: 'top'
},
offset: {
top: 15
},
handlers: {
//mouseenter: 'show',
click: 'toggle'
}
};
/*var data = [
{ x: 0.22870478413068845, y: 0.41821946169772256, text: 'Eye' },
{ x: 0.51, y: 0.5, text: 'Bird' },
{ x: 0.40, y: 0.3, text: 'Water, obviously' }
];*/
var data = [];
var taggd = $('.taggd').taggd( options, data );
taggd.on('change', function() {
console.log(taggd.data);
});
});
In the console log it logs the values fine:
[Object]0: Objecttext: "http://stackoverflow.com"url: "http://stackoverflow.com"url_description: "Q&A for professional and enthusiast programmers"url_image: "http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon#2.png?v=ea71a5211a91&a"url_title: "Stack Overflow"x: 0.41141586360266863y: 0.19444444444444445
I hope someone can shine a light on it and point me in the right direction of what i'm doing wrong.
To simplify it, i want to be able to have a title input and a description input for my tags, how would i achieve this?
Thank you.
I suspect $e.url_title() is causing the error, as far as I know, url_title() isn't a method you can call on jQuery instances.
Presumably you meant to access a variable instead.
I couldn’t find an issue in your scripts, other than the undefined function call, so I basically rewrote the whole thing myself, which seems to work: http://jsbin.com/nexujuhefo/2/edit?js,console,output
I think the problem is Taggd weird logic ;)
Fields now remember data: http://jsbin.com/hosipiyuqa/1/edit?js,console,output

Pop-Under : only one time per session and Onload

I'm searching on google but i can't find a good solution. I'm searching a pop under script which open a new url window but only once time per seesion. i found a lot of script but the open a new window just for the onclick ...
<script>
function jsPopunder(sUrl, sConfig) {
sConfig = (sConfig || {});
var sName = (sConfig.name || Math.floor((Math.random()*1000)+1));
var sWidth = (sConfig.width || window.innerWidth);
var sHeight = (sConfig.height || window.innerHeight);
var sPosX = (typeof(sConfig.left)!= 'undefined') ? sConfig.left.toString() : window.screenX;
var sPosY = (typeof(sConfig.top) != 'undefined') ? sConfig.top.toString() : window.screenY;
/* capping */
var sWait = (sConfig.wait || 3600); sWait = (sWait*1000);
var sCap = (sConfig.cap || 2);
/* cookie stuff */
var popsToday = 0;
var cookie = (sConfig.cookie || '__.popunder');
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 {
popsToday = Math.floor(document.cookie.split(cookie+'Cap=')[1].split(';')[0]);
} catch(err){}
return (sCap<=popsToday || document.cookie.indexOf(cookie+'=') !== -1);
}
function openIt(sUrl, sName, sOptions) {
if (isCapped()) return;
var _parent = (top != self && typeof(top.document.location.toString())==='string') ? top : self;
var popunder = _parent.window.open(sUrl, sName, sOptions);
if (popunder) {
popunder.blur();
setTimeout(function() {
document.onclick = function() { return; };
document.onmousedown = function() { return; };
}, 1000);
var now = new Date();
document.cookie = cookie+'=1;expires='+ new Date(now.setTime(now.getTime()+sWait)).toGMTString() +';path=/';
now = new Date();
document.cookie = cookie+'Cap='+(popsToday+1)+';expires='+ new Date(now.setTime(now.getTime()+(84600*1000))).toGMTString() +';path=/';
window.focus();
try{ opener.window.focus(); }catch(err){}
}
return popunder;
}
function popunder(sUrl, sName, sWidth, sHeight, sPosX, sPosY) {
if (isCapped()) return;
var sOptions = 'toolbar=no,scrollbars=yes,location=yes,statusbar=yes,menubar=no,resizable=1,width='+sWidth.toString()+',height='+sHeight.toString()+',screenX='+sPosX+',screenY='+sPosY;
if (browser.webkit) {
document.onmousedown = function () {
openIt(sUrl, sName, sOptions);
};
document.onbeforeunload = function() {
window.open("about:blank").close();
};
} else {
document.onbeforeunload = function() {
var popunder = openIt(sUrl, sName, sOptions);
if (popunder) {
if (!browser.msie) {
popunder.params = { url: sUrl };
(function(e) {
with (e) {
if (typeof window.mozPaintCount != 'undefined' || typeof navigator.webkitGetUserMedia === "function") {
try {
var poltergeist = document.createElement('a');
poltergeist.href = "javascript:window.open('about:blank').close();document.body.removeChild(poltergeist)";
document.body.appendChild(poltergeist).click();
}catch(err){}
}
}
})(popunder);
}
}
};
}
}
// abort?
if (isCapped()) {
return;
} else {
popunder(sUrl, sName, sWidth, sHeight, sPosX, sPosY);
}
}
jsPopunder('http://www.google.com');
</script>
<?php mysql_close($base);?>
Can you help me ?
I managed to modify one of the code samples I found online (similar to yours) to open a Pop-Under on document load, automatically. Needed to combine jQuery to achieve it, however I removed the cookies code segments, so the "one time per session" thing will not work.
Here's the code:
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 doPopunder(pUrl, pName, pWidth, pHeight, pPosX, pPosY) {
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 ).ready(function (e) {
window["pop_clicked"] = 1;
mypopunder = _parent["window"]["open"](pUrl, pName, sOptions);
if (mypopunder) {
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;
};
doPopunder(pUrl, pName, pWidth, pHeight, pPosX, pPosY);}
Notice how I used jQuery in "$( document ).ready(function (e) {...}". This triggers the event on document load.
Then just add "makePopunder("https://www.myurl.com/");" inside script tags in your html document's body.
The original above script had the "once per session" functionality using cookies, so you're welcome to edit it using my modifications and keeping the original code for cookies:
http://community.sitepoint.com/t/popunder-that-works-well-for-all-browser/29741
Works in all browsers (desktop & mobile): Firefox, Chrome, Safari etc.

Jquery Auto-Complete Limited Search Results (JSON)

I'm using the FoxyComplete plugin with Jquery Auto-Complete to do a simple search. Everything is setup and working great but I'm finding the search results extremely limiting.
I use a big JSON file for all of my data and the problem I'm having is in the following case: Let's assume that my JSON file has the following description:
{
"title": "Brand new black car"
},
If a user searches "black car", he or she will get the result perfectly and the search is great. BUT, if a user search "car new", nothing comes up even though both keywords are in my JSON file.
Any help would be great. I poured through the Jquery AutoComplete docs and couldn't find a solution either. My Jquery autocomplete js is below:
;
(function ($) {
$.fn.extend({
autocomplete: function (urlOrData, options) {
var isUrl = typeof urlOrData == "string";
options = $.extend({}, $.Autocompleter.defaults, {
url: isUrl ? urlOrData : null,
data: isUrl ? null : urlOrData,
delay: isUrl ? $.Autocompleter.defaults.delay : 10,
max: options && !options.scroll ? 10 : 150
}, options);
// if highlight is set to false, replace it with a do-nothing function
options.highlight = options.highlight || function (value) {
return value;
};
// if the formatMatch option is not specified, then use formatItem for backwards compatibility
options.formatMatch = options.formatMatch || options.formatItem;
return this.each(function () {
new $.Autocompleter(this, options);
});
},
result: function (handler) {
return this.bind("result", handler);
},
search: function (handler) {
return this.trigger("search", [handler]);
},
flushCache: function () {
return this.trigger("flushCache");
},
setOptions: function (options) {
return this.trigger("setOptions", [options]);
},
unautocomplete: function () {
return this.trigger("unautocomplete");
}
});
$.Autocompleter = function (input, options) {
var KEY = {
UP: 38,
DOWN: 40,
DEL: 46,
TAB: 9,
RETURN: 13,
ESC: 27,
COMMA: 188,
PAGEUP: 33,
PAGEDOWN: 34,
BACKSPACE: 8
};
// Create $ object for input element
var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);
var timeout;
var previousValue = "";
var cache = $.Autocompleter.Cache(options);
var hasFocus = 0;
var lastKeyPressCode;
var config = {
mouseDownOnSelect: false
};
var select = $.Autocompleter.Select(options, input, selectCurrent, config);
var blockSubmit;
// prevent form submit in opera when selecting with return key
$.browser.opera && $(input.form).bind("submit.autocomplete", function () {
if (blockSubmit) {
blockSubmit = false;
return false;
}
});
// only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
$input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function (event) {
// a keypress means the input has focus
// avoids issue where input had focus before the autocomplete was applied
hasFocus = 1;
// track last key pressed
lastKeyPressCode = event.keyCode;
switch (event.keyCode) {
case KEY.UP:
event.preventDefault();
if (select.visible()) {
select.prev();
} else {
onChange(0, true);
}
break;
case KEY.DOWN:
event.preventDefault();
if (select.visible()) {
select.next();
} else {
onChange(0, true);
}
break;
case KEY.PAGEUP:
event.preventDefault();
if (select.visible()) {
select.pageUp();
} else {
onChange(0, true);
}
break;
case KEY.PAGEDOWN:
event.preventDefault();
if (select.visible()) {
select.pageDown();
} else {
onChange(0, true);
}
break;
// matches also semicolon
case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
case KEY.TAB:
case KEY.RETURN:
if (selectCurrent()) {
// stop default to prevent a form submit, Opera needs special handling
event.preventDefault();
blockSubmit = true;
return false;
}
break;
case KEY.ESC:
select.hide();
break;
default:
clearTimeout(timeout);
timeout = setTimeout(onChange, options.delay);
break;
}
}).focus(function () {
// track whether the field has focus, we shouldn't process any
// results if the field no longer has focus
hasFocus++;
}).blur(function () {
hasFocus = 0;
if (!config.mouseDownOnSelect) {
hideResults();
}
}).click(function () {
// show select when clicking in a focused field
if (hasFocus++ > 1 && !select.visible()) {
onChange(0, true);
}
}).bind("search", function () {
// TODO why not just specifying both arguments?
var fn = (arguments.length > 1) ? arguments[1] : null;
function findValueCallback(q, data) {
var result;
if (data && data.length) {
for (var i = 0; i < data.length; i++) {
if (data[i].result.toLowerCase() == q.toLowerCase()) {
result = data[i];
break;
}
}
}
if (typeof fn == "function") fn(result);
else $input.trigger("result", result && [result.data, result.value]);
}
$.each(trimWords($input.val()), function (i, value) {
request(value, findValueCallback, findValueCallback);
});
}).bind("flushCache", function () {
cache.flush();
}).bind("setOptions", function () {
$.extend(options, arguments[1]);
// if we've updated the data, repopulate
if ("data" in arguments[1]) cache.populate();
}).bind("unautocomplete", function () {
select.unbind();
$input.unbind();
$(input.form).unbind(".autocomplete");
});
function selectCurrent() {
var selected = select.selected();
if (!selected) return false;
var v = selected.result;
previousValue = v;
if (options.multiple) {
var words = trimWords($input.val());
if (words.length > 1) {
var seperator = options.multipleSeparator.length;
var cursorAt = $(input).selection().start;
var wordAt, progress = 0;
$.each(words, function (i, word) {
progress += word.length;
if (cursorAt <= progress) {
wordAt = i;
return false;
}
progress += seperator;
});
words[wordAt] = v;
// TODO this should set the cursor to the right position, but it gets overriden somewhere
//$.Autocompleter.Selection(input, progress + seperator, progress + seperator);
v = words.join(options.multipleSeparator);
}
v += options.multipleSeparator;
}
$input.val(v);
hideResultsNow();
$input.trigger("result", [selected.data, selected.value]);
return true;
}
function onChange(crap, skipPrevCheck) {
if (lastKeyPressCode == KEY.DEL) {
select.hide();
return;
}
var currentValue = $input.val();
if (!skipPrevCheck && currentValue == previousValue) return;
previousValue = currentValue;
currentValue = lastWord(currentValue);
if (currentValue.length >= options.minChars) {
$input.addClass(options.loadingClass);
if (!options.matchCase) currentValue = currentValue.toLowerCase();
request(currentValue, receiveData, hideResultsNow);
} else {
stopLoading();
select.hide();
}
};
function trimWords(value) {
if (!value) return [""];
if (!options.multiple) return [$.trim(value)];
return $.map(value.split(options.multipleSeparator), function (word) {
return $.trim(value).length ? $.trim(word) : null;
});
}
function lastWord(value) {
if (!options.multiple) return value;
var words = trimWords(value);
if (words.length == 1) return words[0];
var cursorAt = $(input).selection().start;
if (cursorAt == value.length) {
words = trimWords(value)
} else {
words = trimWords(value.replace(value.substring(cursorAt), ""));
}
return words[words.length - 1];
}
// fills in the input box w/the first match (assumed to be the best match)
// q: the term entered
// sValue: the first matching result
function autoFill(q, sValue) {
// autofill in the complete box w/the first match as long as the user hasn't entered in more data
// if the last user key pressed was backspace, don't autofill
if (options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE) {
// fill in the value (keep the case the user has typed)
$input.val($input.val() + sValue.substring(lastWord(previousValue).length));
// select the portion of the value not typed by the user (so the next character will erase)
$(input).selection(previousValue.length, previousValue.length + sValue.length);
}
};
function hideResults() {
clearTimeout(timeout);
timeout = setTimeout(hideResultsNow, 200);
};
function hideResultsNow() {
var wasVisible = select.visible();
select.hide();
clearTimeout(timeout);
stopLoading();
if (options.mustMatch) {
// call search and run callback
$input.search(
function (result) {
// if no value found, clear the input box
if (!result) {
if (options.multiple) {
var words = trimWords($input.val()).slice(0, - 1);
$input.val(words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : ""));
} else {
$input.val("");
$input.trigger("result", null);
}
}
});
}
};
function receiveData(q, data) {
if (data && data.length && hasFocus) {
stopLoading();
select.display(data, q);
autoFill(q, data[0].value);
select.show();
} else {
hideResultsNow();
}
};
function request(term, success, failure) {
if (!options.matchCase) term = term.toLowerCase();
var data = cache.load(term);
// recieve the cached data
if (data && data.length) {
success(term, data);
// if an AJAX url has been supplied, try loading the data now
} else if ((typeof options.url == "string") && (options.url.length > 0)) {
var extraParams = {
timestamp: +new Date()
};
$.each(options.extraParams, function (key, param) {
extraParams[key] = typeof param == "function" ? param() : param;
});
$.ajax({
// try to leverage ajaxQueue plugin to abort previous requests
mode: "abort",
// limit abortion to this input
port: "autocomplete" + input.name,
dataType: options.dataType,
url: options.url,
data: $.extend({
q: lastWord(term),
limit: options.max
}, extraParams),
success: function (data) {
var parsed = options.parse && options.parse(data) || parse(data);
cache.add(term, parsed);
success(term, parsed);
}
});
} else {
// if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
select.emptyList();
failure(term);
}
};
function parse(data) {
var parsed = [];
var rows = data.split("\n");
for (var i = 0; i < rows.length; i++) {
var row = $.trim(rows[i]);
if (row) {
row = row.split("|");
parsed[parsed.length] = {
data: row,
value: row[0],
result: options.formatResult && options.formatResult(row, row[0]) || row[0]
};
}
}
return parsed;
};
function stopLoading() {
$input.removeClass(options.loadingClass);
};
};
$.Autocompleter.defaults = {
inputClass: "ac_input",
resultsClass: "ac_results",
loadingClass: "ac_loading",
minChars: 1,
delay: 400,
matchCase: false,
matchSubset: true,
matchContains: false,
cacheLength: 10,
max: 100,
mustMatch: false,
extraParams: {},
selectFirst: true,
formatItem: function (row) {
return row[0];
},
formatMatch: null,
autoFill: false,
width: 0,
multiple: false,
multipleSeparator: ", ",
highlight: function (value, term) {
return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
},
scroll: true,
scrollHeight: 180
};
$.Autocompleter.Cache = function (options) {
var data = {};
var length = 0;
function matchSubset(s, sub) {
if (!options.matchCase) s = s.toLowerCase();
var i = s.indexOf(sub);
if (options.matchContains == "word") {
i = s.toLowerCase().search("\\b" + sub.toLowerCase());
}
if (i == -1) return false;
return i == 0 || options.matchContains;
};
function add(q, value) {
if (length > options.cacheLength) {
flush();
}
if (!data[q]) {
length++;
}
data[q] = value;
}
function populate() {
if (!options.data) return false;
// track the matches
var stMatchSets = {},
nullData = 0;
// no url was specified, we need to adjust the cache length to make sure it fits the local data store
if (!options.url) options.cacheLength = 1;
// track all options for minChars = 0
stMatchSets[""] = [];
// loop through the array and create a lookup structure
for (var i = 0, ol = options.data.length; i < ol; i++) {
var rawValue = options.data[i];
// if rawValue is a string, make an array otherwise just reference the array
rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;
var value = options.formatMatch(rawValue, i + 1, options.data.length);
if (value === false) continue;
var firstChar = value.charAt(0).toLowerCase();
// if no lookup array for this character exists, look it up now
if (!stMatchSets[firstChar]) stMatchSets[firstChar] = [];
// if the match is a string
var row = {
value: value,
data: rawValue,
result: options.formatResult && options.formatResult(rawValue) || value
};
// push the current match into the set list
stMatchSets[firstChar].push(row);
// keep track of minChars zero items
if (nullData++ < options.max) {
stMatchSets[""].push(row);
}
};
// add the data items to the cache
$.each(stMatchSets, function (i, value) {
// increase the cache size
options.cacheLength++;
// add to the cache
add(i, value);
});
}
// populate any existing data
setTimeout(populate, 25);
function flush() {
data = {};
length = 0;
}
return {
flush: flush,
add: add,
populate: populate,
load: function (q) {
if (!options.cacheLength || !length) return null;
/*
* if dealing w/local data and matchContains than we must make sure
* to loop through all the data collections looking for matches
*/
if (!options.url && options.matchContains) {
// track all matches
var csub = [];
// loop through all the data grids for matches
for (var k in data) {
// don't search through the stMatchSets[""] (minChars: 0) cache
// this prevents duplicates
if (k.length > 0) {
var c = data[k];
$.each(c, function (i, x) {
// if we've got a match, add it to the array
if (matchSubset(x.value, q)) {
csub.push(x);
}
});
}
}
return csub;
} else
// if the exact item exists, use it
if (data[q]) {
return data[q];
} else if (options.matchSubset) {
for (var i = q.length - 1; i >= options.minChars; i--) {
var c = data[q.substr(0, i)];
if (c) {
var csub = [];
$.each(c, function (i, x) {
if (matchSubset(x.value, q)) {
csub[csub.length] = x;
}
});
return csub;
}
}
}
return null;
}
};
};
$.Autocompleter.Select = function (options, input, select, config) {
var CLASSES = {
ACTIVE: "ac_over"
};
var listItems,
active = -1,
data,
term = "",
needsInit = true,
element,
list;
// Create results
function init() {
if (!needsInit) return;
element = $("<div/>").hide().addClass(options.resultsClass).css("position", "absolute")
//.attr('id', 'benjamin')
.appendTo(document.body);
list = $("<ul/>").appendTo(element).mouseover(function (event) {
if (target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
$(target(event)).addClass(CLASSES.ACTIVE);
}
}).click(function (event) {
$(target(event)).addClass(CLASSES.ACTIVE);
select();
// TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
input.focus();
return false;
}).mousedown(function () {
config.mouseDownOnSelect = true;
}).mouseup(function () {
config.mouseDownOnSelect = false;
});
if (options.width > 0) element.css("width", options.width);
needsInit = false;
}
function target(event) {
var element = event.target;
while (element && element.tagName != "LI")
element = element.parentNode;
// more fun with IE, sometimes event.target is empty, just ignore it then
if (!element) return [];
return element;
}
function moveSelect(step) {
listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
movePosition(step);
var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
if (options.scroll) {
var offset = 0;
listItems.slice(0, active).each(function () {
offset += this.offsetHeight;
});
if ((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
} else if (offset < list.scrollTop()) {
list.scrollTop(offset);
}
}
};
function movePosition(step) {
active += step;
if (active < 0) {
active = listItems.size() - 1;
} else if (active >= listItems.size()) {
active = 0;
}
}
function limitNumberOfItems(available) {
return options.max && options.max < available ? options.max : available;
}
function fillList() {
list.empty();
var max = limitNumberOfItems(data.length);
for (var i = 0; i < max; i++) {
if (!data[i]) continue;
var formatted = options.formatItem(data[i].data, i + 1, max, data[i].value, term);
if (formatted === false) continue;
var li = $("<li/>").html(options.highlight(formatted, term)).addClass(i % 2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
$.data(li, "ac_data", data[i]);
}
listItems = list.find("li");
if (options.selectFirst) {
listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
active = 0;
}
// apply bgiframe if available
if ($.fn.bgiframe) list.bgiframe();
}
return {
display: function (d, q) {
init();
data = d;
term = q;
fillList();
},
next: function () {
moveSelect(1);
},
prev: function () {
moveSelect(-1);
},
pageUp: function () {
if (active != 0 && active - 8 < 0) {
moveSelect(-active);
} else {
moveSelect(-8);
}
},
pageDown: function () {
if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
moveSelect(listItems.size() - 1 - active);
} else {
moveSelect(8);
}
},
hide: function () {
element && element.hide();
listItems && listItems.removeClass(CLASSES.ACTIVE);
active = -1;
},
visible: function () {
return element && element.is(":visible");
},
current: function () {
return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
},
show: function () {
var offset = $(input).offset();
element.css({
width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
top: offset.top + input.offsetHeight,
left: offset.left
}).show();
if (options.scroll) {
list.scrollTop(0);
list.css({
maxHeight: options.scrollHeight,
overflow: 'auto'
});
if ($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
var listHeight = 0;
listItems.each(function () {
listHeight += this.offsetHeight;
});
var scrollbarsVisible = listHeight > options.scrollHeight;
list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight);
if (!scrollbarsVisible) {
// IE doesn't recalculate width when scrollbar disappears
listItems.width(list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")));
}
}
}
},
selected: function () {
var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
return selected && selected.length && $.data(selected[0], "ac_data");
},
emptyList: function () {
list && list.empty();
},
unbind: function () {
element && element.remove();
}
};
};
$.fn.selection = function (start, end) {
if (start !== undefined) {
return this.each(function () {
if (this.createTextRange) {
var selRange = this.createTextRange();
if (end === undefined || start == end) {
selRange.move("character", start);
selRange.select();
} else {
selRange.collapse(true);
selRange.moveStart("character", start);
selRange.moveEnd("character", end);
selRange.select();
}
} else if (this.setSelectionRange) {
this.setSelectionRange(start, end);
} else if (this.selectionStart) {
this.selectionStart = start;
this.selectionEnd = end;
}
});
}
var field = this[0];
if (field.createTextRange) {
var range = document.selection.createRange(),
orig = field.value,
teststring = "<->",
textLength = range.text.length;
range.text = teststring;
var caretAt = field.value.indexOf(teststring);
field.value = orig;
this.selection(caretAt, caretAt + textLength);
return {
start: caretAt,
end: caretAt + textLength
}
} else if (field.selectionStart !== undefined) {
return {
start: field.selectionStart,
end: field.selectionEnd
}
}
};
})(jQuery);

Categories

Resources