'JavaScript button function result after page reloading

I have a login and register modal and these modals share one same attribute, so I wanted to create an onclick function for each of the modals' submit buttons to trigger errors in respective modals. I tried this code to see if the button can trigger for the modals to show,

function loginModal(){
            $('#modal-register').modal('show');      
   }
    
   document.getElementById("modal-login-btn").addEventListener("click", loginModal);

and it does, however it only works before the page reload, as when i click the submit button, the page will reload. I want the modal to show after the page reload. I also tried this but it doesn't work.

$(document).ready(function(){
        function loginModal(){
            if (count($errors) > 0){
                $(document).ready(function(){
                    $('#modal-login').modal('show');
                });
            }        
        }
    });
    
    document.getElementById("modal-login-btn").addEventListener("click", loginModal);

Does anyone have any idea how to make the function run after page reload?



Solution 1:[1]

You can use a GET value at the url of the page when the page reload:

  1. you can set the url in javascript at the moment of reload

for example

window.location.replace(window.location.href+"?reloaded=true");

  1. implement a function who detect if the url contains a reload GET value.

  2. if the GET value exist, show the modal directly.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Brahim Aimen