Using Javascript to generate a popup that appears right before the user tries to navigate away from the page

I have implemented a pop-up overlay on my website, triggered by clicking a button. However, I am looking to enhance this functionality so that when users scroll down the webpage and then move their cursor towards the top of the page (such as the navigation bar), the pop-up window will automatically appear.

Javascript

// Setup Variables
var closePopup = document.getElementById("popupclose");
var overlay = document.getElementById("overlay");
var popup = document.getElementById("popup");
var button = document.getElementById("button");
// Close Popup Function
closePopup.onclick = function() {
    overlay.style.display = 'none';
    popup.style.display = 'none';
};
// Display Overlay and Pop-up
button.onclick = function() {
    overlay.style.display = 'block';
    popup.style.display = 'block';
}

For a demo showcasing all the code, check out my JSFiddle. https://jsfiddle.net/1ud9crou/

Answer №1

In jQuery, here is a way to achieve it:

var isOnTop = false;
$(window).on('mousemove', function(e) {
    mouseIsOnTop = e.pageY < 20;
    if (mouseIsOnTop) {
        button.onclick();
    }
});

If you prefer using pure Javascript for IE support, you can do the following:

(function() {
    document.onmousemove = handleMouseMove;
    function handleMouseMove(event) {
        var dot, eventDoc, doc, body, pageX, pageY;

        event = event || window.event;

        if (event.pageX == null && event.clientX != null) {
            eventDoc = (event.target && event.target.ownerDocument) || document;
            doc = eventDoc.documentElement;
            body = eventDoc.body;
            event.pageX = event.clientX +
              (doc && doc.scrollLeft || body && body.scrollLeft || 0) -
              (doc && doc.clientLeft || body && body.clientLeft || 0);
            event.pageY = event.clientY +
              (doc && doc.scrollTop  || body && body.scrollTop  || 0) -
              (doc && doc.clientTop  || body && body.clientTop  || 0 );
        }

        mouseIsOnTop = event.pageY < 20;
        if (mouseIsOnTop) {
            button.onclick();
        }
    }
})();

UPDATE: To determine if user has scrolled from the top:

var userDidScrollABit = false;
window.onscroll = function() {
    var body = document.body;
    var doc = document.documentElement;
    doc = (doc.clientHeight) ? doc : body;
    if (doc.scrollTop > 20) {
        userDidScrollABit = true;
    }
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for adding a background image to your website

I am attempting to use a URL for a Background Image: However, my approach is not working as expected. Here is the code snippet: body { background-image: url("https://homepages.cae.wisc.edu/~ece533/images/airplane.png"); background: linear-gradient( ...

Only apply the z-index style in React rendering when it is specifically set to zero

My goal is to set a dynamic z-index for my components based on the state variables. Currently, it only works when the zindex is set to 0. Here is an example of my array: images:[ ['img1',false,[1,2,3],1,0],// ...

Setting the height of content using jQuery can be a useful solution when dealing with small window sizes to prevent it from

Encountering an issue with this code. It currently resizes section[role="main"] to the proper height but cuts off when the window is resized to a smaller size. <script type="text/javascript"> $(function(){ $('section[role="main"]&ap ...

Countdown alert using JavaScript

Currently in my frontend code, I am utilizing angularjs as the javascript framework. In a specific section of my code, I need to display an error message followed by a warning message in this format: If a user inputs an incorrect month, then the following ...

I need a regular expression in React JS that matches the following condition. Can anyone provide one?

Spaces Only alpha text will allow spaces. Field can have multiple spaces, but they cannot be consecutive. Dashes Within the alpha text, dashes are allowed. (boyd-lawson" or "boyd - lawson" is acceptable, but "boyd-" and "boyd " and " -boyd" are not) Mul ...

What is the best way to update the context while iterating through a jQuery each loop?

I am currently working on a code snippet that preprocesses response data retrieved from an AJAX call before displaying it (note: the display part is not included in this snippet). Specifically, it updates the src attribute of the image within each li eleme ...

Implementing sliders for interactive functionality with an HTML table

I need to implement sorting and sliding features on an HTML table using jQuery. Sorting has already been achieved by utilizing the DataTable.js jQuery library. The challenge now is to incorporate a slider into the table, with all subject columns being scro ...

Different browsers have varying ways of handling transition end callbacks with AddEventListener()

Each browser has its own transition end callback. Therefore, I find myself needing to use addEventListener() for each one. addEventListener('transitionend', function() { // code here }); addEventListener('webkitTransitionEnd', funct ...

Creating a Self Closing Alert Message in AngularJS: A Step-by-Step Guide

Just getting started with AngularJS and looking to create a self-closing message. How can this be accomplished? I'm aiming for similar results as the question found here: How to Automatically Close Alerts using Twitter Bootstrap However, I want to ...

Dynamic motion of balloons using jquery technology

I am trying to make an image move smoothly inside a div using jQuery and CSS. I have tried rotation and animation, but nothing has worked the way I need it to. <div class="baloon" style="position:fixed;left:0px;top:160px;"> <img id="rot" class="r ...

Guide to integrating react-phone-number-input into material-ui TextField

Would it be possible for me to use a Material UI TextField component as the inputComponent prop for the PhoneInput component from react-phone-number-input? I am facing an issue where I am unable to apply the ref successfully. Even though I can see the Mat ...

Get a single object from an array with .single method provided by @ngrx

Seeking to retrieve an Observable containing a single object from an array of objects in my store. I aim to utilize the .single operator, which should throw an exception if there is not exactly 1 object present. However, I'm struggling with this as my ...

Implementing a delay between two div elements using jQuery

I have two Divs with the class "sliced", each containing three images with the class "tile". When I animate using jQuery, I am unable to add a delay between the "sliced" classes. However, I have successfully added a delay between the "tile" classes. index ...

Changing the title of a webpage dynamically with dropdown menu selections using AngularJS

Seeking assistance with dynamically changing the title of an HTML page based on a selection from a drop-down menu populated by categories retrieved from a remote database using PHP and Ajax in AngularJS. When a category is clicked, I want the page title to ...

What is the best way to retrieve the outcome of a node-sqlite3 query beyond the scope of db.get()?

I'm attempting to validate whether the sha256 hash stored in my sqlite database corresponds with the sha256 hash of the password that the user transmitted to my NodeJS server. The Auth() method is meant to deliver either a true or false result. Is the ...

Starting an AngularJS module without an HTML page may seem like a daunting task,

I am currently developing a browser extension project using AngularJS. Within the background.js file (which contains the code that runs in the background), I have created a module with a run block. var myExtensionModule = angular.module('myExtension ...

unable to render a vector layer in openlayers 6

Currently, I am facing an issue with displaying a vector layer on an openlayers map using the source of local geojson and gpx files in my Vuejs project. Unfortunately, even when testing outside of Vue.js, the vector layer is not being displayed. Here is t ...

Issue with IE canvas dataURI security violation

Converting SVG from the DOM to a dataURI, drawing it as an image on a canvas element, and reading pixel data works smoothly in Chrome and FF. However, IE 10 throws a security error. Here is a link to a codepen The JavaScript code snippet: var SVG_DATA_I ...

What could be causing the console.log to not work in this Express code snippet?

I'm currently utilizing PouchDB in conjunction with Express for retrieving documents from a database: server.js: var express = require('express') var PouchDB = require('pouchdb') var app = express() var db = new PouchDB('vu ...

Incorporating Scatter Dots into a Horizontal Stacked Bar Chart using Chart.js

My horizontal stacked bar chart is not displaying pink scatter dots based on the right y axis numbers. I need help figuring out what I am doing wrong. When I change the chart to a normal bar instead of horizontal, the dots appear. However, I require them ...