javascriptjquerymodal-dialogbpopup

Loading multiple Ajax html in modal boxes


I'm using a jquery script by http://dinbror.dk/bpopup/ to open an html file in a modal box.

The HTML:

   <button id="my-button">Pop it Up</button>

    <div id="element_to_pop_up">

    <!-- Ajax Javascript that supposed to popup in modal-->
  <script>
    $(document).ready(function() {
    $('#my-button').bind('click', function(e) {

            // Prevents the default action to be triggered. 
            e.preventDefault();

            // Triggering bPopup when click event is fired
            $('#element_to_pop_up').bPopup({
                contentContainer:'.content',
                loadUrl: 'test.html' //Uses jQuery.load()
            });
        });
    });
    </script>
    </div>

But I would like to extend this script so that I can open multiple ajax modals in a page, is there a way to bind this script together without duplicating this code over and over again for every ajax file to open?

Your help highly appreciated


Solution

  • Your question isn't that specific.

    Is each one going to load from a different URL?

    This may or may not be the answer you are looking for:

    $(document).ready(function() {
    $('.my-button').bind('click', function(e) {//select all the buttons with a class selector
    
            var loadFile = $(this).data("file");
    
            // Prevents the default action to be triggered. 
            e.preventDefault();
    
            // Triggering bPopup when click event is fired
            $('#element_to_pop_up').bPopup({
                contentContainer:'.content',
                loadUrl: loadFile //Uses jQuery.load()
            });
        });
    });
    

    //your html:

    <button data-file="test1.html" class="my-button">Load one modal</button>
    <button data-file="test2.html" class="my-button">Load another modal</button>
    <button data-file="test3.html" class="my-button">Load a third modal</button>
    

    I'm assuming that your plugin bpopup can be used multiple times. I have't tested it.

    BTW I don't know why your script block occurs within the div with id 'element_to_pop_up'. It doesn't need to be an it makes the code harder to read.