Jacobo Koenig Jacobo Koenig - 1 month ago 5
HTML Question

Open modal from outside of HTML

I am following a tutorial to create a simple modal, but the instructions explain how to open it from a button within the HTML that calls it.

<html>
<head>
</style>
<!-- Don't forget to include jQuery ;) -->
<script src="jquery.modal.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>

<!-- Modal HTML embedded directly into document -->
<div id="ex1" style="display:none;">
<p>Thanks for clicking. That felt good. <a href="#" rel="modal:close">Close</a> or press ESC</p>
</div>

<!-- I WANT TO ACTIVATE THIS ACTION FROM A JAVASCRIPT FILE -->
<p><a href="#ex1" rel="modal:open">Open Modal</a></p>

</body>
</html>


If I wanted to open it from a linked js file, how could I do it?

K48 K48
Answer

Universal solution

For simplicity, assign an ID to that event:

<a id="testID" href="#ex1" rel="modal:open">Open Modal</a>

Then just trigger a click on that element.

JQuery:

$("#testID").click();

JQuery-Modal specific solution

Just call this to open a modal:

$("#testID").modal();

And to close programmatically, assign the ID "testClose" to some element within the modal, and run this to close the modal:

$("#testClose").modal({closeExisting: true});

Possible improvement for more nuanced control

I noticed that jquery-modal uses custom events such as "modal:open", so theoretically you could also call this:

$("#testID").trigger("modal:before-block");
$("#testID").trigger("modal:block");
$("#testID").trigger("modal:before-open");
$("#testID").trigger("modal:open");

However, this one did not work for me. Just use .click().