简体   繁体   中英

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.

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> 

I'm not an expert in jQuery, but the solution could be as easy as creating a window variable.

Define this initally, outside of a function:

window.hasPoppedUp = false;

On the popup code:

if(!window.hasPoppedUp) {
    //do stuff 
    window.hasPoppedUp = true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM