Question

I have a Wordpress site which has a gallery on a page visible to all users.

The idea is that if a non-member clicks a gallery thumbnail, they get redirected to a signup page. If a user is logged in, the image displays in a lightbox as usual.

I'm playing with this jQuery code and can't get the preventDefault bit working - I think it's because it's inside a conditional.

$('.ngg-gallery-thumbnail a').on('click', function(event){

        if (!$('body').hasClass('logged-in')) {
            alert('Not logged in!');
            event.preventDefault();
        }
    });

Also I'm pretty sure there'll be a more secure way of doing this using PHP - if anyone can point me in the right direction I'd be most grateful!

Was it helpful?

Solution

Try like

$('.ngg-gallery-thumbnail a').on('click', function(event){
    event.preventDefault();
    if (!$('body').hasClass('logged-in')) {
        alert('Not logged in!');
        return false;
    }
    $(this).addClass('lightbox');
});

Dont give the lightbox class before,first check for the condition and then if it satisfies then add class for the lightbox

OTHER TIPS

The correct format of on() method is this:

$('.ngg-gallery-thumbnail').on('click', 'a', function(){
    if (!$('body').hasClass('logged-in')) {
        alert('Not logged in!');
        return false;
    }
    return true;
});

Also, there's no need of preventDefault() method here, since you are using return false here.

Returning false performs three tasks when called:

  1. event.preventDefault();
  2. event.stopPropagation();
  3. Stops callback execution and returns immediately when called.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top