Skip to content Skip to sidebar Skip to footer

How To Load A Iframe Only On Button Click

I want a youtube video Iframe only when 'Watch Video' Button is clicked. Currently the video iframe loads in the background, when the page loads. Note: I do not mean, play the vid

Solution 1:

You can change the src attribute to a data-src, then when you click the button, set src to data-src

// Get the modalvar modal = document.getElementById('trailerdivbox');

// Get the button that opens the modalvar btn = document.getElementById("watchbutton");

var trailer = document.getElementById('trailervideo');

// When the user clicks the button, open the modal 
btn.onclick = function() {
  modal.style.display = "block";
  trailer.setAttribute('src', trailer.getAttribute('data-src'));
}

var trailerbox = document.getElementById("close");

trailerbox.onclick = function() {
  modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close itwindow.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}
/* Watch Trailer Button CSS */#watchbutton {
  background-color: #f2f2f2;
  color: red;
  font-weight: 600;
  border: none;
  /* This one removes the border of button */padding: 10px12px;
}

#watchbutton:hover {
  background-color: #e2e2e2;
  cursor: pointer;
}

#trailerdivbox {
  display: none;
  width: 100%;
  height: 100%;
  position: fixed;
  overflow: auto;
  /* Enable Scrolling */background-color: rgb(0, 0, 0);
  /* Fallback color */background-color: rgba(0, 0, 0, 0.4);
  /* Black w/ opacity */
}

.videoWrapper {
  position: relative;
  padding-bottom: 56.25%;
  /* 16:9 */padding-top: 25px;
  height: 0;
}

.videoWrapperiframe {
  position: absolute;
  max-width: 560px;
  max-height: 315px;
  width: 95%;
  height: 95%;
  left: 0;
  right: 0;
  margin: auto;
}
<buttonid="watchbutton">Watch Trailer &#9658</button><divid="close"><divid="trailerdivbox"><divclass="videoWrapper"><iframeid="trailervideo"class="trailervideo"width="560"height="315"data-src="https://www.youtube.com/embed/TDwJDRbSYbw"frameborder="0"allowfullscreen></iframe></div></div></div>

Post a Comment for "How To Load A Iframe Only On Button Click"