0

This script allows you to click an element all you want, but when you click anything but that element, it fades something out. In my code below I can click all I want inside of $('.wrapper') and nothing happens, but when I click anything outside of that element, I have $('.popup') fadeOut.

(function hideElementOnOffClick(elementWrapper, elementToHide) {

    $(document).bind('click', function(evnt) {
        var $target = $(evnt.target);

       if ($target.is(elementWrapper) || elementWrapper.has(evnt.target).length) {
            return;
        }

        elementToHide.fadeOut();
    });
})(); 

then I call the function with the two element classes in it:

hideElementOnOffClick($('.wrapper'), $('.popup'))

It works find if I use $('.wrapper') instead of elementWrapper and $('.popup') instead of elementToHide, but when I make it into something I can call on in different places with different classes, it doesn't.

How do I fix the parameters so that this works? ​

1 Answer 1

3

You could use .stopPropagation() to stop event propagation, this make your code more clear.

function hideElementOnOffClick(elementWrapper, elementToHide) {
    elementWrapper.click(function(e) {
        e.stopPropagation();
    });
    $(document).click(function(e) {
        elementToHide.fadeOut();
    });    
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.