Search code examples
jqueryjquery-uijquery-traversing

supporting multiple dialog boxes on web page with jquery through traversing the DOM


I have tried every combination that I can think of and for some reason can't get this code to run properly.The dialog method is correct. When i call ".dialog" directly after click without trying to traverse, everything runs fine. If I have multiple dialog boxes they will all open one after the other.

Is this possible with traversing? am I missing something?

I hope this isn't too vague, if there are any questions please let me know.

Thank you in advance for any help!

My code is below:

html:

       <div class = "opener">Click for Item Numbers</div>
        <div class = "dialog" title = "Dialog">
           Dialog box
          </div>



      <div class = "opener">Click for Item Numbers</div>
        <div class = "dialog" title = "Dialog">
           Dialog box
         </div>

jquery:

 //jquery ui dialog box

   $('.dialog').dialog({
     autoOpen: false,
     modal: true,
     show: {
       effect: "blind",
       duration: 1000
      },
     hide: {
      effect: "explode",
      duration: 1000
    }

 })

  //jquery open function for dialog

$(function() {

 $('.opener').on('click', function () {
  $(this).next('div.dialog').dialog('open');


    });
  });
});

Solution

  • The DOM gets all rearranged when you start with .dialog(). My recommendation is to save the element before creating it as a dialog, and then open it via reference.

    $(function () {
    
       $('.opener').each(function () {
           $(this).data('dialog', $(this).next('div.dialog'));
       });
    
       //jquery ui dialog box
    
       $('.dialog').dialog({
           autoOpen: false,
           modal: true,
           show: {
               effect: "blind",
               duration: 1000
           },
           hide: {
               effect: "explode",
               duration: 1000
           }
    
       });
    
       //jquery open function for dialog
    
       $('.opener').on('click', function () {
           $(this).data('dialog').dialog('open');
    
    
       });
    });
    

    See fiddle here: http://jsfiddle.net/q8m844so/