Imre_talpa
Imre_talpa

Reputation: 121

Make multiple images in full screen with a single function

I found in one question on Stack Overflow a code that make an image in full screen.But the code is for only one image.

<!doctype html>
<html>
  <head>
     <style>
      .fullscreen:-webkit-full-screen {
      width: auto !important;
      height: auto !important;
      margin:auto !important;
  }
     .fullscreen:-moz-full-screen {
      width: auto !important;
      height: auto !important;
      margin:auto !important;
  }
     .fullscreen:-ms-fullscreen {
      width: auto !important;
      height: auto !important;
      margin:auto !important;
  }     
     </style>
     <script>
        function makeFullScreen() {
         var divObj = document.getElementById("theImage");
       //Use the specification method before using prefixed versions
      if (divObj.requestFullscreen) {
        divObj.requestFullscreen();
      }
      else if (divObj.msRequestFullscreen) {
        divObj.msRequestFullscreen();               
      }
      else if (divObj.mozRequestFullScreen) {
        divObj.mozRequestFullScreen();      
      }
      else if (divObj.webkitRequestFullscreen) {
        divObj.webkitRequestFullscreen();       
      } else {
        console.log("Fullscreen API is not supported");
      } 

    }
     </script>

  </head>
  <body>
    Hello Image...</br>

    <img id="theImage" style="width:400px; height:auto;"  class="fullscreen" src="pic1.jpg" onClick="makeFullScreen()"></img>

  </body>
</html>

Can this function be transformed to work on multiple images(to not make a function for every image).

Upvotes: 2

Views: 523

Answers (1)

obscure
obscure

Reputation: 12891

This is simply done by adding the onClick handler to multiple image elements and assigning the event parameter to each function call.

<img src="picA.jpg" onClick="makeFullScreen(event)">
<img src="picB.jpg" onClick="makeFullScreen(event)">
<img src="picC.jpg" onClick="makeFullScreen(event)">

Inside the makefullScreen callback function you can get the element which has triggered the click event - thus your image - and make it fullscreen using your existing code.

function makeFullScreen(e) {
  var divObj = e.currentTarget;
  //Use the specification method before using prefixed versions
  if (divObj.requestFullscreen) {
    divObj.requestFullscreen();
  } else if (divObj.msRequestFullscreen) {
    divObj.msRequestFullscreen();
  } else if (divObj.mozRequestFullScreen) {
    divObj.mozRequestFullScreen();
  } else if (divObj.webkitRequestFullscreen) {
    divObj.webkitRequestFullscreen();
  } else {
    console.log("Fullscreen API is not supported");
  }
}

Upvotes: 1

Related Questions