Ways to implement a popup alert when a user attempts to navigate away from the webpage or close the tab

I implemented onload="myFunction()" on the body tag, Along with this JavaScript code:

function myFunction() {
  //alert("Page is loaded");
  document.getElementById("test").style.display = "block";
}

function hidePopup() {
  // alert("Hidden");
  document.getElementById("test").style.display = "none";
}
<div id="test" style="z-index: 20000;display: none;">
  <div id="popup">
    <div id="close" onclick="hidePopup()">x</div>
    <div id="popup_img" class="hos_modal" style="height:900px; width:900px; margin:0 auto;">
      <a href="javascript:void()" target="_blank"><img src="files/image.jpg" alt="free trial" style="width: auto; height: auto;"></a>
    </div>
  </div>
</div>

The provided code triggers a popup when the browser is loaded. Additionally, I made use of onunload and onmouseout events.

Answer №1

When it comes to displaying a message to the user, there is an easy solution available.

window.onbeforeunload = function() {
  alert("Hold on! Are you sure you want to leave?");
  return false;
}

By using this event handler and returning false, you can trigger a popup message using alert(""); which prevents the user from navigating away until they confirm their action

Answer №2

Give this code a try - it could be very useful.

Note: To include the onmouseout function, simply uncomment the relevant lines in the code below

function hidePopup() {
  // alert("Hidden");
  document.getElementById("test").style.display = "none";
}

window.onload = function() {
  console.log('window - onload');

};

document.getElementById("tab_3").addEventListener("mouseover", mouseOver);
// document.getElementById("tab_3").addEventListener("mouseout", mouseOut);

function mouseOver() {
  console.log('window - onmouseover');
  document.getElementById("test").style.display = "block";
}

//function mouseOut() {
  //console.log('window - onmouseout');
  //document.getElementById("test").style.display = "none";
//}
/* Style the tab */

div.tab {
  overflow: hidden;
  border: 1px solid #ccc;
  background-color: #f1f1f1;
}


/* Style the links inside the tab */

div.tab a {
  float: left;
  display: block;
  color: black;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  transition: 0.3s;
  font-size: 17px;
}


/* Change background color of links on hover */

div.tab a:hover {
  background-color: #ddd;
}


/* Create an active/current tablink class */

div.tab a:focus,
.active {
  background-color: #ccc;
}


/* Style the tab content */

.tabcontent {
  display: none;
  padding: 6px 12px;
  border: 1px solid #ccc;
  border-top: none;
}
<div class="tab">
  <a id="tab_1" href="#" class="tablinks">Simple Tab</a>
  <a id="tab_2" href="#" class="tablinks">Simple Tab 2</a>
  <a id="tab_3" href="#" class="tablinks" onmouseover="mouseOver()" onmouseout="mouseOut()">Triggerer Tab</a>
</div>



<div id="London" class="tabcontent">
  <h3>London</h3>
  <p>London is the capital city of England.</p>
</div>

<div id="Paris" class="tabcontent">
  <h3>Paris</h3>
  <p>Paris is the capital of France.</p>
</div>

<div id="Tokyo" class="tabcontent">
  <h3>Tokyo</h3>
  <p>Tokyo is the capital of Japan.</p>
</div>

<div id="test" style="z-index: 20000;display: none;">
  <div id="popup">
    <div id="close" onclick="hidePopup()">x</div>
    <div id="popup_img" class="hos_modal" style="height:900px; width:900px; margin:0 auto;">
      <a href="javascript:void()" target="_blank">
        <img src="http://sit-stand.com/img/cms/animation1.gif" alt="free trial" style="width: auto; height: auto;"></a>
    </div>
  </div>
</div>

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

Locating the JSON path within an object

Need help with checking if a specific path is present in a JSON object? var data = { "schemaOne": { "name": "abc", "Path": "i.abc", "count": 5347, "subFolders": [ ] }, "schemaTwo": { "name": "cde", "Path": "i.cde", " ...

Issues detected between Angular and Express rendering operations

Having an issue with my angular code. It runs perfectly on its own, but when I try to access it on localhost with express, it only displays the HTML file. Here's my server code: var express = require('express'), app = express(); app ...

Manipulate your table data with jQuery: add, update, delete, and display information with ease

When adding data dynamically to the table and attempting to edit, the checkbox value is not updating. This issue needs to be resolved. You can view the code in action on jsFiddle here on JSFiddle ...

Obtain the event object within the Vuex v-model setter method

I am working with a select element that interacts with my Vuex store: <select v-model:value="leadTrackNumber" > <option v-for="(track, index) in tracks ">{{ index }}</option> </select> Here is the corresponding method: leadTra ...

What sets apart an object within the scalajs scope from the exact same object within the js.global scope?

Attempting to create a basic example for rendering a cube using the THREEJS library. package three import org.scalajs.dom import scala.scalajs.js import scala.scalajs.js.Dynamic._ import scala.scalajs.js.annotation.JSName ... object ThreeExample { d ...

Will Angular 2 be taking over from traditional AngularJS or will it simply provide another option?

Considering the shift from Angular 1's MVC architecture to Angular 2's component-based structure, it seems like migrating between these versions would necessitate a significant amount of refactoring. Unless there are unforeseen factors at play? ...

What are the most effective techniques for utilizing JavaScript modules in both the Server and Browser environments?

Currently, I am in the process of developing a JavaScript project that utilizes NodeJS. There are certain objects that need to be shared between the client and server side. I attempted to employ the module system in Node, but struggled to find an appropria ...

"Exploring the world of ThreeJS Hemis

Just a quick question - I'm attempting to create a 3D hemisphere in ThreeJS. I've managed to make a hemisphere using the Circle or CircleBuffer geometry, but there's an issue with the flat side being empty. I've tried adding a circle ...

Create an object name in an Angular factory or service by utilizing the initial and final dates contained within an array

I have a method in my Angular service/factory that accepts an array of arrays containing objects [[{},{}],[{},{}]] as a parameter. The parameter structure consists of arrays representing weeks, with each day's object containing a date and an integer ...

Transferring JSON data to a non-RESTful WCF service

I am looking to implement a JavaScript function that can send an object as JSON to a WCF service for saving. Here is the current JavaScript code: <script> $(document).ready(function(){ $("#submitButton").click(function() ...

Unseen related model fields

I am struggling to figure out what is causing an issue in my code. Can anyone explain why the fields in locations = Location.objects.filter(user=add_profile.user) are not showing up on my html page? models.py class Location(models.Model): user = mode ...

Having issues with ng-view in AngularJs - it's not functioning properly

I am having trouble with the ng-view directive not working. When I implement it, all I see is the "Page" title. Can someone help me diagnose the issue? https://jsfiddle.net/dsgfdyp1/3/ <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/b ...

Move your cursor over an image within a div container

After not finding any helpful answers on this topic, I've decided to ask for help again. My issue involves having an image inside a div. <div id ="gratterlendis"> <a href ="?page_id=8"><img src="img/gratterlendis.png" align="right" wid ...

Automatically focus on new page when button is clicked (in a separate HTML file)

I successfully added auto-focus functionality to a button that opens a modal using the code below: Created with AngularJS: app.directive('autoFocus', function($timeout) { return { restrict: 'AC', link: function(_sc ...

Angular Pagination: Present a collection of pages formatted to the size of A4 paper

Currently, I am working on implementing pagination using NgbdPaginationBasic in my app.module.ts file. import { NgbdPaginationBasic } from './pagination-basic'; My goal is to create a series of A4 size pages with a visible Header and Footer onl ...

I'm looking to mirror images within the Bootstrap framework - any suggestions on how to achieve this using jQuery

When hovering over the image, it should flip to reveal text or a link: <div class="clearfix visible-xs"></div> <div class="col-md-3 col-sm-3 col-xs-6"> <div class="speaker-item animated hiding" data-animation="fade ...

Trouble with UpdatePanel: Why isn't the content page running javascript?

I am facing an issue with a gridview, bootstrap modal that is nested inside an update panel on a content page referencing a master page. The gridview comprises of 3 columns and a linkbutton. Even though I expect the javascript to be triggered when the Li ...

The task "default" is not found within your current gulpfile configuration

After running gulp in my console, I encountered the following error: Task 'default' is not in your gulpfile I double-checked my gulpfile and it appears to be correct: var gulp = require('gulp'), LiveServer = require('gulp- ...

Setting the date in a datetimepicker using the model

I've encountered an issue while trying to utilize the angular date time picker. It seems that when I load data from the model, the picker does not bind the value correctly. If I manually set the value to a date, it works fine. However, when the data ...

Having trouble getting the card to adapt to different screen sizes on mobile devices

Can someone please take a look at this website? It seems to display correctly and function well when viewed in full size on a browser, but for some reason, when I try to access it from a mobile device or using the Chrome device emulator, both the bootstra ...