Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <main id=main class=hasJS>

  <h1>Button to embed video iframe (v2)</h1>

  <p>Currently v2.0 is in use on the <a href="http://www.tesco.com/baking">Tesco Bake-off</a> page.</p>

 <!-- 
<p><button class=btn-video-textOnly data-video="https://www.youtube.com/embed/lOUjUirKzM0" data-video_img="http://www.tesco.com/toy-testers/2016/i/video-1.jpg" data-video_stage="stage" data-video_textOnly>Text-only, no button bg image, default on stage</button></p>
-->

  <section class=theatre>

    <div id=stage class=stage></div>

    <div class=acts>

      <img class=btn-video data-video="https://www.youtube.com/embed/-mzBeT19ijQ" data-video_img="http://www.tesco.com/baking/2016/i/bake-on1.jpg" data-video_stage="stage" alt="Play the Bake-off video">

      <!--
      <button class=btn-video data-video="https://www.youtube.com/embed/-mzBeT19ijQ" data-video_img="http://www.tesco.com/baking/2016/i/bake-on1.jpg" data-video_stage="stage">Play the Bake-off video</button>
-->
      <button class=btn-video data-video="https://www.youtube.com/embed/lOUjUirKzM0" data-video_img="http://www.tesco.com/toy-testers/2016/i/video-1.jpg" data-video_stage="stage">Play the Toy-testers video</button>

      <a class=btn-video href="https://www.youtube.com/embed/RLEKiXaixLY" data-video_img="http://www.tesco.com/global/modules/imagetostage/i/video-2.jpg" data-video_stage="stage">Play the Tannoy-takeover video</a>

    </div>

  </section>

<p><button class=btn-video-textOnly data-video="https://www.youtube.com/embed/RLEKiXaixLY" data-video_img="http://www.tesco.com/global/modules/imagetostage/i/video-2.jpg" data-video_stage="stage" data-video_textOnly>Text-only, without bg image on button</button></p>

  <section>
    <h2>Description</h2>
    <p>For technical reasons, at Tesco we cannot hijack a link to embed a video.<br> We tried using images but the tap/click didn't track.<br> Our solution; use a button.</p>
    <p>This version will launch a video from most objects: anchors, buttons, divs, spans, images.<br>Roles and behaviours are amended to suit.</p>
    <p>All layout is in the CSS and the only magic number is the 16:9 ratio.</p>
  </section>

  <section>
    <h2>Tested</h2>
    <p>PC: IE9 - Edge, Firefox, Chrome.<br> Mac: Firefox, Chrome, Safari.<br> No mobile testing as yet.</p>
  </section>


  <h2>Single video example</h2>
  <div id=stage2 class=stage role=presentational>
    <a class=btn-video data-video href="https://www.youtube.com/embed/RLEKiXaixLY" data-video_img="http://www.tesco.com/global/modules/imagetostage/i/video-2.jpg" data-video_stage="stage2">Play the Tannoy-takeover video</a>
  </div>
  <p>Sent for testing to the <a href="http://digitalaccessibilitycentre.org/">Digital Accessibility Centre</a>.</p>


</main>

<svg style="display:none">
  <defs>

				<symbol viewBox="0 0 224 170" id="icon-youtube-play">
					<title>Play video</title>
					<path fill="white" d="M92 111l54-28L92 55V111z"></path>
					<path d="M209 46c0 0-2-14-8-20-7-8-16-8-20-8-28-2-69-2-69-2h0c0 0-42 0-69 2-4 1-12 1-20 8-6 6-8 20-8 20s-2 16-2 32v15c0 16 2 32 2 32s2 14 8 20c8 8 18 8 22 8 16 2 67 2 67 2s42 0 69-2c4 0 12 0 20-8 6-6 8-20 8-20s2-16 2-32v-15C211 62 209 46 209 46zM92 111V55l54 28L92 111z"></path>
				</symbol>

    <symbol viewBox='0 0 150 130' id="icon-loading">
      <title>Loading</title>
      <path d='M81.5 33l30.8-32.8c0.3-0.3 0.5-0.2 0.3 0.3 -1.8 5.2-1.7 15.3-1.7 15.3 -0.1 6.8-0.8 11.7-6.6 17.9L74.8 65.1c-0.2 0.2-0.4 0-0.3-0.2 1.5-5.1 1.2-15.1 1.2-15.1C75.4 45.6 76.4 38.4 81.5 33M105.9 54.8l43.8 10.3c0.4 0.1 0.4 0.4-0.2 0.4 -5.4 1-14.1 6.1-14.1 6.1 -6 3.3-10.5 5.2-18.8 3.2l-41.9-9.9c-0.3-0.1-0.2-0.3 0-0.4 5.2-1.3 13.7-6.5 13.7-6.5C92 55.9 98.7 53.1 105.9 54.8M99.4 86.3l13 43.2c0.1 0.4-0.1 0.5-0.4 0.1 -3.6-4.2-12.4-9.2-12.4-9.2 -5.8-3.5-9.7-6.5-12.2-14.6L75 64.5c-0.1-0.3 0.2-0.4 0.3-0.2 3.7 3.9 12.5 8.6 12.5 8.6C91.5 74.8 97.3 79.2 99.4 86.3M68.7 97l-30.8 32.8c-0.3 0.3-0.5 0.2-0.3-0.3 1.8-5.2 1.7-15.3 1.7-15.3 0.1-6.8 0.8-11.7 6.6-17.9l29.5-31.4c0.2-0.2 0.4 0 0.3 0.2 -1.5 5.1-1.2 15.1-1.2 15.1C74.8 84.4 73.8 91.6 68.7 97M44.1 75.8L0.3 65.4C-0.1 65.3-0.1 65 0.5 65c5.4-1 14.1-6.1 14.1-6.1 6-3.3 10.5-5.2 18.8-3.2l41.9 9.9c0.3 0.1 0.2 0.3 0 0.4 -5.2 1.3-13.7 6.5-13.7 6.5C58.1 74.7 51.3 77.5 44.1 75.8M50.2 43.8l-13-43.2c-0.1-0.4 0.1-0.5 0.4-0.1C41.2 4.7 50 9.7 50 9.7c5.8 3.5 9.7 6.5 12.2 14.6l12.4 41.3c0.1 0.3-0.2 0.4-0.3 0.2 -3.7-3.9-12.5-8.6-12.5-8.6C58.1 55.4 52.4 50.9 50.2 43.8'/>
    </symbol>
  </defs>
</svg>


<p class=smaller><a target=_blank title="[new window]" href="https://codepen.io/2kool2/pens/public/?grid_type=list#">Pens by Mike Foskett</a> &mdash; <a target=_blank title="[new window]" href="https://websemantics.uk/">webSemantics</a></p>
              
            
!

CSS

              
                body {
  /* template override */
  max-width: 696px;
}

.noJS .theatre {
  /* no point in displaying without JS */
  display: none;
}

.theatre {
  max-width: 664px;
  margin: 2em auto;
	padding: 12px;
  background-color: rgba(255,255,255,.75);
}
.stage {
  display: block;
	max-width: 640px;
	margin: 0 auto;
  position: relative;
  width: 100%;
  height: 100%;
  background-size: cover;
  background-repeat: no-repeat;
  background-color: rgba(255,255,255,.5);
}
.acts {
  display: flex;
  padding-top:12px;
}
.btn-video {
  margin: 0 12px 0 0;
}
.btn-video:last-child {
  margin: 0;
}
.stage .btn-video {
  margin: 0;
}

[class^="btn-video"]{
  display: block;
	cursor: pointer;
  padding:0;
  border: 0 solid;
  width: 100%;
  height: 100%;
	max-width: 640px;
	max-height: 360px;
  background-color: transparent;
  background-size: cover;
  background-repeat: no-repeat;
  will-change: filter, box-shadow;
}
[class^="btn-video"]:hover,
[class^="btn-video"]:focus {
  background-color: transparent;
  -webkit-filter: contrast(120%) brightness(120%);
  filter: contrast(110%) brightness(120%);
  /* Red so you can tell */
  box-shadow: 0 0 0 4px rgba(210, 33, 33, .8); 
  outline: 0 solid;
}

/* Text only button test -textOnly removed when copied to stage default */
.btn-video-textOnly {
  /* styling from default template */
  font-size: larger;
  padding:.125rem .25rem;
  color: #fff;
  background-color: rgba(0,0,0,.5);
}

.btn-video_img {
  display: block;
  width: 100%;
  border: 0 solid;
}

.video_iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%; /* Height calculated by JS as 16:9 ratio */
  z-index: 0;
  opacity: 0;
  transition: opacity 1s ease-out;
}
.video_iframe-on {
  opacity: 1
}


/* SVG (Tesco) loading animation */

.svg-loading {
  opacity: 0;
  fill: #fff;
  pointer-events:none;
  position: absolute;
  width: 80px;
  height: 80px;
  top: calc(50% - 40px);
  left: calc(50% - 40px);
  transition: opacity .3s ease-out;
  -webkit-animation: rotate 4s linear 0s infinite;
  animation: rotate 4s linear 0s infinite;
}
.-iframe-fetching .svg-loading {
  opacity: 1;
}
@-webkit-keyframes rotate {
  to {
    -webkit-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}
@keyframes rotate {
  to {
    -webkit-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}


/* YouTube play button */
.svg-play {
	fill: #D22121;
	opacity: 1;
  position: absolute;
  width: 14%;
  height: 14%;
  top: 43%;
  left: 43%;
  transition: opacity .3s ease-out, transform .3s ease-out;
	pointer-events: none;
}
.-iframe-fetching .svg-play,
.-iframe-on .svg-play {
	opacity: 0;
}
.stage:hover > .svg-play,
.stage:focus > .svg-play {
  transform: scale(1.2);
}
              
            
!

JS

              
                // https://john-dugan.com/javascript-debounce/
// Example: window.addEventListener("resize",debounce(funcToCall, timeToWaitBetweenRefreshes, booleanRunAtStart [false = RunAtEnd]));
var debounce=function(e,t,n){var a;return function(){var r=this,i=arguments,o=function(){a=null,n||e.apply(r,i)},s=n&&!a;clearTimeout(a),a=setTimeout(o,t||200),s&&e.apply(r,i)}};


(function (window, d, debounce) {

  "use strict";

  // Button style object to iframed video version 2.0 31-08-2016

  // Requires:
  //    .hasJS class preferably set on <html> tag to allow CSS to kick-in early
  //    SVG definitions for: #icon-youtube-play, #icon-loading
  //    External functions: debounce()

  // To do:
  //    Externalise class names to cfg file

  // defaults global to this module
  var videoName = "video";
  var btnClass = "btn-video";
  var stages = [];

  var iframeClass = videoName + "_iframe";


  var _getStageSize = function (stageObj) {
    var size = {};
     // more performant than getBoundingClientRect
    size.width = stageObj.clientWidth;
    size.height = (size.width / 16) * 9;
    return size;
  };


  var _resizeTheatre = function () {
    
    function _resizeIframes (stageObj, size) {
      var iframes;
      var i;
      iframes = stageObj.getElementsByClassName(iframeClass);
      i = iframes.length;
      while (i--) {
        iframes[i].width = size.width;
        iframes[i].height = size.height;
      }
    }

    var stageObj;
    var size;
    var i = stages.length;
    while (i--) {
      stageObj = d.getElementById(stages[i]);
      size = _getStageSize(stageObj);
		  stageObj.style.height = size.height + "px";
      _resizeIframes(stageObj, size);
    }
  };


  var _addIframe = function (stageObj) {

    var size = _getStageSize(stageObj);
    var iframe = d.createElement("iframe");

		iframe.src = stageObj.videoSrc + "?rel=0&autoplay=1";
		iframe.className = iframeClass;
		iframe.setAttribute("frameborder", 0);
		iframe.setAttribute("allowfullscreen", true);
		iframe.width = size.width;
		iframe.height = size.height;

		stageObj.style.height = size.height + "px";

		// Don't display iframe until its content is as ready as possible to detect
		iframe.addEventListener("load", function () {
			//requestAnimationFrame(function () { // support IE9

				//iframe.classList.add(videoName + "_iframe-on"); // supporting IE9
				iframe.className += " " + videoName + "_iframe-on";

				//stageObj.classList.remove("-fetching"); // supporting IE9
				stageObj.className =  stageObj.className.replace(" -iframe-fetching", " -iframe-on");
				iframe.focus();
			//});
		}, false);

    stageObj.className += " -iframe-fetching";
		stageObj.appendChild(iframe);
  };


  var _removeOldIframe = function (stageObj) {
    
    // fade existing iframe, leaving new image + svg
    var frames = stageObj.getElementsByClassName(iframeClass);
    
    // Only if more then 1 iframe present
    if (frames && frames.length > 1) {

      // Switch off old iframe
      //frames[0].classList.remove("video_iframe-on"); //support IE9
      frames[0].className = frames[0].className.replace(videoName + "_iframe-on", "");
      stageObj.className = stageObj.className.replace(" -iframe-on", "");
      setTimeout(function () {
        // remove old iframe
        stageObj.removeChild(frames[0]);
      }, 500);
    }
  };


  var _getTarget = function (obj) {
    var target = obj;
    var isBodyTag = obj.tagName.toLowerCase() === "body";
    if (isBodyTag) {
      target = false;
    } else {
			if (!obj.videoSrc) {
				target = _getTarget(obj.parentElement);
			}
		}
    return target;
  };


  var _btnAttachProperties = function (btnObj) {
    var btnReturn = false;
    var dataStr = "data-" + videoName;
    if (
      (btnObj.hasAttribute("href") || btnObj.hasAttribute(dataStr))
      && btnObj.hasAttribute(dataStr + "_stage")
      && d.getElementById(btnObj.getAttribute(dataStr + "_stage"))
      && btnObj.hasAttribute(dataStr + "_img")
    ) {
      // Attached properties are used on build
      // On-click they are evaluated again
      // allows developer to in-browser amend values before clicking
      btnObj.videoSrc = btnObj.getAttribute("href") || btnObj.getAttribute(dataStr);
      btnObj.stageId = btnObj.getAttribute(dataStr + "_stage");
      btnObj.imageSrc = btnObj.getAttribute(dataStr + "_img");
      btnObj.isButton = btnObj.tagName.toLowerCase() === "button";
      btnObj.isImage = btnObj.tagName.toLowerCase() === "img";
      
      // text only button option
      btnObj.isTextOnly = btnObj.hasAttribute(dataStr + "_textOnly");
      
      btnReturn = btnObj;
    }
    return btnReturn;
  };


  var _embedVideo = function (e) {

    e.preventDefault();

    var stageObj;
    var target = _getTarget(e.target); // Tests for presence of target.videoSrc property

    if (target) {

      // Do not rely on button properties initial state
      target = _btnAttachProperties(target);
      if (target) {

        stageObj = d.getElementById(target.stageId);
        stageObj.videoSrc = target.videoSrc;
        stageObj.style.backgroundImage = "url(" + target.imageSrc + ")";

        // Remove stage button
        var btns = stageObj.getElementsByClassName(btnClass);
        if (btns && btns[0]) {
          stageObj.removeChild(btns[0]);
        }

        _addIframe(stageObj);
        _removeOldIframe(stageObj);

      }
    }
  };


  var _keydown_btn = function (e) {
    // enter or space from the opener object
    if (e.which === 13 || e.which === 32) {
        e.preventDefault(); 
        _embedVideo(e);
    }
  };


  var _getSVG = function (icon, clss, title) {
    var svg = d.createElementNS("http://www.w3.org/2000/svg", "svg");
    // svg.classList.add(clss); // IE9 support
		// svg.className = clss; // Edge support
		svg.setAttribute("class", clss);

		// Prevent IE focusing on SVG
		svg.setAttribute("focusable", "false");
    if (title) {
      var t = d.createElementNS("http://www.w3.org/2000/svg", "title");
      t.textContent = title;
      svg.appendChild(t);
    }
    var use = d.createElementNS("http://www.w3.org/2000/svg", "use");
    use.setAttributeNS("http://www.w3.org/1999/xlink", "href", "#" + icon);
    svg.appendChild(use);
    return svg;
  };


  var _setStage = function (btnObj, stageObj) {

    var cloneBtn = btnObj.cloneNode(true);

    stageObj.setAttribute("role", "dialog");
    stageObj.style.height = _getStageSize(stageObj).height + "px";
    stageObj.style.backgroundImage = "url(" + btnObj.imageSrc + ")";

    cloneBtn.videoSrc = btnObj.videoSrc;

    var imgs = cloneBtn.getElementsByTagName("img");
    if (imgs && imgs[0]) {
      imgs[0].style.visibility = "hidden";
    }
    
    if (btnObj.isTextOnly) {
      cloneBtn.className = btnClass;
      cloneBtn.style.color = "transparent";
    }

    stageObj.innerHTML = "";
    stageObj.appendChild(cloneBtn);
    stageObj.appendChild(_getSVG("icon-loading", "svg-loading", "Loading"));
    stageObj.appendChild(_getSVG("icon-youtube-play", "svg-play", "Play video"));

    return cloneBtn;
  };


  var _addButtonEvents = function (btnObj) {
    // Non-buttons require keyboard controls
    if (!btnObj.isButton) {
      btnObj.addEventListener("keydown", _keydown_btn, false);
    }
    btnObj.addEventListener("click", _embedVideo, false);
  };


  var _initButton = function (btnObj) {

    btnObj.setAttribute("aria-controls", btnObj.stageId);

    // Non-buttons require keyboard controls
    if (!btnObj.isButton) {
      btnObj.setAttribute("aria-role", "button");
      btnObj.tabIndex = 0;
    }
    return btnObj;
  };


  var _addBtnImage = function (btnObj) {
    if (!btnObj.isTextOnly) {
    var img = d.createElement("img");
    img.className = btnClass + "_img";
    img.src = btnObj.imageSrc;
    img.alt = btnObj.alt || btnObj.textContent;
    btnObj.innerHTML = "";
    btnObj.appendChild(img);
    return img;
    }
  };


  var _convertImgToButton = function (imgObj) {
    // For the rare time an image is used as a button. 
    var btn = d.createElement("button");
    var str = "data-" + videoName;

    btn.className = btnClass;
    btn.setAttribute(str, imgObj.getAttribute(str));
    btn.videoSrc = imgObj.getAttribute(str);
    btn.textContent = imgObj.alt;
    btn.setAttribute(str + "_img", imgObj.getAttribute(str + "_img"));
    btn.imageSrc = imgObj.getAttribute(str + "_img");
    btn.setAttribute(str + "_stage", imgObj.getAttribute(str + "_stage"));
    btn.stageId = imgObj.getAttribute(str + "_stage");
    imgObj.parentElement.replaceChild(btn, imgObj);
    
    return btn;
  };


  var configuration = function (cfg) {
    videoName = cfg.videoName || videoName;
    btnClass = cfg.btnClass || btnClass;
  };


  var _getFirstBtn = function (stageId) {
    var str = "." + btnClass;
    var str = "[class^=\"" + btnClass + "\"]";
    str += "[data-" + videoName + "_stage=\""  + stageId + "\"]";
    str += "[data-" + videoName + "_img]";
    str += "[data-" + videoName + "]";

    var btns = d.querySelectorAll(str);
    var btn = false;
    for (var i=0; i < btns.length; i++) {
      //if (btns[i].videoSrc !== "" && btns[i].imageSrc !== "") {
      if (btns[i].videoSrc !== "" && btns[i].imageSrc !== "") {
        btn = btns[i];
        break;
      } 
    }
    return btn;
  };
  
  
  var _populateStages = function () {
    // run through each stages[] populate with first btn
    var firstBtn;
    var stageObj;
    var i = stages.length;
    while (i--) {
      stageObj = d.getElementById(stages[i]);
      firstBtn = _getFirstBtn(stageObj.id);
      if (firstBtn) {
        firstBtn = _setStage(firstBtn, stageObj);
        _addButtonEvents(firstBtn);
      }
    }
  };


  var initialise = function (cfg) {

    configuration(cfg);

    var btnObj;
    var firstBtn;
    var stageObj;
    var videoBtns = d.getElementsByClassName(btnClass); 
    
    // Go back to queryselectorall to get partial class name for btn-video-textOnly???
    var videoBtns = d.querySelectorAll("[class^=\"" + btnClass + "\"]"); 
    var i = videoBtns.length;

    if (videoBtns) {

      while (i--) {

        btnObj = _btnAttachProperties(videoBtns[i]);
        if (btnObj) {

          // Ignore img btns for now !!!
          if (btnObj.isImage) {
            btnObj = _convertImgToButton(btnObj);
          }
          _addBtnImage(btnObj);
          _initButton(btnObj);
          _addButtonEvents(btnObj);

          if (stages.indexOf(btnObj.stageId) === -1) {
            stages.push(btnObj.stageId);
          }
        }
      }

      // run through each stages[] populate with first btn
      _populateStages();

      window.addEventListener("resize", debounce(_resizeTheatre, 250, false));
    }
  };

  initialise({
    videoName : "video",  // class name of video, the data attribute and also the base name for all classes used (except SVGs).
    btnClass : "btn-video" // Any object with this class will launch a video if data attributes are correctly set
  });

}(window, document, debounce));
              
            
!
999px

Console