pyguy
pyguy

Reputation: 43

go to page and open modal javascript

The goal is to go to a page and show a modal from that page.

Is there a way to have this execute after the page has successfully loaded?

//load page
window.location.href = 'foobar.html';

//wait until page is ready then open modal?
$(window).ready(function () {
  console.log('did it work?');
  $('#someModal').modal('show');
});

I listed the javascript file in the html page but this just isn't working. Everything is happening in the same document window from the initial page.

ANSWER

I decided to get the previous url and search for a substring to trigger the modal to show on the second page.

//first js script for the first html page
window.location.href = 'foobar.html';

//second js script for the second html page
$(document).ready(function () {

    var prev_url = document.referrer;

    if (prev_url.includes('substring')){
        $('#someModal').modal('show');
    }
});

Upvotes: 1

Views: 1040

Answers (3)

pyguy
pyguy

Reputation: 43

Thank you for the suggestions.

I thought of a way to get this to work! On the second page document reload, I will get the last url string and see if it contains a substring. If yes, show the modal. Seems to be working :)

$(document).ready(function () {

    var prev_url = document.referrer;

    if (prev_url.includes('substring')){
        $('#someModal').modal('show');
    }
});

Upvotes: 1

Sarai Lopez
Sarai Lopez

Reputation: 21

You should separate the scripts. 1rst page:

 $(document).ready(function () {
window.location.href="foobar.html";
});

2nd page:

 $(document).ready(function () {
     $('#someModal').modal('show');
});

I hope this works for you.

Upvotes: 0

Dave Ankin
Dave Ankin

Reputation: 1311

Unfortunately, javascript only exists in between page loads, every new page load will clear all executing javascript code. If you want to simulate a page load, you can use the History api, which will push a new entry onto the browser's back button, and then run code after that. instead of assigning values to window.location, you will need to call pushState and give it some arguments as described in the link, then proceed to call your modal code.

for example,

window.history.pushState({}, window.document.title, 'foobar.html');
$('#someModal').modal('show');

Upvotes: 0

Related Questions