Prevent page from moving to top after clicking on overlay image to start video

1870 views javascript
5

I have a bit of code that automatically starts a video after clicking on an overlay image. The trouble is that the after clicking, the entire page moves up to the top while video plays further down the page. What is the cause and how can I prevent that from happening and allow the video to play where it is originally clicked?

Here is a link to the codepen (scroll down to see video): https://codepen.io/NewbCake/pen/qMMQZo

It depends on Jquery and Fitvids

Thank you for any help!

HTML

<section>
  <div class="video-intro">
    <div class="image">
      <div class="play-button btn"></div>
      <a href="#" id="btn_play" class="btn">
        <img src="http://placekitten.com/960/540" alt="play video" />    
      </a>
    </div>
    <iframe src="https://player.vimeo.com/video/66991893?api=1&title=0&amp;byline=0&amp;portrait=0&amp;color=57c0d4" width="960" height="540" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>
  </div>
</section>

CSS

section {
  display:grid;
  grid-template-columns:10vw 500px;
  margin-top:300px;
}

/* video intro */
.video-intro {
  grid-column: 2 ;
  box-shadow:0px 0px 7px #ddd;
  margin:0 auto 50px !important;
  width:90%;
  position:relative;
  max-width:960px;

.image {
  position:absolute;
  top:0;
  left:0;
  z-index:20;

img {
  width:100%;
  height:auto;
}

JS

$(function(){
  var $parent = $('.video-intro'),
  $f = $parent.find('iframe'),
  $image = $parent.find('.image'),
  f = $f[0],
  url = $f.attr('src').split('?')[0];

  window.addEventListener('message', function(e){
    var d = JSON.parse(e.data);
  }, false);

  $('.btn').click(function(){
    var $t = $(this);
    runCommand('play');
    $image.hide();
  });

  function runCommand(cmd){
    var data = {method : cmd};
    f.contentWindow.postMessage(JSON.stringify(data), url);
  }

  // fitvids
  $('.video-intro').fitVids();

});

answered question

1 Answer

10

Try using javascript: instead of # :

<a href="javascript:" id="btn_play" class="btn">

posted this

Have an answer?

JD

Please login first before posting an answer.