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?
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.
Syntax: var ele = document. activeElement; Return value: It returns the currently focused element in the document.
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.
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();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With