-
-
Save nocodesupplyco/464e33a41ef13f0af578a1e43031d0c8 to your computer and use it in GitHub Desktop.
Trap Focus in Modal/Dialog/Cart
This file contains 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
// 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