Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <h1>Simple keyboard trap</h1>
<p>Setting trap prepends/appends buttons to element and watches focus of these to send back to first or last, trapping our events keyboard within.</p>
<p>Watching these lets the browser do the work with the rest of the elements within, if a button is disabled/enabled we don't need to worry about it, likewise if other content within changes it does not effect our trap or elements we need to watch.</p>
<p>Also iframes within do not break our trap when they are the first or last element. Blur events on elements within the iframe do not fire an event for the parent window and can cause the loss of focus within the trap - only worrying about focus for our appended buttons avoids this.</p>

<p>When focus is set to the first or last element we check document.activeElement matches, if the element was in a non-focusable state then focus will be kicked to the body and not match. If focus is not set successfully iterate forward/back until successful.</p>
<hr>

<h2>Focusable stuff outside of trap</h2>
<input/>

<p>Donec id elit non mi porta gravida at eget metus. Cum sociis natoque <a href="#">penatibus et magnis</a> dis parturient montes, nascetur ridiculus mus.</p>

<hr>

<button id="trap-keyboard">Trap keyboard</button>


<div class="trap-area">
  <a href="javascript:;" data-kill>Kill trap</a>
  <p>When the keyboard trap is active you tab or shift+tab will iterate through focusable elements within this trap-area only.</p>
  <p>Donec sed <a href="#">odio dui</a>. Donec id elit non mi porta gravida at eget metus.</p>
  <form action="#">
    <input type="text">
    <select>
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>
    <input type="checkbox" class="toggle-disabled">
    <button type="submit" disabled id="submit">Submit</button>
  </form>
</div>

<p>This pen was created as an example for the article <a href="https://kahoot.com/tech-blog/focus-on-accessi…menus-and-modals">Focus on accessibility – accessible menus and modals on kahoot.com</a></p>


              
            
!

CSS

              
                .send-focus {
	border: none;
	background-color: transparent;
	width: 0; padding: 0;
  position: absolute;
  
  // 
  border: 1px solid red;
}


body {
  font-family: sans-serif; 
  font-size: 0.8em;
  color: #333;
}
p {
  line-height: 1.4;
}
hr {
  border: none;
  background: #eee;
  height: 2px;
  margin-top: 20px;
  margin-bottom: 20px;
}

// styling for demo
div.trap-area {
  border: 1px solid #ccc;
  padding: 20px; 
  max-width: 300px;
  margin: 40px auto; 
  position: relative;
  p, input, button, select {
    margin-bottom:10px;
  }
  input, button, select {
    display:block;
  }
}
a[data-kill] {
  display: none;
}
.trap-active a[data-kill] {
  display: block;
  position: absolute;
  font-size: 0.7rem;
  background-color: #333; color: #fff;
  padding: 4px 8px;
  bottom: 100%; right: 0;
}
              
            
!

JS

              
                // simple keyboard trap
const trapKeyboard = (el) => {
  el.classList.add('trap-active');
	var focusableElements = el.querySelectorAll(`
		a:not(.send-focus), 
		input[type="text"]:not([name="hp"]), 
		input[type="email"], 
		input[type="number"], 
		input[type="checkbox"], 
		button, 
		select, 
		textarea
	`);


  if ( !el.querySelectorAll('.send-focus--last').length ) {
    var hiddenFirst = document.createElement('button');
    // using a button instead of anchor makes this focusable by tab in safari
    hiddenFirst.classList.add('send-focus');
    hiddenFirst.classList.add('send-focus--last');
    hiddenFirst.setAttribute('aria-hidden', 'true');
    el.prepend(hiddenFirst);
  }
	if ( !el.querySelectorAll('.send-focus--first').length ) {
		var hiddenLast = document.createElement('button'); 
		hiddenLast.classList.add('send-focus');
		hiddenLast.classList.add('send-focus--first');
		hiddenLast.setAttribute('aria-hidden', 'true');
    el.append(hiddenLast);
	}

	var firstFocus = focusableElements[0];
	firstFocus.focus();
  
  const sendFocusToLast = () => {
// set focus on last focusable element
// loop through elements to ensure focus is set
 // else set on prev element

			for(var c = focusableElements.length - 1; c  >= 0; c --){
				focusableElements[c].focus();
				if ( document.activeElement == focusableElements[c] ) { 
				 	break;
				} 
				if (c == 0 ) {
					el.focus();
				}
			}
  };
  
  const sendFocusToFirst = () => {
    for (var i = 0; i < focusableElements.length; i++) {
			focusableElements[i].focus();
			if ( document.activeElement == focusableElements[i] ) { 
				 break;
			 } 
			 if ( i == focusableElements.length-1 )	{
				el.focus();
			 }	
		}
  };

	el.querySelector('.send-focus--first').addEventListener("focus", sendFocusToFirst, true);

	el.querySelector('.send-focus--last').addEventListener("focus", sendFocusToLast, true);
}



// js for demo
const trapButton = document.getElementById('trap-keyboard');
const trapArea = document.querySelector('.trap-area');
const killTrap = document.querySelector('[data-kill]');
const toggleDisabled = document.querySelector('.toggle-disabled');
const submitBtn = document.getElementById('submit');

trapButton.addEventListener('click', ()=>{
  trapKeyboard(trapArea);
});

toggleDisabled.addEventListener('change', ()=>{
    if(toggleDisabled.checked) {
      submit.removeAttribute('disabled');
    } else {
      submit.setAttribute('disabled', true);
    }
});

killTrap.addEventListener('click', (e)=>{
  let thisTrap = e.target.closest('.trap-active');
  thisTrap.classList.remove('trap-active');
 
  let senders = thisTrap.querySelectorAll('.send-focus');
  for ( let i = 0; i< senders.length; i++) {
    senders[i].remove();
  }
});
              
            
!
999px

Console