Opening modal on page load

2019-07-12 19:34发布

问题:

I am using a animatedModal.js to display full screen modal on my page. It works properly and is triggered by clicking on a button.

But, instead of that, i would need it to open automatically once the user enters the site, aka, it needs to be opened before the main page content.

This is the markup:

<!-- MODAL STARTS -->
<a id="demo01" href="#animatedModal">DEMO01</a>
    <div id="animatedModal">
        <div class="close-animatedModal"> 
            CLOSE MODAL
        </div>
        <div class="modal-content">
        </div>
    </div>

<!-- PAGE CONTENT -->
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit</p>

And it is triggered by

$("#demo01").animatedModal();

Fiddle can be found at https://jsfiddle.net/5zLe3npu/

What would be the best solution to display it first, before the content? I am a JS newbie so sorry for potentially stupid question.

回答1:

You could use the .on method to specify what to do on-click of the close button, such as showing the content. And to hide the content initially you could just use style='display:none;' on a containing the content.

HTML -

<!-- MODAL STARTS -->
<div id="animatedModal">
    <div class="close-animatedModal"> 
        CLOSE MODAL
    </div>
    <div class="modal-content">
    </div>
</div>

<!-- PAGE CONTENT -->
<div id='container' style='display:none;'>

    <a id="demo01" href="#animatedModal">DEMO01</a>

    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit</p>

</div>

JQuery -

$("#demo01").animatedModal(); //initialize animatedModal
$("#demo01").click(); //triggers opening of Modal.
$(".close-animatedModal").on( "click", function() {
    $("#container").show();
});

Please see JSFiddle - http://jsfiddle.net/w1gw64aj/

If this answers your question, please mark this as the accepted answer.



回答2:

Use trigger() API Documentation

Try this

$("document").ready(function() {

        $("#demo01").animatedModal();
        $("#demo01").trigger('click');

});

Demo Here