Skip to content

Instantly share code, notes, and snippets.

@adrienjoly
Last active August 29, 2015 14:19
Show Gist options
  • Select an option

  • Save adrienjoly/a4dd6e34f1d28ed56aec to your computer and use it in GitHub Desktop.

Select an option

Save adrienjoly/a4dd6e34f1d28ed56aec to your computer and use it in GitHub Desktop.
jquery-based function for displaying a popin/menu on hover
// 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