Modal at mouseout

Here’s how to get a modal to appear when the user mouses out of the page, like to type in something to the URL bar:

First off, here’s the HTML:

<div id="exitbox">
 <div id="exitboxclose" onclick="document.getElementById('exitbox').style.display='none';">
 X
 </div>
 {{my.Exit Box}}
 </div>

In this example, the Exitbox is built at Rich Text Token so you can make it look however you want. We create a DIV with just an X in it that, when clicked, well set the style to ‘none’, which hides the box. Instead of an X, you can put in an image or anything else you want.

Now we add in the javascript to unhide it and show it at the event:

//Show the popup on MouseOut
 
 function addEvent(obj, evt, fn) { //Cross Browser event handler. Needed to ensure it works on all browsers
 if (obj.addEventListener) {
 obj.addEventListener(evt, fn, false);
 }
 else if (obj.attachEvent) {
 obj.attachEvent("on" + evt, fn);
 }
} 
 var showMouseOut = 1;
 
addEvent(document, "mouseout", function(e) {
 if(showMouseOut != 0) {
 e = e ? e : window.event;
 var from = e.relatedTarget || e.toElement;
 if (!from || from.nodeName == "HTML") {
 document.getElementById("exitbox").style.display = "block";
 showMouseOut = 0;
 }
 }
});

If you want a form in this box, you can choose to build out the DIV in your template instead of calling a token. ¬†We set a variable, showMouseOut, to 1 initially to indicate that we want this event to fire. Once it’s fired, we set it to 0 because we don’t want it to fire a second time.

Leave a Reply

Your email address will not be published. Required fields are marked *