javascript – jQuery event when clicked AND link-ThrowExceptions

Exception or error:

The title is a bit confusing but here’s what I want to do -> There’s a picture. When you click on it, a lightbox pops up (I already have that event). However, if you right click it and open in a new tab, I want a page to appear. Instagram has something similar to what I’m looking for. <a href=""> doesn’t work – it executes both (launches the lightbox and redirects). How do I do that? Is there a way to cancel the href? Thanks.

EDIT: Here’s a visual: http://jsfiddle.net/9VFGS/. In that case, I only want the alert() to be invoked when I click on it, but when I open it in a new tab, I want it to navigate to google.com.

How to solve:

Using event.preventDefault() (doc) in the event handler for triggering your lightbox will prevent the link from executing and changing your window location. Right-click context actions should still work, though, because they don’t trigger click events.

$( '#my-link' ).on( 'click', function( event ) {

    event.preventDefault();

    // do my lightbox stuff here

} 

###

Yes, set href="..." to href="#".

Leave a Reply

Your email address will not be published. Required fields are marked *