Ryan Grush
Ryan Grush

Reputation: 2128

Keep <div> and its children in focus until focus out of <div>

I've seen similar topics posted on SO but mine is slightly different. I'm trying to keep my parent DIV (and children) in focus until I focus out of the div, and it seems surprisingly hard to accomplish.

This solution I thought would work but it looks to only applies to sibling elements and not the actual div itself.

Here's a demo of what I'm trying to do http://jsfiddle.net/nosfan1019/9Eg3k/3/. I need it so you can click on the gray portion and not have it disappear.

Upvotes: 3

Views: 7522

Answers (2)

Jared Farrish
Jared Farrish

Reputation: 49198

This is a bit of a more literal approach than the other answer, but for completeness seems relevant as it does one more thing: Autofocus back to the input. It could be useful, although the other answer is probably easy enough.

$(function() {
    var $divs = $('div'),
        $entered = null;

    var on = function() {
        var $target = $(this);

        _off();

        $entered = $target.parent().addClass('on');
        $target.siblings('span').text(' triggered');
    };

    var focus = function(){
        $(this).find('input').focus();
    };

    var off = function() {
        if ($entered !== null && $(this).parent().is($entered)) {
            return;
        }

        _off();
    };

    var _off = function(){
        $divs.removeClass('on').children('span').text('');
    };

    var entered = function(e){
        if (e.type == 'mouseenter') {
            $entered = $(this);
        } else {
            $entered = null;
        }
    };

    $divs.find('input').focus(on).blur(off);

    $divs
        .attr('tabindex', -1)
        .bind('mouseenter mouseleave', entered)
        .bind('focus', focus);
});

http://jsfiddle.net/userdude/34HLU/2/

Upvotes: 1

A.M.K
A.M.K

Reputation: 16795

Okay, I think that this is what you want:

Demo: http://jsfiddle.net/SO_AMK/GNfzw/

HTML:

<div>
    <input type='text'>
    <span></span>
</div>

<div>
    <input type='text'>
    <span></span>
</div>

<div>
    <input type='text'>
    <span></span>
</div>

CSS:

div {
    margin: 20px;
    padding: 10px;
    outline: 0;
}

jQuery:

$(function() {
    $('div input').parent().attr("tabindex",-1).focus( function() {
        $(this).css('background','#eee');
        $(this).find('span').text(' triggered');

        $(this).focusout(function() {
            $(this).children('span').empty();
            $(this).css('background','white');

        });            

   });
    $('div input').focus( function() {
        $(this).parent().css('background','#eee');
        $(this).siblings('span').text(' triggered');

        $(this).parent().focusout(function() {
            $(this).children('span').empty();
            $(this).css('background','white');

        });            

   });

});

It could probably be more efficient but it seems to work.

Upvotes: 3

Related Questions