Last active
August 29, 2015 14:19
-
-
Save adrienjoly/a4dd6e34f1d28ed56aec to your computer and use it in GitHub Desktop.
jquery-based function for displaying a popin/menu on hover
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // generic function for displaying a menu element when hovering on an other element | |
| function popinOnHover(hoverElement, menuElementOrFunction){ | |
| var $menuElement = typeof menuElementOrFunction !== 'function' ? $(menuElementOrFunction) : null; | |
| var hoveredZones = 0; | |
| function hideIfNotHovered(){ | |
| if (!hoveredZones){ | |
| if (typeof menuElementOrFunction === 'function') { | |
| $menuElement = menuElementOrFunction(false); | |
| } | |
| else | |
| $menuElement.hide(); | |
| } | |
| } | |
| function leave(){ | |
| hoveredZones--; | |
| setTimeout(hideIfNotHovered, 100); | |
| } | |
| function hover(){ | |
| hoveredZones++; | |
| } | |
| function showPopin(){ | |
| if (typeof menuElementOrFunction === 'function') | |
| $menuElement = $(menuElementOrFunction(this)); | |
| $menuElement | |
| .css($(this).position()) | |
| .mouseenter(hover) | |
| .mouseleave(leave) | |
| .show(); | |
| } | |
| $(hoverElement) | |
| .mouseenter(hover) | |
| .mouseenter(showPopin) | |
| .mouseleave(leave); | |
| } | |
| // sample use: | |
| function togglePopin(hoveredElement){ | |
| var $popin = $('.notif-popin'); | |
| if (!hoveredElement) { | |
| $popin.remove(); | |
| return null; | |
| } | |
| if (!$popin.length) { | |
| $popin = $('<div class="notif-popin"></div>').appendTo($body); | |
| } | |
| populatePopin($popin, hoveredElement); | |
| return $popin; | |
| } | |
| popinOnHover($('#hoverElement1, #hoverElement2'), togglePopin); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment