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!

有帮助吗?

解决方案

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

其他提示

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.
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top