Mr.Devops
Mr.Devops

Reputation: 306

How to open a modal on an element when the page loads?

I am trying to call the specific link id #ext when page loads instead of clicking it manually to show the modal popup. However I am not able to achieve it. Can someone look into code and suggest a change?

<!-- Modal HTML embedded directly into document -->
<div id="ex1" class="modal">
<a href="https://www.siteallow.com"><img src="image.jpg" /></a>
</div>

<!-- Link to open the modal -->
<p><a href="#ex1" rel="modal:open" onload="loadImage()">Open Modal</a></p>

The above code works fine when I do click on the link on the page "Open Modal". I want it to be called when page is loaded to show popup auto.

JSfiddle

Just for reference I am using this to show a modal popup: https://jquerymodal.com/

Upvotes: 2

Views: 504

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337714

From the documentation:

You can manually open a modal by calling the .modal() method on the element:

As such you just need to call the modal() method on $('#ex1') when the page loads:

jQuery(function($) {
  $('#ex1').modal();
});

jQuery(function($) {
  $('#ex1').modal();
});
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.css">
<div id="ex1" class="modal">
  <a href="https://www.example.com"><img src="image.png" /></a>
</div>
<p>
  <a href="#ex1" rel="modal:open" onload="loadImage()">Open Modal</a>
</p>

Upvotes: 4

Related Questions