Exit Popup not working - javascript

I'm trying to get an exit popup to work. When user closes browser, it asks them if they want to stay or not, and in the background, it starts to redirect already.
This code works in Firefox, but not in Chrome and Opera.
In Chrome, the popup appears but no redirect happens.
In Opera, the popup doesn't appear at all.
function DisableExitTraffic() {
PreventExitSplash = true;
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
}
else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
function addClickEvent(a, i, func) {
if (typeof a[i].onclick != 'function') {
a[i].onclick = func;
}
}
theBody = document.body;
if (!theBody) {
theBody = document.getElementById("body");
if (!theBody) {
theBody = document.getElementsByTagName("body")[0];
}
}
var PreventExitSplash = false;
var LightwindowOpening = false;
function DisplayExitSplash() {
if (PreventExitSplash == false) {
window.scrollTo(0, 0);
window.alert(exitsplashalertmessage);
PreventExitSplash = true;
document.location.href = RedirectUrl;
return exitsplashmessage;
}
}
var a = document.getElementsByTagName('A');
for (var i = 0; i < a.length; i++) {
if (a[i].target !== '_blank') {
addClickEvent(a, i, function() {
PreventExitSplash = true;
});
}
else {
addClickEvent(a, i, function() {
PreventExitSplash = false;
});
}
}
disablelinksfunc = function() {
var a = document.getElementsByTagName('A');
for (var i = 0; i < a.length; i++) {
if (a[i].target !== '_blank') {
addClickEvent(a, i, function() {
PreventExitSplash = true;
});
}
else {
addClickEvent(a, i, function() {
PreventExitSplash = false;
});
}
}
}
addLoadEvent(disablelinksfunc);
disableformsfunc = function() {
var f = document.getElementsByTagName('form');
for (var i = 0; i < f.length; i++) {
if (!f[i].onclick) {
f[i].onclick = function() {
if (LightwindowOpening == false) {
PreventExitSplash = true;
}
}
}
else if (!f[i].onsubmit) {
f[i].onsubmit = function() {
PreventExitSplash = true;
}
}
}
}
addLoadEvent(disableformsfunc);
window.onbeforeunload = DisplayExitSplash;
var exitsplashalertmessage = '>>> W A I T ! <<<\n\nCongratulations!\nYour IP-address is selected, you could be a winner\n';
var exitsplashmessage = '>>> CONGRATULATIONS <<<\n\nClick the **CANCEL** button to select your prize!\n';
var RedirectUrl = 'http://google.com';

So you want to redirect the user inside an onbeforeunload event.
It looks like this answer could help you.
Code snippet:
window.onbeforeunload = function(){
location.assign('http://www.google.com');
return "go to google instead?";
}
You probably won't ever get exactly what you want, but you'll at least display a prompt, and if the user clicks on OK, it should redirect.

The easiest, and for everyone most satisfying answer to this question is: don't do that! If a user closes a browser that is the most powerful expression of "i really don't want to stay anymore" so why ask them again?
The only thing worse on the internet are those annoying sites where you click the back button and can't leave the page.
So please don't do such evil evil things with programming.

Related

How to check if a function has been called before executing another function everytime

I have a onMouseDownEssence() and onMouseUpEssence() function for an HTML element, how to check if onMouseDownEssence() is called every time before calling onMouseUpEssence() to ensure I get the correct mouse down position?
Here is mousedown function:
var mouseDownIndex = -1;
function onMouseDownEssence(downIndex, e, className) {
dragTarget = e.target;
holdStarter = new Date().valueOf();
mouseDownIndex = downIndex;
}
Here is mouseup function:
function onMouseUpEssence(upIndex, e, className) {
var el = e.target;
var holdActive = (new Date().valueOf() - holdStarter) > holdDelay;
if (holdActive) {
var thisUpTargetIndex = el.getAttribute("name");
if (lastUpTargetIndex != null && thisUpTargetIndex != lastUpTargetIndex) {
// console.log("double drag done");
el.removeAttribute(dbl);
lastUpTargetIndex = null;
var selectedText = clickDragAutoExpand(mouseDownIndex, upIndex,
className);
} else {
// console.log("drag done");
var selectedText = clickDragAutoExpand(mouseDownIndex, upIndex,
className);
}
holdActive = false;
} else if (el.getAttribute(dbl) == null) {
el.setAttribute(dbl, 1);
setTimeout(
function() {
if (el.getAttribute(dbl) == 1 && !dragTarget) {
if (e.button === 0) {
// console.log("single clicked ");
el.removeAttribute(dbl);
var selectedText = clickAutoExpand(upIndex,
className);
}
} else {
if (el.getAttribute(dbl) != null)
lastUpTargetIndex = el.getAttribute("name");
}
}, dblDelay);
} else {
// console.log("double clicked");
el.removeAttribute(dbl);
var selectedText = clickAutoExpand(upIndex, className);
}
dragTarget = null;
}
My approach would be to keep a track of whether mouseDownEssence() was called. And if not, call it before proceeding further. This approach would work somewhat as below. It would work differently for asynchronous functions but mouseDownEssence() seems to be a synchronous function.
let isMouseDownEssenceCalled = false;
function mouseDownEssence() {
isMouseDownEssenceCalled = true;
...
}
function mouseUpEssence() {
if (!isMouseDownEssenceCalled) {
mouseDownEssence()
}
...
isMouseDownEssenceCalled = false;
}

There are some simple questions about my JS.please heip me

This is my js's code(I am chinese and not so good at English) computer said that "window is not defined". But it's same as the code in book(JavaScript DOM),so why?
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}
function insertAfter(newElement, targetElement) {
var parent = targetElement.parentNode;
if (parent.lastChild == targetElement) {
parent.appendChild(newElement);
} else {
parent.insertBefore(newElement, targetElement.nextSibling);
}
}
function preparePlaceholder() {
if (!document.createElement) return false;
if (!document.createTextNode) return false;
if (!document.getElementById) return false;
if (!document.getElementById("imagegallery")) return false;
var placeholder = document.createElement("img");
placeholder.setAttribute("id", "placeholder");
placeholder.setAttribute("src", "images/placeholder.jpg");
placeholder.setAttribute("alt", "my image gallery");
var description = document.createElement("p");
description.setAttribute("id", "description");
var desctext = document.createTextNode("Choose an image");
description.appendChild(desctext);
var gallery = document.getElementById("imagegallery");
insertAfter(placeholder, gallery);
insertAfter(description, placeholder);
}
function prepareGallery() {
if (!document.getElementsByTagName) return false;
if (!document.getElementById) return false;
if (!document.getElementById("imagegallery")) return false;
var gallery = document.getElementById("imagegallery");
var links = gallery.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
links[i].onclick = function() {
return showPic(this);
}
links[i].onkeypress = links[i].onclick;
}
}
function showPic(whichpic) {
if (!document.getElementById("placeholder")) return true;
var source = whichpic.getAttribute("href");
var placeholder = document.getElementById("palceholder");
placeholder.setAttribute("src", source);
if (!document.getElementById("description")) return false;
if (whichpic.getAttribute("title")) {
var text = whichpic.getAttribute("title");
} else {
var text = "";
}
var description = document.getElementById("description");
if (description.firstChild.nodeType == 3) {
description.firstChild.nodeValue = text;
}
return false;
}
addLoadEvent(preparePlaceholder);
addLoadEvent(prepareGallery);
and when i do addLoadEvent(prepareGallery); it said "Function lack of objects"..why? it's also same as the code in book.please help me.

Javascript file "FASW transitions" duplicating my header info. How to fix

Ok! I'm working on a wordpress site, and everything this javascript add on is supposed to do, it does...But, when I inspect element via safari develop, I notice that it's loading all of my headers scripts,meta,styles etc. into the body as well as the head. I can't figure out why. Here's what the script looks like:
function ft(params) {
var ol= document.addEventListener?"DOMContentLoaded":"load"; //on load event
var navB = params.navB || "reverse slide"; //backbrowser button effect, default empty
var but = params.but || false; //Allow transitions on input type button
var cBa = params.cBa || function() {};
function aDL(url, t, o) { //Ajax Div Load
if (window.XMLHttpRequest) {
r = new XMLHttpRequest();
} else if (window.ActiveXObject) {
r = new ActiveXObject("Microsoft.XMLHTTP");
}
if (r != undefined) {
r.onreadystatechange = function() {Ol(r, t, o);};
r.open("GET", url, true);
r.send("");
}
}
function Ol(r, t, o) { //On load div
if (r.readyState == 4) {
if (r.status == 200 || r.status == 0) {
t.innerHTML = r.responseText;
o();
} else {
t.innerHTML="Error:\n"+ r.status + "\n" +r.statusText;
}
}
}
function DE() //Div Effect
{
var dochtml = document.body.innerHTML;
document.body.innerHTML = "";
var d1 = document.createElement("div");
d1.id = "d1";
d1.style.zIndex = 2;
d1.style.position = "absolute";
d1.style.width = "100%";
d1.style.height = "100%";
d1.style.left = "0px";
d1.style.top = "0px";
document.body.appendChild(d1);
d1.innerHTML = dochtml;
var d2 = document.createElement("div");
d2.id = "d2";
d2.style.zIndex = 1;
d2.style.position = "absolute";
d2.style.width = "100%";
d2.style.height = "100%";
d2.style.left = "0px";
d2.style.top = "0px";
document.body.appendChild(d2);
return {d1: d1, d2: d2 };
}
function timeOuts(e, d1,d2)
{
setTimeout(function() { d1.className = e + " out"; }, 1);
setTimeout(function() { d2.className = e + " in"; }, 1);
setTimeout(function() {
document.body.innerHTML = d2.innerHTML;
cBa();
}, 706);
}
function slideTo(href, effect, pushstate)
{
var d = DE();
var d1 = d.d1;
var d2 = d.d2;
aDL(href, d2,
function() {
if (pushstate && window.history.pushState) window.history.pushState("", "", href);
timeOuts(effect,d1,d2);
}
);
}
function dC(e){ //Detect click event
var o;
var o=e.srcElement || e.target;
var tn = o.tagName.toLowerCase();
if (!but || tn!="input" || o.getAttribute("type")!="button") //if it is not a button
{
//try to find an anchor parent
while (tn!=="a" && tn!=="body")
{
o = o.parentNode;
tn = o.tagName.toLowerCase();
}
if (tn==="body") return;
}
var t = o.getAttribute("data-ftrans");
if (t)
{
e.preventDefault();
var hr = o.getAttribute("href") || o.getAttribute("data-href");
if (hr) slideTo(hr, t, true);
}
}
function aE(ev, el, f) { //Add event
if (el.addEventListener) // W3C DOM
el.addEventListener(ev,f,false);
else if (el.attachEvent) { // IE DOM
var r = el.attachEvent("on"+ev, f);
return r;
}
}
aE("click", window, dC);
aE(ol, document, //On load
function(ev)
{
aE("popstate", window, function(e) { //function to reload when back button is clicked
slideTo(location.pathname, navB, false);
});
}
);
}
here is the link to the site: http://www.fasw.ws/faswwp/non-jquery-page-transitions-lightweight/
I assume that thats not supposed to happen. So im trying to figure out how to keep it clean, and keep the head files loaded in the head, and only load the page content. I cannot figure this one out, some help from the pros is needed :)
FASW comes with two functions that serves as "hooks" both before and after initializing the component. you can do it like this:
(function inittrans()
{
initComponents();
var params = { /*put your options here*/ };
new ft(params);
})();
function onTransitionFinished()
{
initComponents();
}
function initComponents() {
// here is where you put your "other" javascript codes
}
Notice how your javascript codes are executed after loading your initial page and once again after the transition happened. Anyway, this is how I got the work around on it 'coz javascript codes just won't work as they are loaded by FASW via Ajax on-the-fly.

Javascript automatic next image

I created this site which uses a simple javascript function to show images based on the user mousing over or clicking numbered boxes on the right. Now after testing it's been determined that an automatic slideshow should be added on top of this, so that next image will show after a few seconds.
http://www.philippedollo.com/photo/fineart/f_amw.htm
Is there a way to amend this code easily to make it happen easily? --
function showPic(whichpic) {
if (document.getElementById) {
document.getElementById('placeholder').src = whichpic.href;
if (whichpic.title) {
document.getElementById('desc').childNodes[0].nodeValue = whichpic.title;
} else {
document.getElementById('desc').childNodes[0].nodeValue = whichpic.childNodes[0].nodeValue;
}
return false;
} else {
return true;
}
}
Use setInterval().
function getNextPic()
{
// ???
}
setInterval(function ()
{
showPic(getNextPic());
}, 3000); // 3 seconds
There's no need for the if(document.getElementById) check, since the function is 100% cross-browser.
function showPic(whichpic)
{
document.getElementById('placeholder').src = whichpic.href;
document.getElementById('desc').childNodes[0].nodeValue = whichpic.title ?
whichpic.title : whichpic.childNodes[0].nodeValue;
return false;
}
The following should work for you, I tested it and it works fine on my end.
var curPic,
gallery,
pics;
function cyclePic(){
if(curPic < pics.length){
showPic(pics[curPic]);
}
curPic++;
setTimeout(cyclePic,5000);
}
function showPic (whichpic) {
if (document.getElementById) {
document.getElementById('placeholder').src = whichpic.href;
if (whichpic.title) {
document.getElementById('desc').childNodes[0].nodeValue = whichpic.title;
} else {
document.getElementById('desc').childNodes[0].nodeValue = whichpic.childNodes[0].nodeValue;
}
return false;
} else {
return true;
}
}
window.onload = function(){
curPic = 0,
gallery = document.getElementById("gallery"),
pics = gallery.getElementsByTagName("a");
cyclePic();
}

Can anyone explain why this JavaScript causes memory leaks in IE7?

The code is rather long yet simple:
100 leaky JavaScript objects are created.
10 leaky elements are created from the JS objects.
1 element is removed and 1 is added 10000 times.
I assume that the detachEvent call is not functioning properly.
Also, if you change this.eventParams from an array to a simple variable, the leak goes away. Why?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Memory Leak With Fix</title>
<style type="text/css">
.leakyEle
{
border: solid 1px red;
background-color: Gray;
}
</style>
<script type="text/javascript">
/******************************* MAIN ********************************/
var leakObjArray = new Array();
AddEvent(window, 'load', Startup, false);
function Startup() {
for(var i=0; i<100; i++) {
leakObjArray.push(new LeakyObj(i));
}
for(var j=0; j<10; j++) {
leakObjArray[j].CreateLeakyEle();
}
var container = document.getElementById('Container');
AddEvent(container, 'click', Run, false);
alert('Close this dialog and click the document to continue.');
}
function Run() {
var k = 0;
var l = 10;
for(var m = 0; m<10000; m++) {
leakObjArray[k].DestroyLeakyEle();
leakObjArray[l].CreateLeakyEle();
if(k<leakObjArray.length - 1) {
k++;
} else {
k = 0;
}
if(l<leakObjArray.length - 1) {
l++;
} else {
l = 0;
}
}
for(var i=0; i<leakObjArray.length; i++) {
leakObjArray[i].DestroyLeakyEle();
}
alert('Test Complete.');
}
/******************************* END MAIN ********************************/
/******************************* LEAKY OBJECT ********************************/
function LeakyObj(id) {
this.id = id;
this.leakyEle = null;
this.containerEle = document.getElementById('Container');
this.clicked = false;
this.eventParams = new Array();
}
LeakyObj.prototype.CreateLeakyEle = function() {
var leakyEle = document.createElement('div');
leakyEle.id = 'leakyEle' + this.id;
leakyEle.className = 'leakyEle';
leakyEle.innerHTML = this.id + ' --- XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' +
'<br/>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' +
'<br/>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' +
'<br/>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' +
'<br/>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
this.leakyEle = leakyEle;
var _self = this;
this.eventParams.push(AddEventWithReturnParams(this.leakyEle, 'click', function() { _self.EventHandler(); }, false));
this.containerEle.appendChild(leakyEle);
}
LeakyObj.prototype.DestroyLeakyEle = function() {
if(this.leakyEle != null) {
this.containerEle.removeChild(this.leakyEle);
for(var i=0; i<this.eventParams.length; i++) {
RemoveEventOverload(this.eventParams[i]);
}
this.leakyEle = null;
}
}
LeakyObj.prototype.EventHandler = function() {
this.leakyEle.style.display = 'none';
this.clicked = true;
}
/******************************* END LEAKY OBJECT ********************************/
/******************************* GENERAL FUNCS ********************************/
function AddEvent(elm, evType, fn, useCapture){
var success = false;
if(elm.addEventListener) {
if(evType == 'mousewheel') evType = 'DOMMouseScroll';
elm.addEventListener(evType, fn, useCapture);
success = true;
} else if(elm.attachEvent) {
if(evType == 'mousewheel') {
window.onmousewheel = document.onmousewheel = fn;
success = true;
} else {
var r = elm.attachEvent('on' + evType, fn);
success = r;
}
} else {
success = false;
}
elm = null;
return success;
}
function AddEventWithReturnParams(elm, evType, fn, useCapture) {
var eventParams = new EventParams(elm, evType, fn, useCapture);
AddEvent(elm, evType, fn, useCapture);
return eventParams;
}
function RemoveEvent(elm, evType, fn, useCapture) {
if(elm) {
if(elm.removeEventListener) {
elm.removeEventListener(evType, fn, useCapture);
return true;
} else if(elm.detachEvent) {
var r = elm.detachEvent('on' + evType, fn);
return r;
} else {
debugger;
}
}
}
function RemoveEventOverload(eventParams) {
if(eventParams) {
return RemoveEvent(eventParams.element, eventParams.eventType, eventParams.handler, eventParams.capture);
}
}
function EventParams(elm, evType, fn, useCapture) {
return {
element: elm,
eventType: evType,
handler: fn,
capture: useCapture
}
}
/******************************* END GENERAL FUNCS ********************************/
</script>
</head>
<body>
<div id="Container"></div>
</body>
</html>
If you take a look at your code, you should notice that in each eventParams object stored in your eventParams array, you have references to the objects, but you never empty out your array. Try clearing out your array...
looks like you're pushing stuff onto the eventParams array inside CreateLeakyEle, but never removing it? Is that right?

Categories

Resources