bpopup multiple

bpopup, javascript, popup

Solution

Since you are using jquery, you should use it's on() method to attach a single listener to the parent DOM element, and use the selector parameter to properly delegate the event to it's children (the button/popups).

If this sounds confusing, a simple example might help:

HTML:

<div id="parent">
    <a href="popup1" class="button">Show popup 1</a>
    <div id="popup1" class="popup">1</div>

    <a href="popup2" class="button">Show popup 2</a>
    <div id="popup2" class="popup">2</div>

    <a href="popup3" class="button">Show popup 3</a>
    <div id="popup3" class="popup">3</div>

    <a href="http://www.google.com/" target="_blank">Non-popup link</a>
</div>

JS:

$('#parent').on('click', 'a.button', function (event) {
    event.stopPropagation();
    event.preventDefault();

    var popup = $(this).attr('href');
    $('#'+popup).bPopup();
});

This adds a single event listener on the parent element, which only gets triggered if the child element which triggered the event matches the selector (in this case `a.button`). It determines which popup to show by retreiving the popup's id from the `href` attribute.

You can see this example working here.

Problem

I'm using a lightweight jQuery popup plugin called 'bPopup'. I'm using it on my website at the moment to load multiple popup windows when clicked. I was recently told that my code was inefficient as I was loading multiple popups with multiple JavaScript 'listeners', i.e.: ``` <script type="text/javascript"> ;(function($) { $(function() { $('#my-button_1').bind('click', function(e) { e.preventDefault(); $('#element_to_pop_up_32754925023').bPopup(); }); }); })(jQuery); </script> <script type="text/javascript"> ;(function($) { $(function() { $('#my-button_2').bind('click', function(e) { e.preventDefault(); $('#element_to_pop_up_95031153149').bPopup(); }); }); })(jQuery); ``` ^^ The multiple JavaScript 'listeners'. And, for the Popups: ``` <!-- Button that triggers the popup --> <a class="main" id="my-button_1" href="#">Popup 1</a></b><br /> <!-- Element to pop up --> <div id="element_to_pop_up_1"> // ... </div> <!-- Button that triggers the popup --> <a class="main" id="my-button_1" href="#">Popup 1</a></b><br /> <!-- Element to pop up --> <div id="element_to_pop_up_1"> // ... </div> ``` He's probably right (sure of it), but not sure how to implement this, or whether this is even possible (small chance he's wrong). Help? And thanks!

Original source