Search code examples
javascriptlightbox

Adding a close function that doesn't reposition page


I added the ability to display a youtube video within a Lightbox on my website. However, the code I found to help with this doesn't have a close (X) on the Lightbox. Whilst it does close by just clicking anywhere on the mask, I think not all web users are going to realise this, so I added a simple

<a href="#" class="x">x</a>

onto the Lightbox div. Whilst this does actually give a functional closing (X) on the lightbox, it has the undesirable effect of the page being back at the top when the Lightbox has closed.

What I ideally want is for the Lightbox to simply close, and the page remains in the same place as it was when it opens, which is what happens if I just click on the mask.

I can see there is a section commented '// Hide lightbox when clicked on', but I have no clue how I can make an (X) also trigger this same action.

Here is the complete script used.

<div id="youtubelightbox" class="parent"><a href="#" class="x">x</a>
  <div class="centeredchild">
    <div class="videowrapper">
      <div id="playerdiv"></div>
    </div>
  </div>
</div>

<script>
// load Youtube API code asynchronously
var tag = document.createElement('script')
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0]
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag)

var isiOS = navigator.userAgent.match(/(iPad)|(iPhone)|(iPod)/i) != null //boolean check for iOS devices

var youtubelightbox = document.getElementById('youtubelightbox')
var player // variable to hold new YT.Player() instance

// Hide lightbox when clicked on
youtubelightbox.addEventListener('click', function(){
  this.style.display = 'none'
  player.stopVideo()
}, false)


// Exclude youtube iframe from above action
youtubelightbox.querySelector('.centeredchild').addEventListener('click', function(e){
e.stopPropagation()
}, false)


// define onYouTubeIframeAPIReady() function and initialize lightbox when API is ready
function onYouTubeIframeAPIReady() {
    createlightbox()
}

// Extracts the Youtube video ID from a well formed Youtube URL
function getyoutubeid(link){
// Assumed Youtube URL formats
// https://www.youtube.com/watch?v=Pe0jFDPHkzo
// https://youtu.be/Pe0jFDPHkzo
// https://www.youtube.com/v/Pe0jFDPHkzo
// and more

//See http://stackoverflow.com/a/6904504/4360074
var youtubeidreg = /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/ ]{11})/i;
return youtubeidreg.exec(link)[1] // return Youtube video ID portion of link
}

// Creates a new YT.Player() instance
function createyoutubeplayer(videourl){
    player = new YT.Player('playerdiv', {
        videoId: videourl,
        playerVars: {autoplay:1,
                     rel:0,
                     showinfo:0,
                     fs:0
                     }
    })
}

// Main Youtube lightbox function
function createlightbox(){
    var targetlinks = document.querySelectorAll('.lightbox')
    for (var i=0; i<targetlinks.length; i++){
        var link = targetlinks[i]
        link._videoid = getyoutubeid(link) // store youtube video ID portion of link inside _videoid property
        targetlinks[i].addEventListener('click', function(e){
            youtubelightbox.style.display = 'block'
            if (typeof player == 'undefined'){ // if video player hasn't been created yet
                createyoutubeplayer(this._videoid)
            }
            else{
                if (isiOS){ // iOS devices can only use the "cue" related methods
                    player.cueVideoById(this._videoid)
                }
                else{
                    player.loadVideoById(this._videoid)
                }
            }
            e.preventDefault()
        }, false)
    }
}


if (isiOS){ // iOS devices can only use the "cue" related methods
    player.cueVideoById(this._videoid)
}
else{
    player.loadVideoById(this._videoid)
}


Solution

  • After some trial and error I figured this out.

    I changed the html to

    <div id="youtubelightbox" class="parent">
      <div class="centeredchild"><div id="x">x</div>
        <div class="videowrapper">
          <div id="playerdiv"></div>
        </div>
      </div>
    </div>
    

    And added the following to the script

    x.addEventListener('click', function(){
      youtubelightbox.style.display = 'none'
      player.stopVideo()
    }, false)