JonSnow
JonSnow

Reputation: 325

Tab through UL and close a div when tabbing out

I have the following problem:

I have a div, that can be "display: block" or "display: hidden". While it is visible it contains an unordered list in it. It is possible to tab throug the entries of the ul.

Now I want to hide the parent div as soon as the user tabs from the last li to the "outside". How can this be done?

<div class="ms-drop" style="display: block;">
    <ul>
       <li><input name="options" type="checkbox" value="A"> Typ A</li>
       <li><input name="options" type="checkbox" value="B"> Typ B</li>
       <li><input name="options" type="checkbox" value="C"> Typ C</li>
    </ul>
</div>

Currently the focus changes the bg color of the li, don't mind about that. I just need to know when the user reaches the last li and THEN hits TAB again to "step outside" (and ONLY Tab, cause he can also step back to to hitting Shift + Tab at the same time). Then the div has to close.

jsFiddle: http://jsfiddle.net/SchweizerSchoggi/so03fcro/1/

Thx a lot for any help!

Upvotes: 1

Views: 2139

Answers (2)

JonSnow
JonSnow

Reputation: 325

ok, I found a solution meanwhile and I have updated the fiddle.

My idea was to check if only keycode 9 (tab) was being pressed while the focus is on the last li or if keycode 9 + shiftKey are pressed. If two keys are pressed: do nothing. If only Tab is pressed on the last element: close div.

$('.ms-drop ul > li:last-child').keydown(function (e) {
      if (e.which == 9 && e.shiftKey) {
            // do nothing
      } else if (e.which == 9) {
           $('.ms-drop').hide();
      }
});

Does this make sense or is there an even better solution? http://jsfiddle.net/SchweizerSchoggi/so03fcro/6/

Upvotes: 0

Jean
Jean

Reputation: 5411

Add an ID to the last item on your list, like this:

<div class="ms-drop" style="display: block;">
    <ul>
       <li class="selected">
            <label>
                <input name="ProcessType" type="checkbox" checked="checked" value="A"> Typ A
            </label>
       </li>
       <li class="selected">
           <label>
               <input name="ProcessType" type="checkbox" checked="checked" value="B"> Typ B
           </label>
       </li>
       <li class="selected" id="last">
           <label>
               <input name="ProcessType" type="checkbox" checked="checked" value="C"> Typ C
           </label>
       </li>
    </ul>
</div>

then add the following lines to your jquery code:

$(document).ready( function() {
    $('.ms-drop ul > li').focusin( function() {
        $(this).addClass('focus');
    });

    $('.ms-drop ul > li').focusout( function() {
        $(this).removeClass('focus');
    });

    $('#last').focusout(function(){
        $('.ms-drop').hide();
    });

});

Upvotes: 1

Related Questions