How to trigger an event on exit of div container using jquery

So, I have a working version of this here: http://jsfiddle.net/yEmvm/19/

When you click on the company of the first address block and then click on the name it fires the event and says invalid address. I don't want to fire that event until I cilck on company for the second address block or anywhere outside that first address block. I cannot figure out another event to trigger this on.

This is just an example. This page will contain an unknown number of address blocks from 3 to 99. Also, it will contain many more fields for a full address. The user can keep adding more with a button. However, class and id name structure is consistent.

Answers


You should run your code in a timeout, and cancel timer on focus:

$('.address').each(function()
{
    var timer;

    $(this).find('input').blur(function()
    {
        timer = setTimeout(function()
        {
            var verified = false; // run your verification here

            if ( ! verified )
            {                
                // run code here to display error
            }
        }, 0);
    })
    .focus(function()
    {
        timer && clearTimeout(timer);
    });
});‚Äč

Here's a very basic example: http://jsfiddle.net/U6TRj/3/


Explanation:

Basically, if you're clicking on an input element while being focused on another input, the browser will first fire the blur event on the old element, then the focus event on the new element.

What we're doing here with the timeout (no delay required), is pushing the execution of the code down the stack, so that it executes after the focus event handler. That way, we can cancel it's execution from within the focus callback.


This is behavior is noted on the jQuery API documentation for .focusout() http://api.jquery.com/focusout/#dsq-comment-108827731

Perhaps the plugin suggested there could help your problem: http://archive.plugins.jquery.com/project/focus


Need Your Help

Swift pods in Swift project

ios xcode swift cocoapods

I need import Swift pod to my Swift project and I faced to a problem.

Start external activity while phone is locked

android lockscreen android-windowmanager

I want to be able to start an Activity that is not part of my app while the device is password locked. How could I do this, if it's even possible?