0

I've tried the following on JSFiddle:

HTML:

<div id="dialog" title="Basic dialog">
  <p>Hello.</p>
</div>

<a href="www.google.com">Link</a>

JavaScript

$(document).ready(function() {
    $( "#dialog" ).dialog({ autoOpen: false }); 
    $(document.body).on('click',"a",function(event){ 
        if ($(this).hasClass('ui-dialog-titlebar-close')) return;
        event.preventDefault();        
        $("#dialog").dialog('open');
    });  
});

I want to achieve this same functionality, but by creating the dialog via JavaScript. That is, I don't want to have the <div id="dialog" ...> in the HTML. How can I do that?

1
  • You can have your HTML loaded via JavaScript onLoad
    – u54r
    Sep 8, 2013 at 0:38

2 Answers 2

3

You can create the dialog on click rather than just showing the dialog. Here's an example on jsfiddle.

Basically you create the DOM node and apply the dialog directly through it. That's what can be done with the $(HTML HERE).dialog() method.

1

You can add your own custom HTML statically and .append() it to the body element or some other div, like in this jsFiddle.

You'll have to position and style it yourself (either by giving it proper CSS classes or by using the style attribute). You can use your browser Developer Tools to take a peek at the jQuery-UI dialog div and "borrow" its CSS for position/style hints =) Although I highly recommend just using the jQuery UI dialog (as it handles the open/close aspects, has the option for a background modal, buttons, etc.). That's what the library is for! ;)

You can also dynamically retrieve the HTML in various ways, e.g. AJAX or many other methods.

3
  • I think your jsFiddle as the same code as mine. Perhaps you linked to the wrong one?
    – Mika H.
    Sep 8, 2013 at 1:01
  • @MikaH. Oops, sorry! Although I highly suggest claydiffrient's answer! It's much better because it uses the jQueryUI framework. Unless you wanted to do away with jQueryUI? Let me know and I can find the right jsFiddle, if not I think I may just delete my answer =)
    – lebolo
    Sep 8, 2013 at 1:04
  • I'm happy with jQueryUI. Yes, claydiffrient's answer looks great. I'll vote your answer up anyway (Please correct the jsFiddle link). Thanks!
    – Mika H.
    Sep 8, 2013 at 1:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.