Skip to content

Instantly share code, notes, and snippets.

@philcon93
Last active September 18, 2017 04:38
Show Gist options
  • Save philcon93/6dedeff404ff7938d4f67892c6e7078d to your computer and use it in GitHub Desktop.
Save philcon93/6dedeff404ff7938d4f67892c6e7078d to your computer and use it in GitHub Desktop.
Place an observer on npopup

nPopup observer

JS

This popup is used for many items for Neto sites, e.g:

  • Add to cart,
  • Remove from cart
  • Wishlist

This configs focus onto the popup so people can navigate via tabbing correctly.

var focused = $('body');
var lastFocused = $('body');
// Capture the current element the user focused in
$(document).on('focusin', function(){
focused = document.activeElement;
});
// Capture the last item focused
function updateFocused(){
lastFocused = focused;
};
$(document).ready(function(){
var popUp = document.getElementById('npopupDesc');
// Configuration of the observer:
var config = {childList: true};
// Create an observer instance
var popUpObserver = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
// Initial observer
if(mutation.addedNodes["0"]){
updateFocused();
// focus on the popup
$(popUp).attr('tabindex', '-1').focus();
}else{
$(popUp).attr('tabindex', '').blur();
// Observer closing popup
$(lastFocused).focus();
}
});
});
// Pass in the target node, as well as the observer options
if(popUp){ popUpObserver.observe(popUp, config);}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment