Do I have to duplicate this function? - jQuery

I'm using this function to create an transparent overlay of information over the current div for a web-based mobile app.

Background: using jQTouch, so I have separate divs, not individual pages loading new.

$(document).ready(function() { 
    $('.infoBtn').click(function() {
        $('#overlay').toggleFade(400);
        return false;    
     });
 });

Understanding that JS will run sequentially when i click the button on the first div the function works fine. When I go to the next div if I click the same button nothing "happens" when this div is displayed, but if i go back to the first div it has actually triggered it on this page.

So I logically duplicated the function and changed the CSS selector names and it works for both.

But do I have to do this for each use? Is there a way to use the same selectors, but load the different content in each variation?

Answers


Would something like this work? I'm assuming what you want is for different buttons to call toggleFade on different overlay divs.

function makeOverlayHandler(selector) {
    return function() {
        $(selector).toggleFade(400);
        return false;
    }
}

$('button selector').click(makeOverlayHandler('#overlay1'));
$('another button selector').click(makeOverlayHandler('#overlay2'));

You could also change makeOverlayHandler's selector parameter to a jQuery object instead of a selector and call it like this: makeOverlayHandler($('#overlay1')).


This best way to do this is to make it all relative, so say you have markup like this:

<div class="container">
  <div class="overlay">Overlay content</div>
  <button class="infoBtn">Click to show overlay</button>
</div>

Then you can find the overlay for this button realtively, like this:

$(function() { //equivalent to $(document).ready(function() {
  $('.infoBtn').click(function() {
    $(this).closest('.container').find('.overlay').toggleFade(400);
    return false;
  });
});

You can optimize this further, e.g. .children('.overlay') if the overlay is always a direct child of container. This goes from the current button (this), finds the .container it's in using .closest() and then finds the .overlay inside of it using .find(). With this approach you have one small bit of code to handle all your bindings, much easier to maintain :)


Need Your Help