How can I delay the loading of a link until the pop-up is closed?

I have successfully implemented a pop-up on my website, but I am facing an issue where I need to prevent any linked pages from loading until the visitor clicks on the accept button. However, I am struggling to make it function as intended.

Below is the snippet of my document body along with the JavaScript code. If anyone has a solution to this problem, I would greatly appreciate it.

<body>
    <!-- Add more sections as needed -->
    <!-- Popup -->
    <div id="popup" class="popup">
        <div class="popup-content">
            <span class="close-button" onclick="closePopup()">&times;</span>
            <p>This is a confirmation message before navigating to another section.</p>
            <button onclick="closePopup()">Accept</button>
        </div>
    </div>

    <script>
        // Function to display the popup
        function showPopup(linkHref) {
            const popup = document.getElementById("popup");
            const popupContent = document.querySelector(".popup-content");
            
            // Set up the link to navigate to after closing the popup
            popupContent.querySelector("button").onclick = function () {
                window.location.href = linkHref;
            };
            
            popup.style.display = "block";
        }
        
        // Function to close the popup
        function closePopup() {
            document.getElementById("popup").style.display = "none";
        }
        
        // Add click event to the navigation links
        const navLinks = document.querySelectorAll("summary");
        navLinks.forEach((link) => {
            link.addEventListener("click", (event) => {
                event.preventDefault(); // Prevent default navigation
                const linkHref = link.getAttribute("href"); // Get the link destination
                showPopup(linkHref); // Display the popup and save the link destination
            });
        });
    </script>
</body>
</html>

I attempted to use the event.preventDefault(); function to stop the loading, but unfortunately, it did not work as expected.

Answer №1

Utilize bufferization to activate/deactivate all document hyperlinks.

class LinkActivator{
  
  constructor(){
    this.activated=true;
    this.buffer=[];
  }
  activate(){
    if(!this.activated){
      this.activated=true;
      this.buffer.forEach(d=>{
        d.dom.href=d.href;
      });
      this.buffer=[];
    }
  }
  deactivate(){
    if(this.activated){
      this.activated = false;
      this.buffer  = Array.from(document.querySelectorAll('a'))
      .map(dom=>{
        const obj={dom,href:dom.href};
        dom.href='#';
        return obj;
      })
    }
  }
}

const linkActivator=new LinkActivator();
<a href='https://duckduckgo.com/' target='_blank'>duckduckgo</a>
<br/>
<a href='https://wikipedia.org/' target='_blank'>wikipedia</a>
<hr/>
<button onclick='linkActivator.deactivate()'>deactivate links</button>
<button onclick='linkActivator.activate()'>activate links</button>

Answer №2

It is recommended to store the link in a "data-" attribute instead of using the href attribute. See the example below:

<a class="summary" href="javascript:;" data-href="https://google.com">Go to Google</a>

Here is the JavaScript code:

 const navLinks = document.querySelectorAll(".summary");
        navLinks.forEach((link) => {
            link.addEventListener("click", () => {
                const linkHref = link.dataset.href; // retrieve the link from data-href attribute
                document.getElementById('accept-btn').setAttribute("href", linkHref); // set the link for the accept button in the pop-up dialogue
            });
        });

This is the pop-up HTML structure:

<div id="popup" class="popup">
        <div class="popup-content">
            <span class="close-button" onclick="closePopup()">&times;</span>
            <p>This is a confirmation message before navigating to another section.</p>
            <a id="accept-btn" href="">Accept</a>
        </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

Adjusting the alignment of the horizontal bars in react-chartjs-2

I have configured the graph with the following settings: { type: 'horizontalBar', indexAxis: 'y', barThickness: 12, scales: { x: { suggestedMax: 6, suggestedMin: 0, grid: { display ...

Can you explain what is meant by an "out of DOM" element?

I'm feeling a bit lost when it comes to DOM nodes and all the terminology surrounding them. Initially, I believed that the DOM consisted solely of what I could see in my inspector - nothing more, nothing less. However, I've come across functions ...

chosen selection from AngularJS dropdown

I'm really struggling with something. Currently, I am working on a web app using AngularJS where I have created a table displaying database results. Each row in the table contains a select item loaded with a model. However, I am unsure how to mark a ...

The functionality of changing the checkbox to "checked" by clicking on the span is not

How can I create a toggle button with a checkbox using css and jquery? Clicking on the span representing the toggle button should change the checked property of the checkbox. Currently, the span does not change the property, even though it triggers the c ...

Shifting annotations on a Bar Graph featuring Negative Values on Google's Chart Maker

Incorporating google charts into my MVC project. Looking to create a bar chart that accommodates negative values. Desire annotations on the same side as the end of the bar for negative values (similar to positive values shown in the green box below). ht ...

Tips for transforming a scroll element into the viewport using Angular 2+

This is a sample Here is a component with a list of items: class HomeComponent { text = 'foo'; testObject = {fieldFirst:'foo'}; itemList = [ '1', '2', '3', & ...

Is there a compatibility issue between Vue particles and my project?

Greetings to all! I recently added Vue Particle to my Vue project, but encountered an issue while importing VueParticles in the Main.js file. Here is a snapshot from my terminal for reference. https://i.stack.imgur.com/Bxh2r.png ...

Ways to verify the timeframe between two specific dates

Having two distinctive arrays: accomodation: [ { id: 1, name: "Senator Hotel Fnideq", address: "Route de Ceuta, 93100 Fnidek, Morocco", checkin: "September 1", fullCheckinDate: "2021-09-01", ...

Issue with BackboneJS TypeError

I attempted to use the example below, but I encountered an error stating "TypeError: _.has is not a function". Example: I have experimented with different versions of jQuery and Backbone (uncompressed), yet the same error persists. Can anyone offer assis ...

Guide on choosing the filename for downloads in Front-End applications

UPDATE: Creating a Blob from a base64 string in JavaScript I'm currently working on a feature where a user can click a button to download a file from its DataURL. However, due to Chrome restrictions on building <a> links, I encountered an err ...

How can you decode JSON using JavaScript?

Need help with parsing a JSON string using JavaScript. The response looks like this: var data = '{"success":true,"number":2}'; Is there a way to extract the values success and number from this? ...

Issue with confirming deletion of tabulated records

HTML Code: <td>random_data_1</td><td><button id="random_data_1"></button></td> <td>random_data_2</td><td><button id="random_data_2"></button></td> <td>random_data_3</td ...

Adjust the quantity of images shown in the Flex Slider carousel

My website includes a flex slider with a carousel, but it seems that I did not configure the properties of the slider correctly (or it could be a CSS issue) as shown here: . The last image in the carousel is only partially visible. While I am able to clic ...

Instructions for attaching an event listener to a Threejs Mesh Object with the help of threex dom events

var domEvents = new THREEx.DomEvents(camera, view.domElement); var div = document.createElement( 'div' ); div.setAttribute('data-remove','mesh1'); div.className = 'close-me'; var label = new THREE.CSS2DObje ...

Bootstrap - Utilizing a boxed grid within a div located in the .fluid-container

Can you please review these two images? I'm trying to place ".myDivInTheGrid" inside a boxed bootstrap div. Any ideas on how to do this? This is what I currently have... <div class="fluid-container"> <div class="col-md-6"></d ...

Using Angular2, you can dynamically assign values to data-* attributes

In my project, I am looking to create a component that can display different icons based on input. The format required by the icon framework is as follows: <span class="icon icon-generic" data-icon="B"></span> The data-icon="B" attribute sp ...

Having trouble uploading my confidential npm package to a secure Nexus repository

I have my own personal collection of books and I am looking to share it by publishing an npm package to a private Nexus registry Here is my package.json setup { "name": "@uniqueorganization/the-collection", "version": ...

What is the correct syntax for declaring a variable within a switch statement in TypeScript?

How can I properly use a switch statement in TypeScript to assign a new variable a value? For example: let name: string switch(index) { case 0: name = "cat" case 1: name = "dog" .... } I keep getting the err ...

Is it better to Vuex - manipulate store item twice, trigger new items, or perform transformations within components each time they are mounted?

I am considering performing two separate transformations on a single, large store item and then saving the results as two new store items. For instance: setEventsData: (state, data) => {...} // main huge master object // perform transformations on it an ...

After refreshing the page, the JQuery radio button will still be selected

In my form, a radio button triggers an additional text field based on user selection. To achieve this functionality, I am using the following jQuery script: $(document).ready(function(){ $('input:radio[name="accountType"]').change(function() ...