I have a script that triggers a popover box which offers a free download. It triggers when a user's mouse leaves the page (obviously not for mobile - I already have a working solution for that). In my script I set a cookie to deactivate the script for 30 minutes, and that part works; if I refresh the page the popover doesn't show again.
The problem is that if someone closes the popover box, and haven't refreshed the page (or navigated to another page on the site), the popover occurs every time the mouse moves out of the page.
I am using a function that sets the event, but I can't make it only fire once. (The Wordpress site I am working on is using jquery ver=1.10.2.)
My Javascript:
if (document.cookie.indexOf('somecookiename') != -1) {
function addEvent(obj, evt, fn) {
if (obj.addEventListener) {
obj.addEventListener(evt, fn, false);
} else if (obj.attachEvent) {
obj.attachEvent("on" + evt, fn);
}
}
};
jQuery(document).ready(function($) {
if (document.cookie.indexOf('somecookiename') == -1) {
//var thirtyminutes = 1000*60*30;
var thirtyminutes = 1000 * 60;
var expires = new Date((new Date()).valueOf() + thirtyminutes);
document.cookie = "somecookiename;expires=" + expires.toUTCString();
addEvent(document, "mouseout", function(e) {
e = e ? e : window.event;
var from = e.relatedTarget || e.toElement;
if (!from || from.nodeName == "HTML") {
document.getElementById("preview-download").style.display = "block";
document.getElementById("back-shader").style.display = "block";
}
});
}
});
function showhide(id) {
if (document.getElementById) {
obj = document.getElementById(id);
if (obj.style.display == "none") {
obj.style.display = "";
} else {
obj.style.display = "none";
}
}
}
The HTML:
<div id="back-shader" class="popover2">
<div id="preview-download" class="popover2">
<h4>BEFORE YOU GO:</h4>
<h5>Download A Free Preview....</h5>
<a href="http://website.com/document.pdf" id="preview-pdf">Download Now</a>
<a href="#" id="closer" onclick="showhide('back-shader'); return(false);"></a>
</div>
</div>
The CSS:
#back-shader,
#preview-download {
display: none;
}
It may be something simple, but I am not a javascript expert. Your help, as always, is appreciated.
The easiest way is removing the event listener using removeEventListener
:
document.addEventListener("mouseout", function handler(e) {
e.currentTarget.removeEventListener(e.type, handler);
/* whatever */
});
document.addEventListener("click", function handler(e) {
e.currentTarget.removeEventListener(e.type, handler);
alert('Only once');
});
Click somewhere
The javascript version of turning off listener after one invoke is this:
canvas.addEventListener("mousedown",callback,{
// This will invoke the event once and de-register it afterward
once: true
});
the simplest solution if you use jQuery - use .one()
instead of .on()
this equals to triggering .off()
in on
http://api.jquery.com/one/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With