简体   繁体   中英

Give focus to returned element in JS

I have a slideshow lightbox which gets activated when a particular thumbnail image gets focus and 'Ente'r is pressed. When I close the lightbox, focus is returned to the same thumbnail image, so the tabbing order is not disturbed. I'm using a global variable for it and it works great but I want to try not to use a global variable. This the working code:

let focusedImgBeforeSlideshow

function openSlideshow () {

  *code which opens the slideshow*

  focusedImgBeforeSlideshow = document.activeElement
}


function closeSlideshow () {
  *code which closes the slideshow*

  focusedImgBeforeSlideshow.focus()
}

I have tried wrapping focusedImgBeforeSlideshow in a function and calling it in openSlideshow() like this:

function focusedImg () {
  const focusedImgBeforeSlideshow = document.activeElement
  return focusedImgBeforeSlideshow
}

function openSlideshow () {
  focusedImg()
}

... and it works but the problem is, I can't return the focus when I close the slideshow. I have tried this:

function closeSlideshow () {
  focusedImg().focus()
}

... but this is nonsense, obviously. Another way I've tried was this:

function focusedImg () {
  const focusedImgBeforeSlideshow
  return focusedImgBeforeSlideshow
}

function openSlideshow () {
  let focused = focusedImg ()

  focused = document.activeElement
  
  return focused
}

... but then again the problem starts when I close the slideshow.

function closeSlideshow () {
  let returnedFocus = openSlideshow ()

  returnedFocus.focused.focus()
}

How can I return focus without using a global variable?

If you don't want to declare a global variable, you can wrap your code into a module using exports keyword.

If you are using okd javascript (Ecmascript 5), you can declare a IIFE to wrap your code into a function and prevent exposing the focusedImgBeforeSlideshow variable.

(function() {
  var focusedImgBeforeSlideshow

  window.openSlideshow = function () {
    focusedImgBeforeSlideshow = document.activeElement

    *code which opens the slideshow*
  }

  window.closeSlideshow = function () {
    *code which closes the slideshow*

    focusedImgBeforeSlideshow.focus()
  }

})()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM