views:

499

answers:

1

Hey guys.. Quick question:

I wrote a simple JS that opens lightBox for image viewing when an image link is clicked. Basically, using jQuery (yes, I was that lazy), I detect the click of an anchor tag, use a regex to make sure that the HREF attribute is to an image file, and if it is, it opens the image in lightBox. It all works fine, except one thing: The anchor needs two clicks before it will open lightBox. Why is that?

Here's the script I wrote:

    $(document).ready(function(){
 var href;
 var imageExtensions = /(.)+(.jpg)|(.png)|(.gif)|(.bmp)/;
 //On click of any link
 $("a").live("click",function(event){
  href = $(this).attr("href");
  //If the target URL is an image, use lightbox to open it
   if(imageExtensions.test(href)){
    event.preventDefault();
    $(this).attr("class","lightboxIMG");
    //Prevent the link from opening, and open lightbox
    $(".lightboxIMG").lightBox();
    $(this).attr("class","");
   }
 });
//END 
});

I don't see what could be causing the user to have to click twice to activate lightBox. If you need a sample to see what I'm referring to, I'm currently using the script in a beta of my new website: http://ctrlshiftcreate.com/photography.php?photo=6&r_folder=

Click "View full size" to see what I mean. I'd greatly appreciate any help - thanks a lot!

+4  A: 

I think what's happening is the lightbox() call only sets the anchor up to be a lightbox, it doesn't actually show the lightbox. So, the first click is saying to lightbox "make this a lightbox link", and the second click gets caught by lightbox and actually shows the lightbox.

edit Is the live aspect of it important? Or, do you plan on adding more links that you'll need to capture after the document is loaded? If live isn't important, the standard lightBox() method should be good enough to catch clicks. If it is, I'd consider writing a hookAnchors() style method that you can call after the ajaxing that simply calls lightBox() again. Something like:

$(document).ready(function() {
    hookAchors();
});

function hookAnchors() {
    var imageExtensions = /(.)+(.jpg)|(.png)|(.gif)|(.bmp)/;
    $('a')
        .filter(function() {
            return imageExtensions.test($(this).attr("href"))
        })
        .lightBox();
}

That way you can call hookAnchors inside your DOM changing code (as a result of $.get for example).

Dan F
Look at that - worked like a charm! I didn't know that lightbox caught the click on its own.If I wasn't also a guy, I'd say I love you!And yeah... I had the whole image gallery running off of AJAX before, but due to bookmarking problems and such, I changed it - that's why I still have the live() function in there.Thanks so much - that's awesome!
BraedenP
lol, no worries, glad it helped :-)
Dan F