Show a dialog with jQuery?

0

I have the following html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
    <body>
        <dialog id="my-dialog"></dialog>
        <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script><scripttype="text/javascript">
            $(document).ready(function () {
                $('#my-dialog').showModal();
            });
        </script>
    </body>
</html>

I can open the dialog with the following javascript:

document.getElementById("my-dialog").showModal();

But I did not find a way to open the modal using jQuery, I already tried this:

$('#my-dialog').showModal();

But I get the following error:

Uncaught TypeError: $(...).showModal is not a function

Is there a way to open a dialog using jQuery?

    
asked by anonymous 17.08.2017 / 14:26

2 answers

1

Hello,

Your first example ( document.getElementById("my-dialog").showModal(); ), you search the DOM with JavaScript, which returns 1 JavaScript element and calls the showModal method.

Your second example ( $('#my-dialog').showModal(); ), you search the DOM with jQuery, which returns a collection of jQuery elements and tries to call the showModal method in this collection of jQuery elements, but in this case this method does not exist in jQuery objects, thus returning the error.

Two possible solutions in principle:

First possible solution

Access the first JavaScript element that is "inside" the jQuery collection, since its search is by ID and should always return 1 element. You can do this as if it were an Array:

$('#my-dialog')[0].showModal();

In this case, if your selector does not return elements (the ID does not exist in the DOM for example) this code will return error, because the position "0" will not exist, since the collection will be empty. This case can be handled by something like this:

if($('#my-dialog').length > 0) {
    $('#my-dialog')[0].showModal();
}

Second possible solution

Create this "method" in jQuery.

According to documentation :

(function( $ ){
   $.fn.showModal = function() {
      this[0].showModal();
      return this;
   }; 
})( jQuery );

And you can do:

$('#my-dialog').showModal();
    
17.08.2017 / 14:53
0

Via javascript you can try $('#my-dialog').modal('show'); .

Look at this answer if you need it.

    
17.08.2017 / 14:31