Forum Discussion

KnutCollettJrge's avatar
KnutCollettJrge
Community Member
25 days ago

Close a lightboxed slide by clicking outside it

In my opinion, clicking outside a lightbox/modal is an intuitive way of closing it. We've hidden the built-in button with javascript, but wanted to be able to close a lightboxed slide by clicking anywhere outside the lightbox. And finally I found a way.

One of the objects added to the scene when you lightbox a slide is an overlay. This makes the slide in the background darker. It can be found in the console and has the class "visible-overlay". I simply added an eventlistener listening for clicks on this element and used the function of the original Close-button to do the job. The script is placed on the lightboxed slide.

Does anyone see any immediate dangers of creating instability doing this?

Here's the Javascript.

// Select the element with the class "visible-overlay"
const overlayElement = document.querySelector('.visible-overlay');

// Check if the element exists to avoid errors
if (overlayElement) {
  // Add an event listener for a click event
  overlayElement.addEventListener('click', (event) => {
	// Simulate a click on the default close button element
	var closeButton = document.getElementById("light-box-close");
	if (closeButton) {
    closeButton.click();
	overlayElement.removeEventListener('click', (event));
	}
  });
}

 

 

Demo

2 Replies

  • ID4WiscState's avatar
    ID4WiscState
    Community Member

    Great concept! I'm curious about best practices using a screen reader.

    • KnutCollettJrge's avatar
      KnutCollettJrge
      Community Member

      In the course we're developing we also have a custom button to close the lightbox. This is picked up by the screen reader like a normal button. I suppose this option is for the visibly unimpaired :)