Jquery focusout issues

263 views Asked by At

I have a popup box that appears after x time, within it is a html form and two text inputs.

I am trying to get a focus listener to close the popup as soon as the user clicks outside the popup.

to do this I have tried setting a focusout on the whole form. This successfully registers when both of the inputs looses focus however it is also registering when it is switching focus from one input to the other.

This of course closes the popup without allowing a the user to fill in the form.

HTML below

<form class="emailForm" name="signup" method="post" >
                Email address<br />
                <input type="text" id="rm_email" name="rm_email" />
                <br />
                First name<br />
                <input type="text" id="rm_first_name" name="rm_first_name" />
</form>

And the script

$('.emailForm').focusout(function() {

        //alert("focus lost");
        $('#emailPrompt').fadeOut("fast");

});

Here's the site live if that helps (the popup will appear after a short period)

http://masterzangetsu.eu/

3

There are 3 answers

0
Mark S On BEST ANSWER

You need to handle this on click(), as you've said, "close the popup as soon as the user clicks outside the popup".

This should do it:

$('body').on('click', function (e) {
    var popup = $('#emailPrompt');
    /*if the click target is NOT the popup box 
    nor its children elements*/
    if (!$(e.target).closest(popup).length) {
        popup.fadeOut('fast');
    }
});

Here's the demo.

Ref: event.target , closest()

0
Frank Conry On

This is kind of hacky but you could try:

$('.emailForm').focusout(function() {

        sleep(2000);    //2 seconds
        if(!$('.emailForm').is(":focus"))
        {
            $('#emailPrompt').fadeOut("fast");
        }

});
0
wrydere On

I'd recommend binding the fadeOut to a different event - perhaps when the user clicks outside the popup/modal, or when the user clicks a close or submit button?

You could bind the click event to the body, or to an overlay if your modal dialog has such a thing.

Check out this answer for an example of how to implement those ideas: How to close a modal by clicking outside the modal window?