Search code examples
javascriptjquerymodal-dialogoverlaymaterialize

Materialize css modal open on page load with fixed nav - not working


I am using Materialize CSS and have several modals on my site. Some of them I want to open on loading a particular new page. Everything was working and then I switched to a fixed nav and all of a sudden the open commands aren't working.

It seems that the function is working but it is not changing the modal to display: block so it acts as if it is open, but nothing is visible and the body overlay has been turned on so that you can not scroll.

I have tried numerous different ways to implement the modal.open(); and from what I can tell it is that something is getting in the way of the function and overriding some of the styles.

I'm at a loss. Any help is appreciated.

<body>

<!--       NAVIGATION       --->

<header>
<div class="navbar-fixed">
    <nav>
        <div class="nav-wrapper">
            <div class="row">
                <div class="col s7 m2 valign-wrapper">
                    <a class="modal-trigger" href="#login"><img src="/images/Logo.png" alt="" class="loginLogo"></a> 
                </div>
                <div class="col s5 m3 offset-m7 valign-wrapper">
                    <ul>
                        <li><button id="successBtn" data-target="signUpSuccess" class="btn btn-signUp btn-success modal-trigger">Sign up</button></li>
                    </ul>
                </div>
            </div>
        </div>
    </nav>
</div>

<!-- Modal Structure -->

<div id="signUpSuccess" class="modal">
    <div class="modal-content">
        <div class="row">
            <div class="col s12">
                <h4>You're signed up!</h4>
                <p>We will notify you soon.</p>
            </div>
        </div>
    </div>
</div>

Javascript:

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

$(document).ready(function(){
    $("#signUpSuccess").modal();
    $("#signUpSuccess").modal("open");
});

To reiterate - The modals are still working when clicked but the #signUpSuccess modal is not opening on load and it was working prior to changing to navbar-fixed.

Materialize CSS: https://materializecss.com/modals.html

I hope this makes sense.


Solution

  • This can be done with instance.open().

    <script>
            document.addEventListener('DOMContentLoaded', function () {
                var Modalelem = document.querySelector('.modal');
                var instance = M.Modal.init(Modalelem);
                instance.open();
            });
    
    </script>
    

    Check documentation Materialize Modals, there are many options available for animations. You should also try using vanilla JS because jQuery is no longer a dependency.