Skip to content

Instantly share code, notes, and snippets.

@nocodesupplyco
Created December 19, 2022 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nocodesupplyco/464e33a41ef13f0af578a1e43031d0c8 to your computer and use it in GitHub Desktop.
Save nocodesupplyco/464e33a41ef13f0af578a1e43031d0c8 to your computer and use it in GitHub Desktop.
Trap Focus in Modal/Dialog/Cart
// Below targets 3 elements within Webflow:
// 1. Dialog Open Button: `.cc-cart-button`
// 2. Dialog Close Button: `.cart-close`
// 3. Dialog Wrapper (element that gets set to display: block or none): `.cart-wrapper`
$(function () {
var findDialog = function (elem) {
var tabbable = elem
.find("select, input, textarea, button, a")
.filter(":visible");
var firstTabbable = tabbable.first();
var lastTabbable = tabbable.last();
/*set focus on first input*/
firstTabbable.focus();
/*redirect last tab to first input*/
lastTabbable.on("keydown", function (e) {
if (e.which === 9 && !e.shiftKey) {
e.preventDefault();
firstTabbable.focus();
}
});
/*redirect first shift+tab to last input*/
firstTabbable.on("keydown", function (e) {
if (e.which === 9 && e.shiftKey) {
e.preventDefault();
lastTabbable.focus();
}
});
/* allow escape key to close insiders div */
elem.on("keyup", function (e) {
if (e.keyCode === 27) {
elem.hide();
}
});
};
$(".cc-cart-button").click(function (e) {
e.preventDefault();
$(".cart-wrapper").show();
findDialog($(".cart-wrapper"));
});
$(".cart-close").click(function (e) {
console.log("Cart closed");
e.preventDefault();
$(".cart-wrapper").hide();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment