简体   繁体   中英

How to activate Bootstrap 4 modal by clicking a button in the first page, that redirects you to a second page with modal activated?

For my project, I want to implement a modal . I am using Bootstrap 4 . The modal should work as following:

  • When I press the button in the first .html page, the button should redirect me to a second .html page, meanwhile open a modal in that second .html page as a welcoming.

So the modal in that case is like a welcoming message as a popup box.

To make things clear. The button "code" is in the first .html file, the modal "code" is in the second .html file.

Button:

<a href="index.html"><button class="btn btn-primary btn-lg btn-block text-uppercase" type="button"
        data-toggle="modal" data-target="#modalLogin">Prijavi se</button></a>

Modal:

<div class="modal fade" id="modalLogin" tabindex="-1" role="dialog" aria-labelledby="modalLoginLabel"
    aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalLoginLabel">Pozdravljeni!</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                Dobrodošli v digitalnem gradbenem delovnem listu.
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-dismiss="modal">Nadaljuj</button>
            </div>
        </div>
    </div>
</div>

I tried everything. from id's, to trying to relocate the code, to trying to find another solution, with JavaScript, but no luck so far.

A click on your <a> cannot open a modal in another page that is about to be opened. Instead, what you do is you slightly modify the href of your <a> , for example: <a href="index.html/welcome"></a> .

Then, in your JS (that is being loaded with index.html ) you can check if there is a 'welcome' in your URL when the user navigates to the page. If there is, you trigger the modal to show. It would look something like this:

$(document).ready(function() {
    if (window.location.href.indexOf("welcome") > -1) {
        $("#modalLogin").modal("show");
    }
});

This way, when the user navigates to index.html the modal doesn't show, but if the user clicks on your button, the modal will be displayed because the URL will contain welcome .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM