Learn the process of seamlessly incorporating a spinner page into the rest of your HTML content

I'm currently working on a project involving a spinner page, but I'm facing some challenges when it comes to integrating the spinner with URL redirections. The project is centered around a multiplication program where if the answer is correct, users are redirected to one specific URL (http://stackoverflow.com), and if incorrect, they're directed to another URL (http://yahoo.com). However, before being redirected to these URLs, I'd like a spinner that I've created to display while the pages load. Can anyone provide assistance with this issue? Much appreciated!

Below is my main HTML page (index1.html):


        <!DOCTYPE html>
        <html>
        <head>
            <link rel="stylesheet" type="text/css" href="stylesheet.css">
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
            <meta charset="ISO-8859-1">
            <title>A Multiplication Game</title>
        </head>

        **<script>
            window.addEventListener("loader", function(){
                var spinner=document.getElementById("spinner");
                document.body.removeChild(load_screen);
            });
        </script>**

        <body>
            <span id="mathprompt">What is <span id="num1">8</span> multiplied by 
            <span id="num2">E</span>?
            </span>
            <br>
            <span id="inputrow">
                <input type="text" id="inputfield">
                <button id="submitbutton">Submit</button>
            </span>

            **<div class="loader" id="spinner"></div>**

            <p id="response"></p>

            <script src="script.js" type="text/javascript"></script>
        </body>
        </html>
    

Here is my JavaScript code (script.js) where I declared a variable for the spinner:


        var num1;
        var num2;
        var guess;
        var answer;
        var response;

        $(document).ready(function() {
            num1=document.getElementById("num1");
            num2=document.getElementById("num2");
            guess=document.getElementById("inputfield");
            response=document.getElementById("response");
            **spinner=document.getElementById("spinner");**

            $("#submitbutton").click(function(){
                checkAnswer();
                redirectPage();
            });

            setNumbers();
        });

        function setNumbers(){
            num1.innerHTML = Math.floor(Math.random() * 10)+1;
            num2.innerHTML = Math.floor(Math.random() * 10)+1;
        }

        function checkAnswer(){
            var n1 = parseInt(num1.innerHTML);
            var n2 = parseInt(num2.innerHTML);
            answer = n1 * n2; 

            if (parseInt(guess.value) == answer){
                response.innerHTML = "Correct!";
            } else{
                response.innerHTML = "Incorrect!";
            }
        }

        function redirectPage(){
            if (parseInt(guess.value) == answer){
                window.location.href = "http://stackoverflow.com";
            } else{
                window.location.href = "http://yahoo.com";
            }
        }
    

And here is the CSS code for the spinner in stylesheet.css:


        @charset "ISO-8859-1";

        .loader{
            border:16px solid #f3f3f3;
            border-radius: 50%;
            border-top: 16px solid #3498db; 
            width: 240px;
            height: 240px;
            animation: spin 2s linear infinite;
            margin-left: auto;
            margin-right: auto;
            text-align:center;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    

Answer №1

It appears that you are trying to determine when an external website has finished loading...unfortunately, in Javascript, you do not have direct access to the "loaded" event of an external website opened in a new tab of the browser.

Your best option is to show a loading indicator and then perform a JavaScript redirect. Once the yahoo/stackoverflow page replaces your website in the browser tab, the loader will naturally disappear...is this the behavior you are looking for?

You have 3 scenarios :

  • If you load yahoo/stackoverflow within an iframe on your webpage, you could display a loading indicator and detect when the page has loaded inside the iframe (for example, by loading a different page within the iframe first and checking if you can access its content using JS...once you cannot access it, the external page must be loaded).

  • If you are redirecting to the yahoo/stackoverflow page directly, you can only show a loading indicator before the external pages start loading.

  • Another option is to prefetch the external page, display a loading indicator, and then redirect once the page has fully loaded. This way, your browser may cache most of the HTML elements (to verify)...

    var myPrefetchedPage;
    $.ajax({
      url: "test.html",
      cache: false,
      success: function(html){
        myPrefetchedPage = html;
      }
    })
    

Preloading code within an iframe :

jQuery(document).ready(function ($) {
    $app = $('.app');
    $app.addClass('loading');

    $iframe = $('<iframe>');
    $iframe.attr({src: 'http://www.yahoo.fr/'});
    $iframe.appendTo($('body'));

    // Upon loading of <iframe>, remove loading spinner to reveal <iframe> 
    // or initiate a redirect to the page in the current browser tab.
    $iframe.load(function() {
        $('.app').remove();
        // Redirect to the actual page
        window.location.href='http://www.yahoo.fr/';
    });
});

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

In Internet Explorer, auto margins in Flexbox do not function properly when using justify-content: center

My table has cells that can contain both icons and text, with the icons appearing to the left of the text. There are different alignment scenarios to consider: Only an icon is present: The icon should be centered Only text is present: The text should be ...

Tips for showcasing axios data on Vue components

I'm just starting out with Vue.js and I'm struggling to grasp how it all works. I have a function that sends data to the server and receives a response using axios. However, when I try to display the response using a variable, something seems to ...

What steps do I need to take to create an extension that executes code within VS Code?

Invent a new interpreted language using Python. Although it functions smoothly within the terminal, I'm facing challenges in locating resources or documentation to develop an extension that can execute it within the VS code IDE. Additionally, I aim to ...

Adjust the dimensions of the text area to modify its height and width

Can someone help me adjust the width and height of the <textarea> tag in HTML so that it only has two lines (rows)? Right now, it's only displaying one line. Any suggestions on how to solve this issue? Even when I try changing the width to 1000 ...

There are various IDs in the output and I only require one specific ID

I have a JSON fetcher that is functioning properly. However, whenever I request an ID, it returns all the IDs present in the JSON data. Is there a way to retrieve only the latest ID? This is my first time working with JSON so I am still learning. $(docu ...

Having trouble with submitting a form using an external button in React?

class Index extends React.Component { state = {isLoading: false} onSubmit = (event) => { console.log('here we go'); event.preventDefault(); // this.checkEmailExistance(); }; render() { return ( ...

Should servlet response be HTML for use in AJAX calls?

I am currently in the process of developing a web application with multiple pages, including index.html which serves as the main page and contains various <a> tabs linking to different Servlet pages. As part of my design, I have a consistent CSS lay ...

The attempt to save data failed with a timed out error for Operation `todos.insertOne()` after 10000ms of buffering

const express=require("express"); const { stringify } = require("querystring"); const router= express.Router() const Db=require("../models/Db") router.get("/",(req,res)=>{ res.render("index.hbs"); }) .post("/addData",async(req,res)=>{ const ...

Building a table in Quasar by utilizing nested objects

I am currently facing an issue while using Quasar to create Q-Tables. I am struggling with incorporating nested objects with dynamic key names. Below is the content of my table: data: [ { 'FrozenYogurt' : { &a ...

JavaScript is only recognizing the initial set within an array

Recently, I created an array which contains information about different movies. Each movie includes details such as title, year, genre, and more. However, when attempting to access each movie in the list, only the first entry is recognized correctly while ...

React JS: Incorporating Multiple Placeholder Objects within Components

Apologies if this question is a duplicate, but I haven't found any helpful answers yet. I'm new to React and JavaScript. I am looking to include multiple objects inside a component: For example: src={url} name={text} subTitle={subtext} My in ...

Dealing with an endless loop caused by a promise in AngularJS's ui router $stateChangeStart event

I am currently working on implementing authentication in my Angular application and I want to redirect to an external URL when a user is not logged in (based on a $http.get request). However, I seem to be stuck in an infinite loop when using event.prevent ...

Organize your Flex-Items

Suppose there is a Flex-Box #X containing 4 Flex-Items #Y1 ... #Y4 that need to be arranged in the following manner: https://i.sstatic.net/NDix8.png If the output medium is smaller than 60em, the flex-items should be positioned like this: https://i.sstatic ...

Steps to retrieve an array from AJAX request and save it to a JavaScript variable

How can I retrieve the 'this.responseText' array from this function and assign it to a variable named 'teacherIDList'? Any suggestions? var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readySt ...

Error in Ruby on Rails: View cannot locate the path for Collection routes

I have included a collection route with POST method in my routes file. resources: curated_items do collection do post 'duplicate' end end However, I am unable to locate the path for the 'duplicate' prefix in my view.v ...

Encountering unresponsive npm behavior post-prefix modification

Recently, I attempted to update my IONIC CLI via npm. The installation was successful multiple times, but the version of CLI remained unchanged. After some research, I decided to modify the npm prefix, which resulted in the IONIC command not being found. F ...

Tips for resolving a fuzzy background image while using transform scale

Within my program, users are able to reduce the size of a specific component. I utilize transform: scale() in order to accomplish this. I have found that I am able to produce clearer images by incorporating the following: -webkit-backfa ...

What is the reason for hasChildNodes returning true when dealing with an Empty Node?

When the user clicks on purchase and the cart is empty, there should be an alert. However, it seems that no response is triggered. Upon running the program, an error message appears stating that it cannot read the property of addEventListener which is unde ...

Using Rails' link_to method within Bootstrap modals

I'm trying to implement a voting system where users can vote on different items displayed in a Bootstrap modal. Each item is listed as a button on the index page, and when clicked, it opens up the modal for voting. However, I'm facing challenges ...

The entity referred to as [object Object] lacks the capability to execute the 'addEventListener' method

When I add the most recent version of jQuery from the official site, like this: <script src="http://code.jquery.com/jquery-latest.js"></script> The issue arises on line 3 of the code below (pscript.js): function init() { $("textbox").foc ...