N00b N00b - 9 days ago 6
Javascript Question

JQuery - Only display pop-up once

The following pop-up displays when the mouse leaves the screen. I need a cookie or something to only display this once (I'm a bit of a novice), but can't work out how to incorporate this into the code.

// Exit intent
function addEvent(obj, evt, fn) {
if (obj.addEventListener) {
obj.addEventListener(evt, fn, false);
}
else if (obj.attachEvent) {
obj.attachEvent("on" + evt, fn);
}
}

// Exit intent trigger
addEvent(document, 'mouseout', function(evt) {
if (evt.toElement == null && evt.relatedTarget == null ) {
$('.lightbox').slideDown();
};
});

// Closing the Popup Box
$(document).ready(function(){
$('#close').click(function(){
$('.lightbox').slideUp();
});
});


You can view the code in action here: http://championcontainersnz.com/buy_estimate

Any help you can provide would be greatly appreciated. Thanks.

Answer

The following example will show you with the code that you have provided. You just need a variable to store if the box has popped up or not.

var isPopped = false;
// Exit intent
function addEvent(obj, evt, fn) {
  if (obj.addEventListener) {
    obj.addEventListener(evt, fn, false);
  } else if (obj.attachEvent) {
    obj.attachEvent("on" + evt, fn);
  }
}

// Exit intent trigger
addEvent(document, 'mouseout', function(evt) {
  if (evt.toElement == null && evt.relatedTarget == null && isPopped == false) {
    $('.lightbox').slideDown();
    isPopped = true;
  };
});

// Closing the Popup Box
$(document).ready(function() {
  $('#close').click(function() {
    $('.lightbox').slideUp();
  });
});
.lightbox {
  border: solid 1px #000;
  padding: 50px;
  position: absolute;
  top: 50px;
  left: 150px;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="lightbox">Hello There
<button id="close">Close Me</button></div>