Search code examples
jqueryclicklive

jQuery live() ... have to click twice to activate links?


I have the following bit of code, simply:

$(function() {
  $('a.add-photos-link').live('click', function(e) {
    $(this).colorbox({
      overlayClose: false,
      onComplete: function() {
        $('#add_photos').submit(function(e) {
          // more stuff to do
          e.preventDefault();
        });
      }
    });
    e.preventDefault();
  });
});

However, this only seems to work after single-clicking on the link TWICE. These links are dynamically added to the page (a.add-photos-link).

Why is this happening and what can I do to fix it so it fires after the first single-click?


Solution

  • Your current code only creates a colorbox for the link. It does not open the colorbox, which is why you need to click the link twice: once to create it and again to open it.

    You can use the open option (as documented) when creating the colorbox to open it immediately, like so:

    $(this).colorbox({
      open: true,
      overlayClose: false,
      onComplete: function() {
        // ...
      }
    });