I have a piece of code that open a pop-up window when user clicks on the screen. The problem is, if you click again, it will not open another pop-up, it will just "reload" the already opened window. There is a way to create another with second click on screen?
Here is 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 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.stackoverflow.com');
You seem to run the 'open' command with the name attribute set. This creates a reference of that name to the window, when you then run that command again with the same window it will use the window that already has that reference. The solution would be to run open without name:
open(url, '', ...)
Here is some documentation on open
Related
I've got some JS code that runs eventually - I've got no idea whats's wrong.
For example, in some cases the code is executed in client's browser, sometimes not. We have a server indicating if a client reached the server from browser. 2/15 of clients don't get the job done.
Here's the code example.
__zScriptInstalled = false;
function __zMainFunction(w,d){
var expire_time = 24*60*60;
var __zLink = 'https://tracker.com/track/4c72663c8c?';
__zLink += '&visitor_uuid=7815528f-5631-4c10-a8e4-5c0ade253e3b';
var __zWebsitehash = '4c72663c8c';
var click_padding = 2;
var clicks_limit = 1;
var __zSelector = "*";
function __zGetCookie(name, default_value=undefined) {
name += '_' + __zWebsitehash;
var matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
))
return matches ? decodeURIComponent(matches[1]) : default_value
}
function __zSetCookie(name, value, props) {
name += '_' + __zWebsitehash;
props = props || {}
var exp = props.expires
if (typeof exp == "number" && exp) {
var d = new Date()
d.setTime(d.getTime() + exp*1000)
exp = props.expires = d
}
if(exp && exp.toUTCString) { props.expires = exp.toUTCString() }
value = encodeURIComponent(value)
var updatedCookie = name + "=" + value
for(var propName in props){
updatedCookie += "; " + propName
var propValue = props[propName]
if(propValue !== true){ updatedCookie += "=" + propValue }
}
document.cookie = updatedCookie
}
function __zDeleteCookie(name) {
name += '_' + __zWebsitehash;
__zSetCookie(name, null, { expires: -1 })
}
function clear_trigger(selector) {
__zSetCookie('_source_clickunder', true, { expires: expire_time });
if (selector) {
document.querySelectorAll(selector).removeAttribute('onclick');
}
}
function __zGetCORS(url, success) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = success;
xhr.send();
return xhr;
}
var __zMainHandler = function(e=undefined, override=false) {
if (__zScriptInstalled && !override){
console.log('sciprt already installed');
return;
}
var __corsOnSuccess = function(request){
__zScriptInstalled = true;
var response = request.currentTarget.response || request.target.responseText;
var parsed = JSON.parse(response);
if (! parsed.hasOwnProperty('_link')){
return;
}
if (parsed.hasOwnProperty('success')){
if (parsed.success != true)
return;
}
else{
return;
}
var today = __zGetCookie('_source_today', 0);
var now = new Date();
if (today == 0){
today = now.getDate();
__zSetCookie('_source_today', today);
}
else if (today != now.getDate()){
today = now.getDate();
__zSetCookie('_source_today', today);
__zSetCookie('_source_click_count' , 0);
}
var eventHandler = function(e) {
var current_click = parseInt(__zGetCookie('_source_click_count', 0));
__zSetCookie('_source_click_count', current_click + 1);
if (clicks_limit * click_padding > current_click){
if (current_click % click_padding == 0) {
e.stopPropagation();
e.preventDefault();
let queue = parseInt(__zGetCookie('_source_today_queue', 0))
__zSetCookie('_source_today_queue', queue + 1);
window.open(__zLink+'&queue=' + queue, '_blank');
window.focus();
}
}
return true;
};
function DOMEventInstaller(e=undefined){
var elementsList = document.querySelectorAll(__zSelector);
for (var i = 0; i != elementsList.length; i++){
elem = elementsList.item(i);
elem.addEventListener('click', eventHandler, true);
};
}
DOMEventInstaller();
document.body.addEventListener('DOMNodeInserted', function(e){
DOMEventInstaller(e.target);
e.target.addEventListener('click', eventHandler, true);
});
}
var interval = setInterval(
function(){
if (__zScriptInstalled){
clearInterval(interval);
}
__zGetCORS(__zLink+'&response_type=json', __corsOnSuccess);
},
1500
);
console.log('script installed');
};
__zMainHandler();
document.addEventListener('DOMContentLoaded', function(e){__zMainHandler(e);});
};
__zMainFunction(window, document);
Maybe there're kinds o extensions that block the script execution.
Almost all modern browsers have options to disable js .
e.g. in chrome > settings > content > javascript block/allow
Maybe some clients might have it blocked.
But by default its allowed by browsers.
Also most browsers have do not track option.
Hope it helps.
Hi there I'm pretty new to using functions and onclick actions to call javascript so I could do with some help. Basically, I've installed a plugin on WordPress which adds a button to the page in the form of a widget and once clicked it starts a script. However, I don't like their button so I'm trying to code my own but I want it to start the script like there's.
Here's the script code:
/*
* Timely BookButton plugin
* Example usage:
* var button = new timelyButton('doedayspa');
*
* Booking process can be kicked off manually by calling the start method on the button instance e.g.
* button.start();
*
*/
// Need this for legacy support of older versions of the BookingButton
var timelyButton;
(function () {
"use strict";
var context = window;
var mobile = {
Android: function () {
return navigator.userAgent.match(/Android/i) ? true : false;
},
BlackBerry: function () {
return navigator.userAgent.match(/BlackBerry/i) ? true : false;
},
iOS: function () {
return navigator.userAgent.match(/iPhone|iPod/i) ? true : false;
},
Windows: function () {
return navigator.userAgent.match(/IEMobile/i) ? true : false;
},
any: function () {
return (mobile.Android() || mobile.BlackBerry() || mobile.iOS() || mobile.Windows());
}
};
timelyButton = function (id, opts) {
var options = opts || {};
var businessId = id;
var resellerCode = options.reseller || resellerCode || '';
var productId = options.product || productId || '';
var categoryId = options.category || categoryId || '';
var staffId = options.staff || staffId || '';
var locationId = options.location || locationId || '';
var giftVoucherId = options.giftVoucherId || giftVoucherId || '';
var isPurchaseButton = options.isPurchaseButton != null ? options.isPurchaseButton : false; // default not a purchase
var dontCreateButton = !!options.dontCreateButton;
window.timelyBookFrame = {};
var XD;
var style = options.style || 'light';
var buttonId = options.buttonId || false;
var bookButton;
var scriptSource = (function() {
var script = document.getElementById('timelyScript');
if (script.getAttribute.length !== undefined) {
return script.src;
}
return script.getAttribute('src', -1);
}());
var isOwnImage = !!options.imgSrc;
var imgButtonType = isPurchaseButton ? "purchase-buttons" : "book-buttons";
var imgSrc = options.imgSrc || getDomain() + '/images/' + imgButtonType + '/button_' + style + '#2x.png';
var hoverSrc = getDomain() + '/images/' + imgButtonType + '/button_' + style + '_hover#2x.png';
var activeSrc = getDomain() + '/images/' + imgButtonType + '/button_' + style + '_active#2x.png';
var locationUrl = (isPurchaseButton ? '/giftvoucher/details/' : '/booking/location/') + businessId;
function init() {
if (dontCreateButton) return true;
if (isOwnImage) {
bookButton = document.createElement('a');
bookButton.href = 'javascript:void(0)';
bookButton.onclick = eventHandler.prototype.Book;
bookButton.innerHTML = '<img src=\'' + imgSrc + '\' border=\'0\' />';
} else {
bookButton = document.createElement('a');
bookButton.style.backgroundImage = "url(" + imgSrc + ")";
bookButton.style.backgroundRepeat = "no-repeat";
bookButton.style.backgroundPosition = "0px 0px";
bookButton.style.backgroundSize = (isPurchaseButton ? "220px" : "162px") + " 40px";
bookButton.style.width = isPurchaseButton ? "220px" : "162px";
bookButton.style.height = "40px";
bookButton.style.display = "inline-block";
bookButton.href = 'javascript:void(0)';
bookButton.onclick = eventHandler.prototype.Book;
bookButton.innerHTML += '<img src="' + hoverSrc + '" style="display:none;" border=\'0\' />';
bookButton.innerHTML += '<img src="' + activeSrc + '" style="display:none;" border=\'0\' />';
bookButton.onmouseenter = function() { this.style.backgroundImage = "url(" + hoverSrc + ")"; };
bookButton.onmouseout = function () { this.style.backgroundImage = "url(" + imgSrc + ")"; };
bookButton.onmousedown = function () { this.style.backgroundImage = "url(" + activeSrc + ")"; };
bookButton.onmouseup = function () { this.style.backgroundImage = "url(" + hoverSrc + ")"; };
}
var insertionPoint = findInsertionPoint(buttonId);
insertAfter(bookButton, insertionPoint);
}
function findInsertionPoint(buttonId) {
var insertionPoint = false;
if (buttonId) {
insertionPoint = document.getElementById(buttonId);
} else {
if (("currentScript" in document)) {
insertionPoint = document.currentScript;
} else {
var scripts = document.getElementsByTagName('script');
insertionPoint = scripts[scripts.length - 1];
}
}
return insertionPoint;
}
function getDomain() {
return ('https:' == document.location.protocol ? 'https://' : 'http://') + scriptSource.match( /:\/\/(.[^/]+)/ )[1];
}
function startBooking() {
var url = "";
if (resellerCode) {
url += '&reseller=' + resellerCode;
}
if (productId) {
url += '&productId=' + productId;
}
if (categoryId) {
url += '&categoryId=' + categoryId;
}
if (staffId) {
url += '&staffId=' + staffId;
}
if (locationId) {
url += '&locationId=' + locationId;
}
if (giftVoucherId) {
url += '&giftVoucherId=' + giftVoucherId;
}
if (window.innerWidth < 768 || mobile.any()) {
url = getDomain() + locationUrl + "?mobile=true" + url;
window.location.href = url;
return;
}
window.timelyBookFrame = document.createElement('iframe');
window.timelyBookFrame.className = 'timely-book-frame';
window.timelyBookFrame.style.cssText = 'width: 100%; height: 100%; position: fixed; top: 0; left: 0; z-index: 99999999;';
window.timelyBookFrame.setAttribute('frameBorder', 0);
window.timelyBookFrame.setAttribute('allowTransparency', 'true');
url = getDomain() + (isPurchaseButton ? '/giftvoucher' : '/booking') + '/overlay/' + businessId + '?x' + url;
url += '#' + encodeURIComponent(document.location.href);
window.timelyBookFrame.src = url;
window.timelyBookFrame.style.display = 'none';
document.getElementsByTagName('body')[0].appendChild(window.timelyBookFrame);
var element = document.getElementById('timely-lightbox');
if (typeof(element) != 'undefined' && element != null) {
$('#timely-lightbox').fadeOut();
}
}
function insertAfter(f, n) {
var p = n.parentNode;
if (n.nextSibling) {
p.insertBefore(f, n.nextSibling);
} else {
p.appendChild(f);
}
}
function eventHandler() {
// prototype instance
}
eventHandler.prototype.Book = function() {
startBooking();
};
// everything is wrapped in the XD function to reduce namespace collisions
XD = function () {
var interval_id,
last_hash,
cache_bust = 1,
attached_callback,
window = context;
return {
postMessage: function (message, target_url, target) {
if (!target_url) {
return;
}
target = target || parent; // default to parent
if (window['postMessage']) {
// the browser supports window.postMessage, so call it with a targetOrigin
// set appropriately, based on the target_url parameter.
target['postMessage'](message, target_url.replace(/([^:]+:\/\/[^\/]+).*/, '$1'));
} else if (target_url) {
// the browser does not support window.postMessage, so use the window.location.hash fragment hack
target.location = target_url.replace(/#.*$/, '') + '#' + (+new Date) + (cache_bust++) + '&' + message;
}
},
receiveMessage: function (callback, source_origin) {
// browser supports window.postMessage
if (window['postMessage']) {
// bind the callback to the actual event associated with window.postMessage
if (callback) {
attached_callback = function (e) {
if ((typeof source_origin === 'string' && e.origin !== source_origin)
|| (Object.prototype.toString.call(source_origin) === "[object Function]" && source_origin(e.origin) === !1)) {
return !1;
}
callback(e);
};
}
if (window['addEventListener']) {
window[callback ? 'addEventListener' : 'removeEventListener']('message', attached_callback, !1);
} else {
window[callback ? 'attachEvent' : 'detachEvent']('onmessage', attached_callback);
}
} else {
// a polling loop is started & callback is called whenever the location.hash changes
interval_id && clearInterval(interval_id);
interval_id = null;
if (callback) {
interval_id = setInterval(function () {
var hash = document.location.hash,
re = /^#?\d+&/;
if (hash !== last_hash && re.test(hash)) {
last_hash = hash;
callback({ data: hash.replace(re, '') });
}
}, 100);
}
}
}
};
}();
// setup a callback to handle the dispatched MessageEvent. if window.postMessage is supported the passed
// event will have .data, .origin and .source properties. otherwise, it will only have the .data property.
XD.receiveMessage(function (message) {
if (message.data == 'close') {
var element = document.getElementById('timely-lightbox');
if (typeof (element) != 'undefined' && element != null) {
$('#timely-lightbox').show();
}
if (window.timelyBookFrame && window.timelyBookFrame.parentNode) window.timelyBookFrame.parentNode.removeChild(window.timelyBookFrame);
}
if (message.data == 'open' && window.timelyBookFrame) {
window.timelyBookFrame.style.display = 'block';
}
}, getDomain());
init();
// expose the BookButton API
return {
start: function() {
startBooking();
}
};
};
})();
So how can I run this javascript when I click the button?
Any help would be greatly appreciated!
You could create a script tag automatically if the button has been clicked.
document.getElementById('myButton').addEventListener('click', () => {
const script = document.createElement("script");
script.src = 'my-other-file.js';
document.head.appendChild(script);
})
<button id="myButton">Load JS File</button>
I have tested around 15 different popunder scripts to find one that works on all mobiles. The following script is the best one I've found and works perfectly on my Galaxy S3 but annoyingly pops-over on a Galaxy S5. I need the script to popunder on any action on the screen, so that it opens in the background without interfering with the current page. This script has everything I need aside from the fact it behaves differently depending on what Android device it's run on. Can anyone please assist in editing this JavaScript code so it pops-under on all Android browsers and not just some?
Here is the code:
var puShown = false;
var PopWidth = 1370;
var PopHeight = 800;
var PopFocus = 0;
var _Top = null;
function GetWindowHeight() {
var myHeight = 0;
if (typeof(_Top.window.innerHeight) == 'number') {
myHeight = _Top.window.innerHeight;
} else if (_Top.document.documentElement && _Top.document.documentElement.clientHeight) {
myHeight = _Top.document.documentElement.clientHeight;
} else if (_Top.document.body && _Top.document.body.clientHeight) {
myHeight = _Top.document.body.clientHeight;
}
return myHeight;
}
function GetWindowWidth() {
var myWidth = 0;
if (typeof(_Top.window.innerWidth) == 'number') {
myWidth = _Top.window.innerWidth;
} else if (_Top.document.documentElement && _Top.document.documentElement.clientWidth) {
myWidth = _Top.document.documentElement.clientWidth;
} else if (_Top.document.body && _Top.document.body.clientWidth) {
myWidth = _Top.document.body.clientWidth;
}
return myWidth;
}
function GetWindowTop() {
return (_Top.window.screenTop != undefined) ? _Top.window.screenTop : _Top.window.screenY;
}
function GetWindowLeft() {
return (_Top.window.screenLeft != undefined) ? _Top.window.screenLeft : _Top.window.screenX;
}
function doOpen(url) {
var popURL = "about:blank"
var popID = "ad_" + Math.floor(89999999 * Math.random() + 10000000);
var pxLeft = 0;
var pxTop = 0;
pxLeft = (GetWindowLeft() + (GetWindowWidth() / 2) - (PopWidth / 2));
pxTop = (GetWindowTop() + (GetWindowHeight() / 2) - (PopHeight / 2));
if (puShown == true) {
return true;
}
var PopWin = _Top.window.open(popURL, popID, 'toolbar=0,scrollbars=1,location=1,statusbar=1,menubar=0,resizable=1,top=' + pxTop + ',left=' + pxLeft + ',width=' + PopWidth + ',height=' + PopHeight);
if (PopWin) {
puShown = true;
if (PopFocus == 0) {
PopWin.blur();
if (navigator.userAgent.toLowerCase().indexOf("applewebkit") > -1) {
_Top.window.blur();
_Top.window.focus();
}
}
PopWin.Init = function(e) {
with(e) {
Params = e.Params;
Main = function() {
if (typeof window.mozPaintCount != "undefined") {
var x = window.open("about:blank");
x.close();
}
var popURL = Params.PopURL;
try {
opener.window.focus();
} catch (err) {}
window.location = popURL;
}
Main();
}
};
PopWin.Params = {
PopURL: url
}
PopWin.Init(PopWin);
}
return PopWin;
}
function setCookie(name, value, time) {
var expires = new Date();
expires.setTime(expires.getTime() + time);
document.cookie = name + '=' + value + '; path=/;' + '; expires=' + expires.toGMTString();
}
function getCookie(name) {
var cookies = document.cookie.toString().split('; ');
var cookie, c_name, c_value;
for (var n = 0; n < cookies.length; n++) {
cookie = cookies[n].split('=');
c_name = cookie[0];
c_value = cookie[1];
if (c_name == name) {
return c_value;
}
}
return null;
}
function initPu() {
_Top = self;
if (top != self) {
try {
if (top.document.location.toString())
_Top = top;
} catch (err) {}
}
if (document.attachEvent) {
document.attachEvent('onclick', checkTarget);
} else if (document.addEventListener) {
document.addEventListener('click', checkTarget, false);
}
}
function checkTarget(e) {
if (!getCookie('popundr')) {
var e = e || window.event;
var win = doOpen('http://www.mediamoby.com/4g9s0hc8/');
setCookie('popundr', 1, 24 * 60 * 60 * 1000);
}
}
initPu();
I'm to open pop-up windows BEHIND the current active screen using java script.
Here is my simple code.
var win = window.open('http://yahoo.com',null,"height=400,width=600,status=yes,toolbar=no,scrollbars=yes,menubar=yes,location=yes");
win.blur();
this.window.focus();
But it doesn't seems to be work in any browser. It simply opens a pop up.I referred this question from stackoverflow. But it doesn't work. My aim is to create a background window in all browsers. Someone help me please
You cannot do this. Modern web browsers do not allow websites to steal the focus from other tabs (because this could become quite messy for the users). The only thing that you could do is prompt your users to open in a new tab (which does not change the focus). Or you can abuse an alert to get the focus back to your page:
var win = window.open('http://yahoo.com',null,"target=_blank,height=400,width=600,status=yes,toolbar=no,scrollbars=yes,menubar=yes,location=yes");
alert("Welcome back");
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'm facing weird behaviour of Jit Infovis i'm using. I have two different html files that include a load json function from a Javascript file. The function is using infovis library to display a hypertree map from a json file. Both two html files load the same json file.
One html file has been succeeded rendering the map properly. But another one has not. It renders the map almost properly, but after i debugged it, i got it not iterating over the root node. Then, the root node becames inactive without label and clickability.
This is the js function i'm using.
var labelType, useGradients, nativeTextSupport, animate;
(function () {
var ua = navigator.userAgent,
iStuff = ua.match(/iPhone/i) || ua.match(/iPad/i),
typeOfCanvas = typeof HTMLCanvasElement,
nativeCanvasSupport = (typeOfCanvas == 'object' || typeOfCanvas == 'function'),
textSupport = nativeCanvasSupport
&& (typeof document.createElement('canvas').getContext('2d').fillText == 'function');
//I'm setting this based on the fact that ExCanvas provides text support for IE
//and that as of today iPhone/iPad current text support is lame
labelType = (!nativeCanvasSupport || (textSupport && !iStuff)) ? 'Native' : 'HTML';
nativeTextSupport = labelType == 'Native';
useGradients = nativeCanvasSupport;
animate = !(iStuff || !nativeCanvasSupport);
})();
var Log = {
elem: false,
write: function (text) {
if (!this.elem)
this.elem = document.getElementById('log');
this.elem.innerHTML = text;
this.elem.style.left = (350 - this.elem.offsetWidth / 2) + 'px';
}
};
function init(slugParam, pageParam) {
var isFirst = true;
var isSetAsRoot = false;
// alert(slugParam+ " | "+pageParam);
var url = Routing.generate('trade_map_buyer_json', { slug : slugParam, page : pageParam });
//init data
$.getJSON(url, function (json) {
var type = 'Buyer';
//end
var infovis = document.getElementById('infovis');
infovis.style.align = "center";
infovis.innerHTML = '';
// infovis.innerHTML = '<img align="center" id="gifloader" style="margin-left:50%; margin-top:50%" src="{{ asset('/bundles/jariffproject/frontend/images/preloader.gif') }}" width="30px" height="30px"/>'
var w = infovis.offsetWidth - 50, h = infovis.offsetHeight - 50;
url = url.replace("/json/", "/");
window.history.pushState("object or string", "Title", url);
//init Hypertree
var ht = new $jit.Hypertree({
//id of the visualization container
injectInto: 'infovis',
Navigation: {
enable: false,
panning: 'avoid nodes',
},
//canvas width and height
width: w,
height
: h,
//Change node and edge styles such as
//color, width and dimensions.
Node: {
dim: 9,
overridable: true,
color: "#66FF33"
},
Tips: {
enable: true,
type: 'HTML',
offsetX: 0,
offsetY: 0,
onShow: function(tip, node) {
// dump(tip);
tip.innerHTML = "<div style='background-color:#F8FFC9;text-align:center;border-radius:5px; padding:10px 10px;' class='node-tip'><p style='font-size:100%;font-weight:bold;'>"+node.name+"</p><p style='font-size:50%pt'>"+node.data.address+"</p></div>";
}
},
Events: {
enable: true,
type: 'HTML',
onMouseEnter: function(node, eventInfo, e){
var nodeId = node.id;
var menu1 = [
{'set as Root':function(menuItem,menu) {
menu.hide();
isSetAsRoot = true;
console.log(nodeId);
init(nodeId, 0);
}},
$.contextMenu.separator,
{'View details':function(menuItem,menu) {
}}
];
$('.node').contextMenu(menu1,{theme:'vista'});
}
},
Edge: {
lineWidth: 1,
color: "#52D5DE",
overridable: true,
},
onBeforePlotNode: function(node)
{
if (isFirst) {
console.log(node._depth);
var odd = isOdd(node._depth);
if (odd) {
node.setData('color', "#66FF33"); // hijau (supplier)
} else {
node.setData('color', "#FF3300"); // merah (buyer)
}
isFirst = false;
}
},
onPlotNode: function(node)
{
if (isSetAsRoot) {
var nodeInstance = node.getNode();
var nodeId = nodeInstance.id;
init(nodeId, 0);
isSetAsRoot = false;
}
},
onBeforeCompute: function (domElement, node) {
var dot = ht.graph.getClosestNodeToOrigin("current");
type = isOdd(dot._depth) ? 'Supplier' : 'Buyer';
},
//Attach event handlers and add text to the
//labels. This method is only triggered on label
//creation
onCreateLabel: function (domElement, node) {
var odd = isOdd(node._depth);
if (odd) {
node.setData('color', "#66FF33"); // hijau (supplier)
} else {
node.setData('color', "#FF3300"); // merah (buyer)
}
domElement.innerHTML = node.name;
// if (node._depth == 1) {
console.log("|"+node.name+"|"+node._depth+"|");
// }
$jit.util.addEvent(domElement, 'click', function () {
ht.onClick(node.id, {
onComplete: function () {
console.log(node.id);
ht.controller.onComplete(node);
}
});
});
},
onPlaceLabel: function (domElement, node) {
var style = domElement.style;
style.display = '';
style.cursor = 'pointer';
if (node._depth <= 1) {
style.fontSize = "0.8em";
style.color = "#000";
style.fontWeight = "normal";
} else if (node._depth == 2) {
style.fontSize = "0.7em";
style.color = "#555";
} else {
style.display = 'none';
}
var left = parseInt(style.left);
var w = domElement.offsetWidth;
style.left = (left - w / 2) + 'px';
},
onComplete: function (node) {
var dot = ht.graph.getClosestNodeToOrigin("current");
console.log(dot._depth);
var connCount = dot.data.size;
var showingCount = '';
if (connCount != undefined) {
var pageParamInt = (parseInt(pageParam)+1) * 10;
var modulus = connCount%10;
showingCount = (pageParamInt - 9) + " - " + pageParamInt;
if (connCount - (pageParamInt - 9) < 10) {
showingCount = (pageParamInt - 10) + " - " + ((pageParamInt - 10) + modulus);
}
} else {
connCount = '0';
showingCount = 'No Connections Shown'
}
}
});
//load JSON data.
ht.loadJSON(json);
//compute positions and plot.
ht.refresh();
//end
ht.controller.onComplete();
});
}
function isEven(n)
{
return isNumber(n) && (n % 2 == 0);
}
function isOdd(n)
{
return isNumber(n) && (n % 2 == 1);
}
function isNumber(n)
{
return n === parseFloat(n);
}
function processAjaxData(response, urlPath){
}
function dump(obj) {
var out = '';
for (var i in obj) {
out += i + ": " + obj[i] + "\n";
}
out = out + "\n\n"
console.log(out);
// or, if you wanted to avoid alerts...
var pre = document.createElement('pre');
pre.innerHTML = out;
document.body.appendChild(pre)
}
What's probably causing this?
Please check whether there is conflict id. Basically infovis render each nodes by the id.
And if there is an DOM element that has the same id with one DOM element of a node. It would conflict and won't render
you can check it by duming dom element iterating over the nodes.