0

My first foray into writing jQuery functions.

I have this function, but I'm not sure why the overlay var has to be outside the scope of the click function. I tried it within but it doesn't work right. Can I refactor this to make it better?

(function($) {
  $.fn.popOver = function() {

    // Variable for overlay
    var overlay = $("<div id='overlay'></div>");

    // Listen for clicks
    return this.click(function(e) {

      // Prevent the anchor link from loading
      e.preventDefault();

      // Variable for popover
      var popover = $(this).next();

      // Append the overlay to the document body
      $('body').append(overlay.click(function() {
        overlayHide();
      }))

      //Set the css and fade in our overlay
      overlay.show();
      popover.fadeIn(150);

      // Listen for clicks on elements
      popover.find('a').click(function() {
        overlayHide();
      })

      // Hide Overlay function
      function overlayHide() {
        overlay.remove();
        popover.fadeOut(150);
      }

    })
  }
}) (jQuery);
5
  • Better means shorter? Do yo have any problems with this code? Commented Dec 19, 2010 at 0:15
  • 2
    It'd be nice if you could indent your inner functions for better readability. Commented Dec 19, 2010 at 0:16
  • @deceze Right, the lack of indentation just made me miss the main click() handler :( Commented Dec 19, 2010 at 0:18
  • 3
    I fixed the indenting; it was hurting my brain Commented Dec 19, 2010 at 0:18
  • yea thanks. sorry about that. Commented Dec 19, 2010 at 0:28

1 Answer 1

1

Because you are not doing anything more specific than simply calling that other function, you can change lines like this...

popover.find('a').click(overlayHide);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.