Search code examples
jqueryfancyboxstoppropagation

Can't get fancybox link working inside toggle down box


Here is my problem. I have some custom jquery written to toggle down a login form on my site. I then added some code I found here to close that box if you click off it.

The problem comes in because I have a link to a fancybox inside this div that toggles in/out. Because i'm using event.stopPropagation(); along with the clickoff, it messes with that fancybox link. Full code example is below.

//Login Toggle
    $('a.login').click(function() {
        if ($('.login-box').is(':hidden')){
            $('.login-box').fadeIn('normal');
            $('span.arrow-up').fadeIn('normal');
            $(this).text('Close');
        }
        else{
            $('.login-box').fadeOut('normal');
            $('span.arrow-up').fadeOut('normal');
            $(this).text('Log-In');
        }
    });
    //Close when click off login
    $('html').click(function() {
        $('.login-box').fadeOut('normal');
        $('span.arrow-up').fadeOut('normal');
        $('a.login').text('Log-In');
    });
    //Exclude these divs, so clicking inside them won't close login
    $('.login-box, a.login, span.arrow-up').click(function(event){
        event.stopPropagation();
    });

    //Forgot Password Fancybox
    $("a.fancybox").fancybox({
        maxWidth    : 800,
        maxHeight   : 600,
        fitToView   : false,
        width       : '70%',
        height      : '70%',
        autoSize    : false,
        closeClick  : false,
        openEffect  : 'fade',
        closeEffect : 'fade'
    });

If I take out the stopPropagation, everything works as expected (the fancybox button works), I just lose the ability to close the login box by clicking outside of it. Can anyone help me with a smarter way of writing it that doesn't break the fancybox functionality?


Solution

  • event.stopPropagation() is preventing the event from reaching the handler that is set by fancybox

    You need to allow events targeting a.fancybox to continue propagating

    $('.login-box, a.login, span.arrow-up').click(function(event){
        if ($(event.target).hasClass('fancybox') == false) {
            event.stopPropagation();
        }
    });
    

    This will allow events to propagate for any elements that have the class 'fancybox'


    This is unrelated to your problem, but I would suggest that you add event.preventDefault() or return false to click handlers for links