Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking all children of a submenu to see if any element has focus in jquery, using :focus selector

I have a navigation menu which when an item is selected on the menu, a submenu will appear. The submenu can contain 3 possible elements: text to represent a category, a url to take the user somewhere, and a search box with which the user can type data in and hit a button to go to a controller action. For design purposes, every five elements are grouped into one ul.

This is an example of such a submenu:

<div id = "submenu">
<ul>
<li> Products </li>
<li> <a href = "ourproducts"> View Our Products</a></li>
<li> <form method="GET" action="/"><input value="" name="searchproduct"><input type="Submit" value="Search For Product"> </form> </li>
</ul>

I have a mouseleave function on the submenu that will cause the submenu to hide. However, if the form has focus (say the user is trying to type something in and they accidentally bump the mouse), then I do not want the submenu to disappear.

This is what I have tried so far:

$("#submenu").mouseleave(function () {
        var childhasfocus= 0;
        for (var i = 1; i < $(this).children().length; i++) {
            if ($(this).children[i].is(":focus") == true) { //CODE GOES UP TO HERE BEFORE BREAKING
                childhasfocus = 1;
            }
        }
        // TRIED THIS- if ($(this + '>:focus').length > 0){
        if (childhasfocus != 1){
            hideLinks();
        }
    });

Two Questions:

1:If one of the elements inside a ul has focus, will the ul also has focus?

2:What should I replace my if statement with?

like image 810
tehdoommarine Avatar asked Jan 25 '12 19:01

tehdoommarine


People also ask

How do you get children of children in jQuery?

Definition and Usage. The children() method returns all direct children of the selected element. The DOM tree: This method only traverse a single level down the DOM tree. To traverse down multiple levels (to return grandchildren or other descendants), use the find() method.

How do I find out which DOM element has the focus?

Syntax: var ele = document. activeElement; Return value: It returns the currently focused element in the document.

How do you get the children of the $( this selector?

Answer: Use the jQuery find() Method You can use the find() method to get the children of the $(this) selector using jQuery. The jQuery code in the following example will simply select the child <img> element and apply some CSS style on it on click of the parent <div> element.


1 Answers

Try this

$("#submenu").mouseleave(function () {
    //This will check if any child of submenu has focus. If no then hideLinks
    if ($(this).children(":focus").length == 0){
        hideLinks();
    }
});
like image 73
ShankarSangoli Avatar answered Nov 22 '22 10:11

ShankarSangoli