Next slide button - javascript

I'm having trouble putting a button on the next slide, the mouse and keys of any keyboard works, but wanted to put a button or 2, one to go back and another to move on, I thought of a timer but the success rate was 0% , I'm a good time trying but this really hard, if anyone can help me in this, would help me a lot
/*********************
* Helpers Code
********************/
/**
* #function DOMReady
*
* #param callback
* #param element
* #param listener
* #returns {*}
* #constructor
*/
const DOMReady = ((
callback = () => {},
element = document,
listener = 'addEventListener'
) => {
return (element[listener]) ? element[listener]('DOMContentLoaded', callback) : window.attachEvent('onload', callback);
});
/**
* #function ProjectAPI
*
* #type {{hasClass, addClass, removeClass}}
*/
const ProjectAPI = (() => {
let hasClass,
addClass,
removeClass;
hasClass = ((el, className) => {
if (el === null) {
return;
}
if (el.classList) {
return el.classList.contains(className);
}
else {
return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'));
}
});
addClass = ((el, className) => {
if (el === null) {
return;
}
if (el.classList) {
el.classList.add(className);
}
else if (!hasClass(el, className)) {
el.className += ' ' + className
}
});
removeClass = ((el, className) => {
if (el === null) {
return;
}
if (el.classList) {
el.classList.remove(className);
}
else if (hasClass(el, className)) {
let reg = new RegExp('(\\s|^)' + className + '(\\s|$)');
el.className = el.className.replace(reg, ' ');
}
});
return {
hasClass: hasClass,
addClass: addClass,
removeClass: removeClass
};
})();
/*********************
* Application Code
********************/
/**
* #function readyFunction
*
* #type {Function}
*/
const readyFunction = (() => {
const KEY_UP = 38;
const KEY_DOWN = 40;
let scrollingClass = 'js-scrolling',
scrollingActiveClass = scrollingClass + '--active',
scrollingInactiveClass = scrollingClass + '--inactive',
scrollingTime = 1350,
scrollingIsActive = false,
currentPage = 1,
countOfPages = document.querySelectorAll('.' + scrollingClass + '__page').length,
prefixPage = '.' + scrollingClass + '__page-',
_switchPages,
_scrollingUp,
_scrollingDown,
_mouseWheelEvent,
_keyDownEvent,
init;
/**
* #function _switchPages
*
* #private
*/
_switchPages = () => {
let _getPageDomEl;
/**
* #function _getPageDomEl
*
* #param page
* #returns {Element}
* #private
*/
_getPageDomEl = (page = currentPage) => {
return document.querySelector(prefixPage + page);
};
scrollingIsActive = true;
ProjectAPI.removeClass(
_getPageDomEl(),
scrollingInactiveClass
);
ProjectAPI.addClass(
_getPageDomEl(),
scrollingActiveClass
);
ProjectAPI.addClass(
_getPageDomEl(currentPage - 1),
scrollingInactiveClass
);
ProjectAPI.removeClass(
_getPageDomEl(currentPage + 1),
scrollingActiveClass
);
setTimeout(
() => {
return scrollingIsActive = false;
},
scrollingTime
);
};
/**
* #function _scrollingUp
*
* #private
*/
_scrollingUp = () => {
if (currentPage === 1) {
return;
}
currentPage--;
_switchPages();
};
/**
* #function _scrollingDown
*
* #private
*/
_scrollingDown = () => {
if (currentPage === countOfPages) {
return;
}
currentPage++;
_switchPages();
};
/**
* #function _mouseWheelEvent
*
* #param e
* #private
*/
_mouseWheelEvent = (e) => {
if (scrollingIsActive) {
return;
}
if (e.wheelDelta > 0 || e.detail < 0) {
_scrollingUp();
}
else if (e.wheelDelta < 0 || e.detail > 0) {
_scrollingDown();
}
};
/**
* #function _keyDownEvent
*
* #param e
* #private
*/
_keyDownEvent = (e) => {
if (scrollingIsActive) {
return;
}
let keyCode = e.keyCode || e.which;
if (keyCode === KEY_UP) {
_scrollingUp();
}
else if (keyCode === KEY_DOWN) {
_scrollingDown();
}
};
/**
* #function init
*
* #note auto-launch
*/
init = (() => {
document.addEventListener(
'mousewheel',
_mouseWheelEvent,
false
);
document.addEventListener(
'DOMMouseScroll',
_mouseWheelEvent,
false
);
document.addEventListener(
'keydown',
_keyDownEvent,
false
);
})();
});
/**
* Launcher
*/
DOMReady(readyFunction);
/***********************
* Variables
**********************/
/***********************
* Project Main Styles
**********************/
*,
*:before,
*:after {
box-sizing: border-box;
margin: 0;
padding: 0; }
body {
font-family: "Open Sans", sans-serif;
background-color: #282828; }
.slider-pages {
overflow: hidden;
position: relative;
zoom: 59%;
width: 94%;
left: 3%;
height: 100vh; }
.slider-page {
position: absolute;
top: 0;
width: 50%;
height: 100vh;
transition: transform 1350ms; }
.slider-page--skew {
overflow: hidden;
position: absolute;
top: 0;
width: 140%;
height: 100%;
background: #282828;
transform: skewX(-18deg); }
.slider-page--left {
left: 0;
transform: translateX(-32.5vh) translateY(100%) translateZ(0); }
.slider-page--left .slider-page--skew {
left: -40%; }
.slider-page--left .slider-page__content {
padding: auto 30% auto 30%;
transform-origin: 100% 0; }
.slider-page--right {
left: 50%;
transform: translateX(32.5vh) translateY(-100%) translateZ(0); }
.slider-page--right .slider-page--skew {
right: -40%; }
.slider-page--right .slider-page__content {
padding: auto 30% auto 30%;
transform-origin: 0 100%; }
.slider-page__content {
position: absolute;
display: flex;
justify-content: center;
align-items: center;
flex-flow: column wrap;
top: 0;
left: 0;
width: 100%;
height: 100%;
padding: 0 30% 0 30%;
color: #e2e2e2;
background-size: cover;
transform: skewX(18deg);
transition: transform 1350ms; }
.slider-page__title {
margin-bottom: 1em;
font-size: 1em;
text-align: center;
text-transform: uppercase; }
.slider-page__title--big {
font-size: 1.2em; }
.slider-page__description {
font-size: 1em;
text-align: center; }
.slider-page__link {
color: #80a1c1; }
.slider-page__link:hover, .slider-page__link:focus {
color: #6386a9;
text-decoration: none; }
/***********************
* Project JS Styles
**********************/
.js-scrolling__page {
position: absolute;
top: 0;
left: 0;
width: 100%; }
.js-scrolling--active .slider-page {
transform: translateX(0) translateY(0) translateZ(0); }
.js-scrolling--inactive .slider-page__content {
transform: skewX(18deg) scale(0.9); }
.js-scrolling__page-1 .slider-page--left .slider-page__content {
background-image: url("https://cdn.discordapp.com/attachments/584536200052867077/687769359183380537/ram-of-re-zero-starting-life-in-another-world-wallpaper-3440x1440-2148_15.png"); }
.js-scrolling__page-1 .slider-page--right .slider-page__content {
background-color: #282828; }
.js-scrolling__page-2 .slider-page--left .slider-page__content {
background-color: #e2e2e2; }
.js-scrolling__page-2 .slider-page--left .slider-page__title,
.js-scrolling__page-2 .slider-page--left .slider-page__description {
color: #282828; }
.js-scrolling__page-2 .slider-page--right .slider-page__content {
background-image: url("https://cdn.discordapp.com/attachments/584536200052867077/687766774950789160/9ibz1cnnwdp31.png"); }
.js-scrolling__page-3 .slider-page--left .slider-page__content {
background-image: url("https://cdn.discordapp.com/attachments/584536200052867077/687773688782913563/9ibz1cnnwdp31.png"); }
.js-scrolling__page-3 .slider-page--right .slider-page__content {
background-color: #282828; }
<section class="slider-pages">
<article class="js-scrolling__page js-scrolling__page-1 js-scrolling--active">
<div class="slider-page slider-page--left">
<div class="slider-page--skew">
<div class="slider-page__content">
</div>
<!-- /.slider-page__content -->
</div>
<!-- /.slider-page--skew -->
</div>
<!-- /.slider-page slider-page--left -->
<div class="slider-page slider-page--right">
<div class="slider-page--skew">
<div class="slider-page__content">
<h1 class="slider-page__title slider-page__title--big">
Re:Zero kara Hajimeru Isekai Seikatsu
</h1>
<!-- /.slider-page__title slider-page__title--big -->
<h2 class="slider-page__title">
</h2>
<!-- /.slider-page__title -->
<p class="slider-page__description">
End
</p>
<!-- /.slider-page__description -->
</div>
<!-- /.slider-page__content -->
</div>
<!-- /.slider-page--skew -->
</div>
<!-- /.slider-page slider-page--right -->
</article>
<!-- /.js-scrolling__page js-scrolling__page-1 js-scrolling--active -->
<article class="js-scrolling__page js-scrolling__page-2">
<div class="slider-page slider-page--left">
<div class="slider-page--skew">
<div class="slider-page__content">
<h1 class="slider-page__title">
EVANGELION 3.0 + 1.0
</h1>
<!-- /.slider-page__title -->
<p class="slider-page__description">
ENd
</p>
<!-- /.slider-page__description -->
</div>
<!-- /.slider-page__content -->
</div>
<!-- /.slider-page--skew -->
</div>
<!-- /.slider-page slider-page--left -->
<div class="slider-page slider-page--right">
<div class="slider-page--skew">
<div class="slider-page__content">
</div>
<!-- /.slider-page__content -->
</div>
<!-- /.slider-page--skew -->
</div>
<!-- /.slider-page slider-page--right -->
</article>
<!-- /.js-scrolling__page js-scrolling__page-2 -->

You can use the functions you already defined, namely _scrollingUp and _scrollingDown, and assign them to your buttons' onclick events. By doing this, these functions will be called whenever the right button is clicked.
A simplified example would be:
document.getElementById("prev").onclick = _scrollingUp;
document.getElementById("next").onclick = _scrollingDown;
<button id="prev">Previous</button>
<button id="next">Next</button>

Related

Smooth scroll using translateY in js

I created class based functions in my project. Scroll class is to create smooth scroll behaviour using translateY property. The second one called SideNavigation generate bullet list navigation based on projects elements length. I want to achive smooth scroll effect also on click on those bullets, but can't find solution for this. Code snippet included. Hope anyone can help with this.
const config = {
ease: 0.1,
current: 0,
previous: 0,
rounded: 0
}
class Scroll {
constructor(velocity) {
this.velocity = velocity
}
setBodyHeight() {
document.body.style.height = document.getElementById('projects').getBoundingClientRect().height + 'px'
}
isMobile() {
return 'ontouchstart' in document.documentElement && navigator.userAgent.match(/Mobi/)
}
onScroll() {
config.current = window.scrollY
config.previous += (config.current - config.previous) * config.ease
config.rounded = Math.round(config.previous * 100) / 100
const difference = config.current - config.rounded
const acceleration = difference / document.body.clientWidth
const velocity = +acceleration
const skew = velocity * this.velocity
const element = document.getElementById('projects')
this.isMobile() ? element.style.transform = `skewY(${skew}deg)` : element.style.transform = `translateY(-${config.rounded}px)`
requestAnimationFrame(() => this.onScroll())
}
}
class SideNavigation {
constructor() {
createBullets()
}
}
function createBullets() {
const bulletWrapper = document.createElement('div')
const bulletList = document.createElement('ul')
bulletWrapper.classList.add('side-nav')
for (let i = 0; i < document.getElementsByClassName('project').length; i++) {
const bullet = document.createElement('li')
bullet.setAttribute('id', '' + i)
bullet.addEventListener('click', event => {
console.log(document.getElementsByClassName('project')[parseInt(event.target.id)].offsetTop)
// scroll to current section
})
bulletList.append(bullet)
bulletWrapper.append(bulletList)
document.body.append(bulletWrapper)
}
}
window.addEventListener('load', () => {
const scrollInstance = new Scroll(8, true)
const sideNav = new SideNavigation()
scrollInstance.setBodyHeight()
requestAnimationFrame(() => scrollInstance.onScroll())
})
html,
body {
height: 100%;
}
main {
position: fixed;
left: 0;
top: 0;
height: 100%;
width: 100%;
overflow: hidden;
}
#projects {
width: 80%;
}
.project {
height: 500px;
width: 100%;
background: #333;
color: #fff;
}
.side-nav {
position: fixed;
right: 20px;
top: 20%;
z-index: 10;
}
.side-nav li {
width: 30px;
height: 30px;
display: block;
background: #333;
margin-bottom: 20px;
border-radius: 50%;
cursor: pointer;
}
<body>
<main>
<div id="projects">
<div class="project">
<p>Some text example</p>
</div>
<div class="project">
<p>Some text example</p>
</div>
<div class="project">
<p>Some text example</p>
</div>
<div class="project">
<p>Some text example</p>
</div>
<div class="project">
<p>Some text example</p>
</div>
</div>
</main>
</body>
I hope I understood your question correctly. Is this what you're looking for?
const config = {
ease: 0.1,
current: 0,
previous: 0,
rounded: 0
}
class Scroll {
constructor(velocity) {
this.velocity = velocity
}
setBodyHeight() {
document.body.style.height = document.getElementById('projects').getBoundingClientRect().height + 'px'
}
isMobile() {
return 'ontouchstart' in document.documentElement && navigator.userAgent.match(/Mobi/)
}
onScroll() {
config.current = window.scrollY
config.previous += (config.current - config.previous) * config.ease
config.rounded = Math.round(config.previous * 100) / 100
const difference = config.current - config.rounded
const acceleration = difference / document.body.clientWidth
const velocity = +acceleration
const skew = velocity * this.velocity
const element = document.getElementById('projects')
this.isMobile() ? element.style.transform = `skewY(${skew}deg)` : element.style.transform = `translateY(-${config.rounded}px)`
requestAnimationFrame(() => this.onScroll())
}
}
class SideNavigation {
constructor() {
createBullets()
}
}
function createBullets() {
const bulletWrapper = document.createElement('div')
const bulletList = document.createElement('ul')
bulletWrapper.classList.add('side-nav')
for (let i = 0; i < document.getElementsByClassName('project').length; i++) {
const bullet = document.createElement('li')
bullet.setAttribute('id', '' + i)
bullet.addEventListener('click', event => {
console.log(document.getElementsByClassName('project')[parseInt(event.target.id)].offsetTop)
// scroll to current section
window.scrollBy(0, document.getElementsByClassName('project')[parseInt(event.target.id)].offsetTop - window.pageYOffset);
})
bulletList.append(bullet)
bulletWrapper.append(bulletList)
document.body.append(bulletWrapper)
}
}
window.addEventListener('load', () => {
const scrollInstance = new Scroll(8, true)
const sideNav = new SideNavigation()
scrollInstance.setBodyHeight()
requestAnimationFrame(() => scrollInstance.onScroll())
})
html,
body {
height: 100%;
}
main {
position: fixed;
left: 0;
top: 0;
height: 100%;
width: 100%;
overflow: hidden;
}
#projects {
width: 80%;
}
.project {
height: 500px;
width: 100%;
background: #333;
color: #fff;
}
.side-nav {
position: fixed;
right: 20px;
top: 20%;
z-index: 10;
}
.side-nav li {
width: 30px;
height: 30px;
display: block;
background: #333;
margin-bottom: 20px;
border-radius: 50%;
cursor: pointer;
}
<body>
<main>
<div id="projects">
<div class="project">
<p>Some text example</p>
</div>
<div class="project">
<p>Some text example</p>
</div>
<div class="project">
<p>Some text example</p>
</div>
<div class="project">
<p>Some text example</p>
</div>
<div class="project">
<p>Some text example</p>
</div>
</div>
</main>
</body>
The scrollBy function's second parameter allows to modify the window's Y axis. But as we want each bullet to jump to the start of it's project, we decrease the current Y axis of the page from the Y axis of the project window.scrollBy(0, document.getElementsByClassName('project')[parseInt(event.target.id)].offsetTop - window.pageYOffset).

don't show pop-up again if it closed using javascript

How can I stop showing pop-up after clicking on close button?
This is my pop-up function, it opens after scrolling to 1300px of page.
$(document).scroll(function() {
var y = $(this).scrollTop();
if (y > 1300) {
$('.popup').fadeIn();
}
});
but when I closed it , it opend again
this is my button fun
function closePopup(){
document.getElementById('popup').style.display = 'none';
}
++ this is my button
<button type="button" class="close" id="close-popup" onclick="closePopup()" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
You can add a boolean control when it's clicked
let popupClosed = false;
function closePopup() {
document.getElementById('popup').style.display = 'none';
popupClosed = true;
}
$(document).scroll(function() {
var y = $(this).scrollTop();
if (y > 1300 && !popupClosed) {
$('.popup').fadeIn();
}
});
You need a way to control when the popup was opened for the first time (or closed).
$(document).scroll(function() {
let y = $(this).scrollTop(),
popup = $('.popup')
if (y > 1300 && ! popup.data('opened')) {
popup.data('opened', true)
popup.fadeIn();
}
});
I replaced your scroll height detection with a button. Just call $('.popup').popupShow() whenever you scroll past 1,300 pixels.
Make sure you call $('.popup').popup(options) with the appropriate close/open callbacks.
Once you close the popup for the first time, a data attribute of doNotOpen will be set to true. Subsequent open attempts will not be allowed, because the open callback checks for the presence of that doNotOpen data value.
function main() {
$('.popup').popup({
title: 'Popup Test',
open: function() {
return !this.data('doNotOpen'); // type boolean
},
close: function() {
this.data('doNotOpen', true);
}
});
$('.show-btn').on('click', function() {
$('.popup').popupShow();
});
}
/**
* #name flex-popup.jquery.js
* #date 2021-03-03
* #author Mr. Polywhirl
*
* Callback when opening a popup.
* #callback openCallback
* #return {boolean} whether to show the popup
*
* Callback when closing a popup.
* #callback closeCallback
*/
(function($) {
var defaultOptions = {
title: null,
content: null
};
var setAndDelete = function($el, prop, props) {
if (props[prop]) {
$el.html(props[prop]);
delete props[prop];
}
};
/**
* #param {string} title
* #param {string} content
* #param {options.openCallback} open
* #param {options.closeCallback} close
*/
$.fn.popup = function(options) {
var opts = $.extend(true, {}, defaultOptions, options);
if (this.is(':empty')) this.popupCreate();
this.find('.popup-close').on('click', function() {
$(this).closest('.popup').popupHide();
});
setAndDelete(this.find('.popup-header-title'), 'title', opts);
setAndDelete(this.find('.popup-content'), 'content', opts);
return this.data(opts).css('display', 'flex').hide();
};
$.fn.popupCreate = function() {
return this
.append($('<div>').addClass('popup-header')
.append($('<div>').addClass('popup-header-title'))
.append($('<div>').addClass('popup-close')))
.append($('<div>').addClass('popup-content'));
};
$.fn.popupShow = function() {
if (this.is(':hidden') && (!this.data('open') || this.data('open').call(this))) {
if (this.data('open')) this.data('open').call(this);
return this.fadeIn();
} else {
if (this.is(':hidden')) {
console.log('Not allowed!');
}
}
};
$.fn.popupHide = function() {
if (!this.is(':hidden')) {
if (this.data('close')) this.data('close').call(this);
return this.fadeOut();
}
};
})(jQuery);
main();
:root {
--popup-background: #AAA;
--popup-header-background: #777;
--popup-content-background: #AAA;
--popup-border-color: #555;
--popup-close-color: #BBB;
--popup-close-hover-color: #DDD;
}
body {
background: #222;
}
.popup {
display: flex;
flex-direction: column;
position: absolute;
top: 25vh;
left: 25vw;
width: 50vw;
height: 50vh;
z-index: 1000;
background: var(--popup-background);
border: thin solid var(--popup-border-color);
}
.popup>.popup-header {
display: flex;
flex-direction: row;
align-items: center;
background: var(--popup-header-background);
padding: 0.25em 0.5em;
}
.popup .popup-header-title {
flex: 1;
text-align: center;
font-weight: bold;
}
.popup .popup-close {
font-size: 2em;
line-height: 1em;
font-weight: bold;
color: var(--popup-close-color);
}
.popup .popup-close:hover {
color: var(--popup-close-hover-color);
cursor: pointer;
}
.popup .popup-close::after {
content: '\00D7';
}
.popup>.popup-content {
background: var(--popup-content-background);
flex: 1;
padding: 0.25em 0.5em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="popup">
<div class="popup-header">
<div class="popup-header-title">Replace this</div>
<div class="popup-close"></div>
</div>
<div class="popup-content">
<h1>Content heading</h1>
<p>Content description here.</p>
</div>
</div>
<button class="show-btn">Show Popup</button>
Note: Here is a mirror on JSFiddle.

Using setInterval to create a progress bar

I was hoping a kind soul might be able to assist.
I have a slideshow which auto-plays, my intention is to have the next button act as a visual aid, highlighting the when the next frame is coming in.
sync with the autoPlay interval.
Right now, the update func concludes too early, which is the best I have managed to do. Typically I have the clearInterval and setInterval conflicting creating shuddering animations.
What am I doing wrong?
<!doctype html>
<html lang="en">
<head>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
.carousel_wrapper {
height: 50vh;
width: 100%;
position: relative;
}
.carousel_frame {
width: 100%; height: 100%;
}
.carousel_controls {
position: absolute;
bottom: 0;
left: 0;
}
.prev, .next {
height: 50px;
width: 100px;
background: aqua;
display: inline-block;
}
.next {
background: linear-gradient(to right, white 0%, aqua);
}
.carousel_frame:nth-child(1) {
background: red;
}
.carousel_frame:nth-child(2) {
background: blue;
}
.carousel_frame:nth-child(3) {
background: green;
}
</style>
<script>
window.addEventListener('DOMContentLoaded', () => {
const homepage_carousel = new carousel();
});
function carousel() {
const carousel = document.getElementsByClassName('.carousel_wrapper')[0];
const frames = [...document.getElementsByClassName('carousel_frame')];
const prev_button = document.getElementsByClassName('prev')[0];
const next_button = document.getElementsByClassName('next')[0];
this.frameIndex = 1;
prev_button.addEventListener('click', () => {
this.resetPlay();
this.move(-1);
})
next_button.addEventListener('click', () => {
this.resetPlay();
this.move(+1);
})
this.hideAll = () => {
frames.forEach((f) => {
f.style.display = 'none';
});
}
this.show = () => {
this.hideAll();
frames[this.frameIndex - 1].style.display = 'block';
this.update_bg();
}
this.move = (amount) => {
this.frameIndex += amount;
this.frameIndex = (this.frameIndex > frames.length ? 1 : (this.frameIndex < 1) ? frame.lengh : this.frameIndex);
this.show();
}
this.update_bg = () => {
let w = 1;
let test = setInterval(adjust, 10);
function adjust() {
if (w >= 100) {
clearInterval(test);
w = 0;
} else {
w++;
next_button.style.backgroundImage = `linear-gradient(to right, white ${w}%, aqua)`
}
}
setInterval(adjust, 3000);
}
this.autoPlay = () => {
this.move(+1)
this.update_bg();
}
this.resetPlay = () => {
// clearInterval(timer);
// timer = setInterval(this.autoPlay(), 4000);
}
this.show();
const timer = setInterval(this.autoPlay, 3000);
}
</script>
</head>
<body>
<div class='carousel_wrapper'>
<div class='carousel_frame'>
<span>Headline</span>
<span>Description</span>
<span>CTA</span>
</div>
<div class='carousel_frame'>
<span>Headline</span>
<span>Description</span>
<span>CTA</span>
</div>
<div class='carousel_frame'>
<span>Headline</span>
<span>Description</span>
<span>CTA</span>
</div>
<div class='carousel_controls'>
<span class='prev'>Previous</span>
<span class='next'>
Next
</span>
</div>
</div>
</body>
</html>

jQuery prev/next button in polaroid gallery plugin

I am using a polaroid image gallery plugin. The way it works, the polaroid images are scattered in a div and it has some circle nav buttons at the bottom that can be clicked to make the selected image active and moves it to the middle.
Instead of having circle nav buttons for selecting each image, I wanted to use prev/next buttons (this way it won't show 20+ circle nav icons when the gallery has more than 20 photos).
I was able to add some prev/next buttons and get them working, but there is one slight issue I cannot figure out. When the gallery loads, if you select the prev/next buttons, the gallery works as intended, it will switch the photos as necessary when the buttons are clicked. However, if the user clicks anywhere in the gallery (not on the buttons) it will shuffle all of the photos (it should not shuffle), then once a user does this, the prev/next buttons no longer work until the page is refreshed.
I am still learning jQuery/js and I cannot figure out what is causing this. I need to restrict the shuffling and selecting of the photos only when the prev/next buttons are selected because if a user accidentally clicks anywhere in the gallery, the buttons break.
I created a jsfiddle here.
The html is pretty straight forward, here is an example with the prev/next buttons I added:
<section id="photostack-1" class="photostack photostack-start">
<div>
<figure>
<img src="https://tympanus.net/Development/ScatteredPolaroidsGallery/img/5.jpg" alt="img05"/>
<figcaption>
<h2 class="photostack-title">Speed Racer</h2>
</figcaption>
</figure>
<figure>
<img src="https://tympanus.net/Development/ScatteredPolaroidsGallery/img/2.jpg" alt="img02"/>
<figcaption>
<h2 class="photostack-title">Happy Days</h2>
</figcaption>
</figure>
<figure>
<img src="https://tympanus.net/Development/ScatteredPolaroidsGallery/img/3.jpg" alt="img03"/>
<figcaption>
<h2 class="photostack-title">Beautywood</h2>
</figcaption>
</figure>
<figure>
<img src="https://tympanus.net/Development/ScatteredPolaroidsGallery/img/1.jpg" alt="img01"/>
<figcaption>
<h2 class="photostack-title">Serenity Beach</h2>
</figcaption>
</figure>
<figure>
<img src="https://tympanus.net/Development/ScatteredPolaroidsGallery/img/4.jpg" alt="img04"/>
<figcaption>
<h2 class="photostack-title">Heaven of time</h2>
</figcaption>
</figure>
<figure>
<img src="https://tympanus.net/Development/ScatteredPolaroidsGallery/img/6.jpg" alt="img06"/>
<figcaption>
<h2 class="photostack-title">Forever this</h2>
</figcaption>
</figure>
<figure>
<img src="https://tympanus.net/Development/ScatteredPolaroidsGallery/img/7.jpg" alt="img07"/>
<figcaption>
<h2 class="photostack-title">Lovely Green</h2>
</figcaption>
</figure>
<figure>
<img src="https://tympanus.net/Development/ScatteredPolaroidsGallery/img/8.jpg" alt="img08"/>
<figcaption>
<h2 class="photostack-title">Wonderful</h2>
</figcaption>
</figure>
<figure>
<img src="https://tympanus.net/Development/ScatteredPolaroidsGallery/img/9.jpg" alt="img09"/>
<figcaption>
<h2 class="photostack-title">Love Addict</h2>
</figcaption>
</figure>
<figure>
<img src="https://tympanus.net/Development/ScatteredPolaroidsGallery/img/10.jpg" alt="img10"/>
<figcaption>
<h2 class="photostack-title">Friendship</h2>
</figcaption>
</figure>
<figure>
<img src="https://tympanus.net/Development/ScatteredPolaroidsGallery/img/11.jpg" alt="img11"/>
<figcaption>
<h2 class="photostack-title">White Nights</h2>
</figcaption>
</figure>
<figure>
<img src="https://tympanus.net/Development/ScatteredPolaroidsGallery/img/12.jpg" alt="img12"/>
<figcaption>
<h2 class="photostack-title">Serendipity</h2>
</figcaption>
</figure>
<figure>
<img src="https://tympanus.net/Development/ScatteredPolaroidsGallery/img/13.jpg" alt="img13"/>
<figcaption>
<h2 class="photostack-title">Pure Soul</h2>
</figcaption>
</figure>
<figure>
<img src="https://tympanus.net/Development/ScatteredPolaroidsGallery/img/14.jpg" alt="img14"/>
<figcaption>
<h2 class="photostack-title">Winds of Peace</h2>
</figcaption>
</figure>
<figure>
<img src="https://tympanus.net/Development/ScatteredPolaroidsGallery/img/15.jpg" alt="img15"/>
<figcaption>
<h2 class="photostack-title">Shades of blue</h2>
</figcaption>
</figure>
<figure>
<img src="https://tympanus.net/Development/ScatteredPolaroidsGallery/img/16.jpg" alt="img16"/>
<figcaption>
<h2 class="photostack-title">Lightness</h2>
</figcaption>
</figure>
</div>
<!-- Next and Previous controls -->
<div id="imageControls">
<button id="leftArrowGallery" class="btnGallery"><i class="fa fa-chevron-left"></i></button>
<button id="rightArrowGallery" class="btnGallery"><i class="fa fa-chevron-right"></i></button>
</div>
</section>
The custom jQuery used to add the prev/next buttons and remove the circle nav icons is:
var ps = new Photostack( document.getElementById( 'photostack-1' ), {});
$("#leftArrowGallery").prependTo($(".photostack > nav"));
$("#rightArrowGallery").appendTo($(".photostack > nav"));
$("#leftArrowGallery").on("click", function () {
ps.navigate('prev');
});
$("#rightArrowGallery").on("click", function () {
ps.navigate('next');
});
$(".photostack > nav > span").each(function(){ $(this).remove(); });
You can view all of the js for the plugin in the jsfiddle.
Screenshot example of original gallery with circle nav icons:
Screenshot example of gallery with custom prev/next buttons added:
Again, the buttons are working correctly, I just need to prevent when someone clicks anywhere in the gallery, it shuffles the images then the prev/next buttons break and no longer work until the page is refreshed.
Thank you for your help!
I read your code and I found out that the biggest problem when you put photostack-start class is that every time you click on photostack stage you schuffle your photos twice: once in _photoShow function and once in open function (open function is triggered every time). To resolve your problem, a solution could be to stop one schuffled action. To do this I created a variable and I put it in open function:
if( this.open ) {
return false;
}
this.open = true;
Now, _open function is triggered only once (when you click on button "view gallery") and after that only _photoShow works so your code works finally as you want.
BE CAREFUL: In this example I removed some pics 'cause I have a character limit here (30000), but the code will work anyway also with more pics.
A fiddle with more pics: https://jsfiddle.net/m46cxkhg/217/ (tested with Chrome and Firefox)
;( function( window ) {
'use strict';
Modernizr.addTest('csstransformspreserve3d', function () {
var prop = Modernizr.prefixed('transformStyle');
var val = 'preserve-3d';
var computedStyle;
if(!prop) return false;
prop = prop.replace(/([A-Z])/g, function(str,m1){ return '-' + m1.toLowerCase(); }).replace(/^ms-/,'-ms-');
Modernizr.testStyles('#modernizr{' + prop + ':' + val + ';}', function (el, rule) {
computedStyle = window.getComputedStyle ? getComputedStyle(el, null).getPropertyValue(prop) : '';
});
return (computedStyle === val);
});
var support = {
transitions : Modernizr.csstransitions,
preserve3d : Modernizr.csstransformspreserve3d
},
transEndEventNames = {
'WebkitTransition': 'webkitTransitionEnd',
'MozTransition': 'transitionend',
'OTransition': 'oTransitionEnd',
'msTransition': 'MSTransitionEnd',
'transition': 'transitionend'
},
transEndEventName = transEndEventNames[ Modernizr.prefixed( 'transition' ) ];
function extend( a, b ) {
for( var key in b ) {
if( b.hasOwnProperty( key ) ) {
a[key] = b[key];
}
}
return a;
}
function shuffleMArray( marray ) {
var arr = [], marrlen = marray.length, inArrLen = marray[0].length;
for(var i = 0; i < marrlen; i++) {
arr = arr.concat( marray[i] );
}
arr = shuffleArr( arr );
var newmarr = [], pos = 0;
for( var j = 0; j < marrlen; j++ ) {
var tmparr = [];
for( var k = 0; k < inArrLen; k++ ) {
tmparr.push( arr[ pos ] );
pos++;
}
newmarr.push( tmparr );
}
return newmarr;
}
function shuffleArr( array ) {
var m = array.length, t, i;
while (m) {
i = Math.floor(Math.random() * m--);
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}
function Photostack( el, options ) {
this.el = el;
this.inner = this.el.querySelector( 'div' );
this.allItems = [].slice.call( this.inner.children );
this.allItemsCount = this.allItems.length;
if( !this.allItemsCount ) return;
this.items = [].slice.call( this.inner.querySelectorAll( 'figure:not([data-dummy])' ) );
this.itemsCount = this.items.length;
this.options = extend( {}, this.options );
extend( this.options, options );
this.current = this.options.start;
this._init();
var ps = this;
return {
showPhoto: function(idx) {
ps._showPhoto.call(ps, idx);
},
open: function() {
ps._open.call(ps, true);
},
navigate: function(dir) {
ps._navigate.call(ps, dir);
},
}
}
Photostack.prototype.options = {
start: 0,
showNavigation: true,
afterInit: null,
afterShowPhoto: null,
afterNavigate: null
};
Photostack.prototype._init = function() {
this.currentItem = this.items[ this.current ];
if(this.options.showNavigation) {
this._addNavigation();
}
this._getSizes();
this._initEvents();
if(this.options.afterInit) {
this.options.afterInit(this);
}
}
Photostack.prototype._addNavigation = function() {
// add nav dots
this.nav = document.createElement( 'nav' )
var inner = '';
for( var i = 0; i < this.itemsCount; ++i ) {
inner += '<span></span>';
}
this.nav.innerHTML = inner;
this.el.appendChild( this.nav );
this.navDots = [].slice.call( this.nav.children );
}
Photostack.prototype._open = function( beforeStep ) {
/* I added this */
if( this.open ) {
return false;
}
this.open = true;
/* End of change */
var self = this,
el = this.el;
var setTransition = function() {
if( support.transitions ) {
classie.addClass( el, 'photostack-transition' );
}
}
if( beforeStep ) {
el.removeEventListener( 'click', open );
classie.removeClass( el, 'photostack-start' );
setTransition();
}
else {
self.openDefault = true;
setTimeout( setTransition, 25 );
}
self.started = true;
self._showPhoto( self.current );
};
Photostack.prototype._initEvents = function() {
if(this.options.clickToFlip == 'true')
{
this.items.forEach(function(img, idx){
img.addEventListener('click', function(event){
event.preventDefault();
if( idx === self.current ) {
self._rotateItem();
}
})
});
}
var self = this,
beforeStep = classie.hasClass( this.el, 'photostack-start' );
if( beforeStep ) {
this._shuffle();
this.el.addEventListener( 'click', function() {
self._open(beforeStep);
});
}
else {
this._open(beforeStep);
}
if(this.options.showNavigation) {
this.navDots.forEach( function( dot, idx ) {
dot.addEventListener( 'click', function() {
if( idx === self.current ) {
self._rotateItem();
}
else {
// if the photo is flipped then rotate it back before shuffling again
var callback = function() { self._showPhoto( idx ); }
if( self.flipped ) {
self._rotateItem( callback );
}
else {
callback();
}
}
} );
} );
}
window.addEventListener( 'resize', function() { self._resizeHandler(); } );
}
Photostack.prototype._resizeHandler = function() {
var self = this;
function delayed() {
self._resize();
self._resizeTimeout = null;
}
if ( this._resizeTimeout ) {
clearTimeout( this._resizeTimeout );
}
this._resizeTimeout = setTimeout( delayed, 100 );
}
Photostack.prototype._resize = function() {
var self = this, callback = function() { self._shuffle( true ); }
this._getSizes();
if( this.started && this.flipped ) {
this._rotateItem( callback );
}
else {
callback();
}
}
Photostack.prototype._showPhoto = function( pos ) {
if( this.isShuffling ) {
return false;
}
this.isShuffling = true;
// if there is something behind..
if( classie.hasClass( this.currentItem, 'photostack-flip' ) ) {
this._removeItemPerspective();
if(this.options.showNavigation) {
classie.removeClass( this.navDots[ this.current ], 'flippable' );
}
}
if(this.options.showNavigation) {
classie.removeClass( this.navDots[ this.current ], 'current' );
}
classie.removeClass( this.currentItem, 'photostack-current' );
// change current
this.current = pos;
this.currentItem = this.items[ this.current ];
if(this.options.showNavigation) {
classie.addClass( this.navDots[ this.current ], 'current' );
}
// if there is something behind..
if( this.options.showNavigation && this.currentItem.querySelector( '.photostack-back' ) ) {
// nav dot gets class flippable
classie.addClass( this.navDots[ pos ], 'flippable' );
}
// shuffle a bit
this._shuffle();
if(this.options.afterShowPhoto) {
this.options.afterShowPhoto(this);
}
}
// display items (randomly)
Photostack.prototype._shuffle = function( resize ) {
var iter = resize ? 1 : this.currentItem.getAttribute( 'data-shuffle-iteration' ) || 1;
if( iter <= 0 || !this.started || this.openDefault ) { iter = 1; }
// first item is open by default
if( this.openDefault ) {
// change transform-origin
classie.addClass( this.currentItem, 'photostack-flip' );
this.openDefault = false;
this.isShuffling = false;
}
var overlapFactor = .5,
// lines & columns
lines = Math.ceil(this.sizes.inner.width / (this.sizes.item.width * overlapFactor) ),
columns = Math.ceil(this.sizes.inner.height / (this.sizes.item.height * overlapFactor) ),
// since we are rounding up the previous calcs we need to know how much more we are adding to the calcs for both x and y axis
addX = lines * this.sizes.item.width * overlapFactor + this.sizes.item.width/2 - this.sizes.inner.width,
addY = columns * this.sizes.item.height * overlapFactor + this.sizes.item.height/2 - this.sizes.inner.height,
// we will want to center the grid
extraX = addX / 2,
extraY = addY / 2,
// max and min rotation angles
maxrot = 35, minrot = -35,
self = this,
// translate/rotate items
moveItems = function() {
--iter;
// create a "grid" of possible positions
var grid = [];
// populate the positions grid
for( var i = 0; i < columns; ++i ) {
var col = grid[ i ] = [];
for( var j = 0; j < lines; ++j ) {
var xVal = j * (self.sizes.item.width * overlapFactor) - extraX,
yVal = i * (self.sizes.item.height * overlapFactor) - extraY,
olx = 0, oly = 0;
if( self.started && iter === 0 ) {
var ol = self._isOverlapping( { x : xVal, y : yVal } );
if( ol.overlapping ) {
olx = ol.noOverlap.x;
oly = ol.noOverlap.y;
var r = Math.floor( Math.random() * 3 );
switch(r) {
case 0 : olx = 0; break;
case 1 : oly = 0; break;
}
}
}
col[ j ] = { x : xVal + olx, y : yVal + oly };
}
}
// shuffle
grid = shuffleMArray(grid);
var l = 0, c = 0, cntItemsAnim = 0;
self.allItems.forEach( function( item, i ) {
// pick a random item from the grid
if( l === lines - 1 ) {
c = c === columns - 1 ? 0 : c + 1;
l = 1;
}
else {
++l
}
var randXPos = Math.floor( Math.random() * lines ),
randYPos = Math.floor( Math.random() * columns ),
gridVal = grid[c][l-1],
translation = { x : gridVal.x, y : gridVal.y },
onEndTransitionFn = function() {
++cntItemsAnim;
if( support.transitions ) {
this.removeEventListener( transEndEventName, onEndTransitionFn );
}
if( cntItemsAnim === self.allItemsCount ) {
if( iter > 0 ) {
moveItems.call();
}
else {
// change transform-origin
classie.addClass( self.currentItem, 'photostack-flip' );
// all done..
self.isShuffling = false;
if( typeof self.options.callback === 'function' ) {
self.options.callback( self.currentItem );
}
}
}
};
if(self.items.indexOf(item) === self.current && self.started && iter === 0) {
self.currentItem.style.WebkitTransform = 'translate(' + self.centerItem.x + 'px,' + self.centerItem.y + 'px) rotate(0deg)';
self.currentItem.style.msTransform = 'translate(' + self.centerItem.x + 'px,' + self.centerItem.y + 'px) rotate(0deg)';
self.currentItem.style.transform = 'translate(' + self.centerItem.x + 'px,' + self.centerItem.y + 'px) rotate(0deg)';
// if there is something behind..
if( self.currentItem.querySelector( '.photostack-back' ) ) {
self._addItemPerspective();
}
classie.addClass( self.currentItem, 'photostack-current' );
}
else {
item.style.WebkitTransform = 'translate(' + translation.x + 'px,' + translation.y + 'px) rotate(' + Math.floor( Math.random() * (maxrot - minrot + 1) + minrot ) + 'deg)';
item.style.msTransform = 'translate(' + translation.x + 'px,' + translation.y + 'px) rotate(' + Math.floor( Math.random() * (maxrot - minrot + 1) + minrot ) + 'deg)';
item.style.transform = 'translate(' + translation.x + 'px,' + translation.y + 'px) rotate(' + Math.floor( Math.random() * (maxrot - minrot + 1) + minrot ) + 'deg)';
}
if( self.started ) {
if( support.transitions ) {
item.addEventListener( transEndEventName, onEndTransitionFn );
}
else {
onEndTransitionFn();
}
}
} );
};
moveItems.call();
}
Photostack.prototype._navigate = function(dir) {
var current = this.current,
itemsCount = this.itemsCount,
lastItem = itemsCount - 1,
idx = 0;
if(dir == 'next') {
idx = current < lastItem ? current + 1 : 0
} else if(dir == 'prev') {
idx = current > 0 ? current - 1 : lastItem;
}
this._showPhoto(idx);
if(this.options.afterNavigate) {
this.options.afterNavigate(this);
}
}
Photostack.prototype._getSizes = function() {
this.sizes = {
inner : { width : this.inner.offsetWidth, height : this.inner.offsetHeight },
item : { width : this.currentItem.offsetWidth, height : this.currentItem.offsetHeight }
};
// translation values to center an item
this.centerItem = { x : this.sizes.inner.width / 2 - this.sizes.item.width / 2, y : this.sizes.inner.height / 2 - this.sizes.item.height / 2 };
}
Photostack.prototype._isOverlapping = function( itemVal ) {
var dxArea = this.sizes.item.width + this.sizes.item.width / 3, // adding some extra avoids any rotated item to touch the central area
dyArea = this.sizes.item.height + this.sizes.item.height / 3,
areaVal = { x : this.sizes.inner.width / 2 - dxArea / 2, y : this.sizes.inner.height / 2 - dyArea / 2 },
dxItem = this.sizes.item.width,
dyItem = this.sizes.item.height;
if( !(( itemVal.x + dxItem ) < areaVal.x ||
itemVal.x > ( areaVal.x + dxArea ) ||
( itemVal.y + dyItem ) < areaVal.y ||
itemVal.y > ( areaVal.y + dyArea )) ) {
// how much to move so it does not overlap?
// move left / or move right
var left = Math.random() < 0.5,
randExtraX = Math.floor( Math.random() * (dxItem/4 + 1) ),
randExtraY = Math.floor( Math.random() * (dyItem/4 + 1) ),
noOverlapX = left ? (itemVal.x - areaVal.x + dxItem) * -1 - randExtraX : (areaVal.x + dxArea) - (itemVal.x + dxItem) + dxItem + randExtraX,
noOverlapY = left ? (itemVal.y - areaVal.y + dyItem) * -1 - randExtraY : (areaVal.y + dyArea) - (itemVal.y + dyItem) + dyItem + randExtraY;
return {
overlapping : true,
noOverlap : { x : noOverlapX, y : noOverlapY }
}
}
return {
overlapping : false
}
}
Photostack.prototype._addItemPerspective = function() {
classie.addClass( this.el, 'photostack-perspective' );
}
Photostack.prototype._removeItemPerspective = function() {
classie.removeClass( this.el, 'photostack-perspective' );
classie.removeClass( this.currentItem, 'photostack-flip' );
}
Photostack.prototype._rotateItem = function( callback ) {
if( classie.hasClass( this.el, 'photostack-perspective' ) && !this.isRotating && !this.isShuffling ) {
this.isRotating = true;
var self = this, onEndTransitionFn = function() {
if( support.transitions && support.preserve3d ) {
this.removeEventListener( transEndEventName, onEndTransitionFn );
}
self.isRotating = false;
if( typeof callback === 'function' ) {
callback();
}
};
if( this.flipped ) {
if(this.options.showNavigation) {
classie.removeClass( this.navDots[ this.current ], 'flip' );
}
if( support.preserve3d ) {
this.currentItem.style.WebkitTransform = 'translate(' + this.centerItem.x + 'px,' + this.centerItem.y + 'px) rotateY(0deg)';
this.currentItem.style.transform = 'translate(' + this.centerItem.x + 'px,' + this.centerItem.y + 'px) rotateY(0deg)';
}
else {
classie.removeClass( this.currentItem, 'photostack-showback' );
}
}
else {
if(this.options.showNavigation) {
classie.addClass( this.navDots[ this.current ], 'flip' );
}
if( support.preserve3d ) {
this.currentItem.style.WebkitTransform = 'translate(' + this.centerItem.x + 'px,' + this.centerItem.y + 'px) translate(' + this.sizes.item.width + 'px) rotateY(-179.9deg)';
this.currentItem.style.transform = 'translate(' + this.centerItem.x + 'px,' + this.centerItem.y + 'px) translate(' + this.sizes.item.width + 'px) rotateY(-179.9deg)';
}
else {
classie.addClass( this.currentItem, 'photostack-showback' );
}
}
this.flipped = !this.flipped;
if( support.transitions && support.preserve3d ) {
this.currentItem.addEventListener( transEndEventName, onEndTransitionFn );
}
else {
onEndTransitionFn();
}
}
}
// add to global namespace
window.Photostack = Photostack;
})( window );
var ps = new Photostack( document.getElementById( 'photostack-1' ), {});
$("#leftArrowGallery").prependTo($(".photostack > nav"));
$("#rightArrowGallery").appendTo($(".photostack > nav"));
$("#leftArrowGallery").on("click", function () {
ps.navigate('prev');
});
$("#rightArrowGallery").on("click", function () {
ps.navigate('next');
});
$(".photostack > nav > span").each(function(){ $(this).remove(); });
.photostack {
background: #ddd;
position: relative;
text-align: center;
overflow: hidden;
}
.js .photostack {
height: 580px;
}
.photostack-start {
cursor: pointer;
}
.photostack > div {
width: 100%;
height: 100%;
margin: 0 auto;
}
.photostack figure {
width: 320px;
height: 360px;
position: relative;
display: inline-block;
background: #fff;
padding: 40px;
text-align: center;
margin: 5px;
}
.js .photostack figure {
position: absolute;
display: block;
margin: 0;
}
.photostack figcaption h2 {
margin: 20px 0 0 0;
color: #a7a0a2;
font-size: 16px;
}
.photostack-img {
outline: none;
width: 240px;
height: 240px;
background: #f9f9f9;
}
.photostack-back {
display: none;
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
background: #fff;
font-family: "Give You Glory", cursive;
color: #a7a0a2;
padding: 50px 40px;
text-align: left;
font-size: 22px;
line-height: 1.25;
z-index: 1;
}
.photostack-back p {
margin: 0;
}
.photostack-back p span {
text-decoration: line-through;
}
.photostack nav {
position: absolute;
width: 100%;
bottom: 30px;
z-index: 90;
text-align: center;
left: 0;
-webkit-transition: opacity 0.3s;
transition: opacity 0.3s;
}
.photostack-start nav {
opacity: 0;
}
.photostack nav span {
position: relative;
display: inline-block;
margin: 0 5px;
width: 30px;
height: 30px;
cursor: pointer;
background: #aaa;
border-radius: 50%;
text-align: center;
-webkit-transition: -webkit-transform 0.6s ease-in-out, background 0.3s;
transition: transform 0.6s ease-in-out, background 0.3s;
-webkit-transform: scale(0.48);
transform: scale(0.48);
}
.photostack nav span:last-child {
margin-right: 0;
}
.photostack nav span::after {
content: "\e600";
font-family: 'icons';
font-size: 80%;
speak: none;
display: inline-block;
vertical-align: top;
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
line-height: 30px;
color: #fff;
opacity: 0;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-transition: opacity 0.3s;
transition: opacity 0.3s;
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
}
.photostack nav span.current {
background: #888;
-webkit-transform: scale(1);
transform: scale(1);
}
.photostack nav span.current.flip {
-webkit-transform: scale(1) rotateY(-180deg) translateZ(-1px);
transform: scale(1) rotateY(-180deg) translateZ(-1px);
background: #555;
}
.photostack nav span.flippable::after {
opacity: 1;
-webkit-transition-delay: 0.4s;
transition-delay: 0.4s;
}
.js .photostack::before {
content: '';
position: absolute;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.5);
top: 0;
left: 0;
z-index: 100;
-webkit-transition: opacity 0.3s, visibility 0s 0.3s;
transition: opacity 0.3s, visibility 0s 0.3s;
}
.js .photostack-start::before {
-webkit-transition: opacity 0.3s;
transition: opacity 0.3s;
}
.js .photostack::after {
content: 'View Gallery';
font-weight: 400;
position: absolute;
border: 3px solid #fff;
text-align: center;
white-space: nowrap;
left: 50%;
top: 50%;
-webkit-transform: translateY(-50%) translateX(-50%);
transform: translateY(-50%) translateX(-50%);
padding: 10px 20px;
color: #fff;
text-transform: uppercase;
letter-spacing: 1px;
cursor: pointer;
z-index: 101;
}
.js .photostack::before,
.js .photostack::after {
opacity: 0;
visibility: hidden;
}
.js .photostack-start::before,
.js .photostack-start:hover::after,
.touch .photostack-start::after {
opacity: 1;
visibility: visible;
}
.photostack figure::after {
content: '';
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
visibility: visible;
opacity: 1;
background: rgba(0,0,0,0.05);
-webkit-transition: opacity 0.6s;
transition: opacity 0.6s;
}
figure.photostack-current::after {
-webkit-transition: opacity 0.6s, visibility 0s 0.6s;
transition: opacity 0.6s, visibility 0s 0.6s;
opacity: 0;
visibility: hidden;
}
.photostack-transition figure {
-webkit-transition: -webkit-transform 0.6s ease-in-out;
transition: transform 0.6s ease-in-out;
}
.photostack-perspective {
-webkit-perspective: 1800px;
perspective: 1800px;
}
.photostack-perspective > div,
.photostack-perspective figure {
-webkit-transform-style: preserve-3d;
transform-style: preserve-3d;
}
.photostack-perspective figure,
.photostack-perspective figure div {
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
}
.photostack-perspective figure.photostack-flip {
-webkit-transform-origin: 0% 50%;
transform-origin: 0% 50%;
}
.csstransformspreserve3d figure.photostack-flip .photostack-back {
-webkit-transform: rotateY(180deg);
transform: rotateY(180deg);
display: block;
}
.no-csstransformspreserve3d figure.photostack-showback .photostack-back {
display: block;
}
.no-js .photostack figure {
box-shadow: -2px 2px 0 rgba(0,0,0,0.05);
}
.no-js .photostack figure::after {
display: none;
}
.no-js .photostack figure:nth-child(3n) {
-webkit-transform: translateX(-10%) rotate(5deg);
transform: translateX(-10%) rotate(5deg);
}
.no-js .photostack figure:nth-child(3n-2) {
-webkit-transform: translateY(10%) rotate(-3deg);
transform: translateY(10%) rotate(-3deg);
}
#photostack-1 nav span.current {
background: #888;
-webkit-transform: scale(0.61);
transform: scale(0.61);
}
#leftArrowGallery {
margin-right: 10px;
}
#rightArrowGallery {
margin-left: 10px;
}
#rightArrowGallery i {
padding-left: 5px;
}
#leftArrowGallery i {
padding-right: 5px;
}
.btnGallery {
background-color: #da2c33;
border: medium none;
color: #FFFFFF;
cursor: pointer;
display: inline-block;
font: 12px;
padding: 3px 6px;
text-decoration: none;
white-space: nowrap;
border-radius: 5px;
}
.btnGallery:hover {
background-color: #b20a11;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.7.1/modernizr.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/classie/1.0.1/classie.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" media="all" type="text/css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="photostack-1" class="photostack photostack-start">
<div>
<figure>
<img src="https://tympanus.net/Development/ScatteredPolaroidsGallery/img/5.jpg" alt="img05"/>
<figcaption>
<h2 class="photostack-title">Speed Racer</h2>
</figcaption>
</figure>
<figure>
<img src="https://tympanus.net/Development/ScatteredPolaroidsGallery/img/2.jpg" alt="img02"/>
<figcaption>
<h2 class="photostack-title">Happy Days</h2>
</figcaption>
</figure>
<figure>
<img src="https://tympanus.net/Development/ScatteredPolaroidsGallery/img/3.jpg" alt="img03"/>
<figcaption>
<h2 class="photostack-title">Beautywood</h2>
</figcaption>
</figure>
<figure>
<img src="https://tympanus.net/Development/ScatteredPolaroidsGallery/img/1.jpg" alt="img01"/>
<figcaption>
<h2 class="photostack-title">Serenity Beach</h2>
</figcaption>
</figure>
<figure>
<img src="https://tympanus.net/Development/ScatteredPolaroidsGallery/img/4.jpg" alt="img04"/>
<figcaption>
<h2 class="photostack-title">Heaven of time</h2>
</figcaption>
</figure>
<figure>
<img src="https://tympanus.net/Development/ScatteredPolaroidsGallery/img/6.jpg" alt="img06"/>
<figcaption>
<h2 class="photostack-title">Forever this</h2>
</figcaption>
</figure>
<figure>
<img src="https://tympanus.net/Development/ScatteredPolaroidsGallery/img/7.jpg" alt="img07"/>
<figcaption>
<h2 class="photostack-title">Lovely Green</h2>
</figcaption>
</figure>
</div>
<div id="imageControls">
<button id="leftArrowGallery" class="btnGallery"><i class="fa fa-chevron-left"></i></button>
<button id="rightArrowGallery" class="btnGallery"><i class="fa fa-chevron-right"></i></button>
</div>
</section>

Full screen pop up window for multiple embedded videos

I'm new to js and I found a codepen that does exactly what I want to do except it currently only works for one embedded video.
What i am trying to achieve is the same but with 6 videos.
(function ($) {
'use strict';
$.fn.fitVids = function (options) {
var settings = {
customSelector: null,
ignore: null
};
if (!document.getElementById('fit-vids-style')) {
// appendStyles: https://github.com/toddmotto/fluidvids/blob/master/dist/fluidvids.js
var head = document.head || document.getElementsByTagName('head')[0];
var css = '.fluid-width-video-wrapper{width:100%;position:relative;padding:0;}.fluid-width-video-wrapper iframe,.fluid-width-video-wrapper object,.fluid-width-video-wrapper embed {position:absolute;top:0;left:0;width:100%;height:100%;}';
var div = document.createElement("div");
div.innerHTML = '<p>x</p><style id="fit-vids-style">' + css + '</style>';
head.appendChild(div.childNodes[1]);
}
if (options) {
$.extend(settings, options);
}
return this.each(function () {
var selectors = [
'iframe[src*="player.vimeo.com"]',
'iframe[src*="youtube.com"]',
'iframe[src*="youtube-nocookie.com"]',
'iframe[src*="kickstarter.com"][src*="video.html"]',
'object',
'embed'
];
if (settings.customSelector) {
selectors.push(settings.customSelector);
}
var ignoreList = '.fitvidsignore';
if (settings.ignore) {
ignoreList = ignoreList + ', ' + settings.ignore;
}
var $allVideos = $(this).find(selectors.join(','));
$allVideos = $allVideos.not('object object'); // SwfObj conflict patch
$allVideos = $allVideos.not(ignoreList); // Disable FitVids on this video.
$allVideos.each(function (count) {
var $this = $(this);
if ($this.parents(ignoreList).length > 0) {
return; // Disable FitVids on this video.
}
if (this.tagName.toLowerCase() === 'embed' && $this.parent('object').length || $this.parent('.fluid-width-video-wrapper').length) {
return;
}
if ((!$this.css('height') && !$this.css('width')) && (isNaN($this.attr('height')) || isNaN($this.attr('width')))) {
$this.attr('height', 9);
$this.attr('width', 16);
}
var height = (this.tagName.toLowerCase() === 'object' || ($this.attr('height') && !isNaN(parseInt($this.attr('height'), 10)))) ? parseInt($this.attr('height'), 10) : $this.height(),
width = !isNaN(parseInt($this.attr('width'), 10)) ? parseInt($this.attr('width'), 10) : $this.width(),
aspectRatio = height / width;
if (!$this.attr('id')) {
var videoID = 'fitvid' + count;
$this.attr('id', videoID);
}
$this.wrap('<div class="fluid-width-video-wrapper"></div>').parent('.fluid-width-video-wrapper').css('padding-top', (aspectRatio * 100) + '%');
$this.removeAttr('height').removeAttr('width');
});
});
};
// Works with either jQuery or Zepto
})(window.jQuery || window.Zepto);
// Init style shamelessly stolen from jQuery http://jquery.com
var Froogaloop = (function () {
// Define a local copy of Froogaloop
function Froogaloop(iframe) {
// The Froogaloop object is actually just the init constructor
return new Froogaloop.fn.init(iframe);
}
var eventCallbacks = {},
hasWindowEvent = false,
isReady = false,
slice = Array.prototype.slice,
playerDomain = '';
Froogaloop.fn = Froogaloop.prototype = {
element: null,
init: function (iframe) {
if (typeof iframe === "string") {
iframe = document.getElementById(iframe);
}
this.element = iframe;
// Register message event listeners
playerDomain = getDomainFromUrl(this.element.getAttribute('src'));
return this;
},
/*
* Calls a function to act upon the player.
*
* #param {string} method The name of the Javascript API method to call. Eg: 'play'.
* #param {Array|Function} valueOrCallback params Array of parameters to pass when calling an API method
* or callback function when the method returns a value.
*/
api: function (method, valueOrCallback) {
if (!this.element || !method) {
return false;
}
var self = this,
element = self.element,
target_id = element.id !== '' ? element.id : null,
params = !isFunction(valueOrCallback) ? valueOrCallback : null,
callback = isFunction(valueOrCallback) ? valueOrCallback : null;
// Store the callback for get functions
if (callback) {
storeCallback(method, callback, target_id);
}
postMessage(method, params, element);
return self;
},
/*
* Registers an event listener and a callback function that gets called when the event fires.
*
* #param eventName (String): Name of the event to listen for.
* #param callback (Function): Function that should be called when the event fires.
*/
addEvent: function (eventName, callback) {
if (!this.element) {
return false;
}
var self = this,
element = self.element,
target_id = element.id !== '' ? element.id : null;
storeCallback(eventName, callback, target_id);
// The ready event is not registered via postMessage. It fires regardless.
if (eventName != 'ready') {
postMessage('addEventListener', eventName, element);
} else if (eventName == 'ready' && isReady) {
callback.call(null, target_id);
}
return self;
},
/*
* Unregisters an event listener that gets called when the event fires.
*
* #param eventName (String): Name of the event to stop listening for.
*/
removeEvent: function (eventName) {
if (!this.element) {
return false;
}
var self = this,
element = self.element,
target_id = element.id !== '' ? element.id : null,
removed = removeCallback(eventName, target_id);
// The ready event is not registered
if (eventName != 'ready' && removed) {
postMessage('removeEventListener', eventName, element);
}
}
};
/**
* Handles posting a message to the parent window.
*
* #param method (String): name of the method to call inside the player. For api calls
* this is the name of the api method (api_play or api_pause) while for events this method
* is api_addEventListener.
* #param params (Object or Array): List of parameters to submit to the method. Can be either
* a single param or an array list of parameters.
* #param target (HTMLElement): Target iframe to post the message to.
*/
function postMessage(method, params, target) {
if (!target.contentWindow.postMessage) {
return false;
}
var url = target.getAttribute('src').split('?')[0],
data = JSON.stringify({
method: method,
value: params
});
if (url.substr(0, 2) === '//') {
url = window.location.protocol + url;
}
target.contentWindow.postMessage(data, url);
}
/**
* Event that fires whenever the window receives a message from its parent
* via window.postMessage.
*/
function onMessageReceived(event) {
var data, method;
try {
data = JSON.parse(event.data);
method = data.event || data.method;
} catch (e) {
//fail silently... like a ninja!
}
if (method == 'ready' && !isReady) {
isReady = true;
}
// Handles messages from moogaloop only
if (event.origin != playerDomain) {
return false;
}
var value = data.value,
eventData = data.data,
target_id = target_id === '' ? null : data.player_id,
callback = getCallback(method, target_id),
params = [];
if (!callback) {
return false;
}
if (value !== undefined) {
params.push(value);
}
if (eventData) {
params.push(eventData);
}
if (target_id) {
params.push(target_id);
}
return params.length > 0 ? callback.apply(null, params) : callback.call();
}
/**
* Stores submitted callbacks for each iframe being tracked and each
* event for that iframe.
*
* #param eventName (String): Name of the event. Eg. api_onPlay
* #param callback (Function): Function that should get executed when the
* event is fired.
* #param target_id (String) [Optional]: If handling more than one iframe then
* it stores the different callbacks for different iframes based on the iframe's
* id.
*/
function storeCallback(eventName, callback, target_id) {
if (target_id) {
if (!eventCallbacks[target_id]) {
eventCallbacks[target_id] = {};
}
eventCallbacks[target_id][eventName] = callback;
} else {
eventCallbacks[eventName] = callback;
}
}
/**
* Retrieves stored callbacks.
*/
function getCallback(eventName, target_id) {
if (target_id) {
return eventCallbacks[target_id][eventName];
} else {
return eventCallbacks[eventName];
}
}
function removeCallback(eventName, target_id) {
if (target_id && eventCallbacks[target_id]) {
if (!eventCallbacks[target_id][eventName]) {
return false;
}
eventCallbacks[target_id][eventName] = null;
} else {
if (!eventCallbacks[eventName]) {
return false;
}
eventCallbacks[eventName] = null;
}
return true;
}
/**
* Returns a domain's root domain.
* Eg. returns http://vimeo.com when http://vimeo.com/channels is sbumitted
*
* #param url (String): Url to test against.
* #return url (String): Root domain of submitted url
*/
function getDomainFromUrl(url) {
if (url.substr(0, 2) === '//') {
url = window.location.protocol + url;
}
var url_pieces = url.split('/'),
domain_str = '';
for (var i = 0, length = url_pieces.length; i < length; i++) {
if (i < 3) {
domain_str += url_pieces[i];
} else {
break;
}
if (i < 2) {
domain_str += '/';
}
}
return domain_str;
}
function isFunction(obj) {
return !!(obj && obj.constructor && obj.call && obj.apply);
}
function isArray(obj) {
return toString.call(obj) === '[object Array]';
}
// Give the init function the Froogaloop prototype for later instantiation
Froogaloop.fn.init.prototype = Froogaloop.fn;
// Listens for the message event.
// W3C
if (window.addEventListener) {
window.addEventListener('message', onMessageReceived, false);
}
// IE
else {
window.attachEvent('onmessage', onMessageReceived);
}
// Expose froogaloop to the global object
return (window.Froogaloop = window.$f = Froogaloop);
})();
////////////////////////////////////////
// Our Script
////////////////////////////////////////
$(document).ready(function () {
// Initiate FitVid.js
$(".containiframeCeleb2").fitVids();
$(".containiframeRiver2").fitVids();
$(".containiframeBach").fitVids();
$(".containiframeLouie").fitVids();
$(".containiframeRiver1").fitVids();
$(".containiframeCeleb1").fitVids();
$(".containiframe").fitVids();
// Iframe/player variables
var iframe = $('#videoCeleb1')[0];
var iframe = $('#videoRiver1')[0];
var iframe = $('#videoLouie')[0];
var iframe = $('#videoBach')[0];
var iframe = $('#videoRiver2')[0];
var iframe = $('#videoCeleb2')[0];
var iframe = $('#video')[0];
var player = $f(iframe);
// Open on play
$('.play').click(function () {
$('.content').css('left', 0)
$('.content').addClass('show')
player.api("play");
})
$('.playcelebrity1').click(function () {
$('.content').css('left', 0)
$('.content').addClass('show')
player.api("playcelebrity1");
})
$('.playcottage1').click(function () {
$('.content').css('left', 0)
$('.content').addClass('show')
player.api("playcottage1");
})
$('.playLouie').click(function () {
$('.content').css('left', 0)
$('.content').addClass('show')
player.api("playLouie");
})
$('.playbachelourette').click(function () {
$('.content').css('left', 0)
$('.content').addClass('show')
player.api("playbachelourette");
})
$('.playcottage2').click(function () {
$('.content').css('left', 0)
$('.content').addClass('show')
player.api("playcottage2");
})
$('.playcelbrity2').click(function () {
$('.content').css('left', 0)
$('.content').addClass('show')
player.api("playcelbrity2");
})
// Closes on click outside
$('.content').click(function () {
$('.content').removeClass('show')
setTimeout(function () {
$('.content').css('left', '-100%')
}, 300);
player.api("pause");
})
});
/* Lazy-man Reset */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* Fullscreen Section */
header {
width: 100%;
/* 100% height */
height: 100vh;
color: white;
background: #2980b9;
text-align: center;
padding: 20px;
/* Fancy flex-box centering */
display: flex;
align-items: center;
justify-content: center;
-webkit-display: flex;
-webkit-align-items: center;
-webkit-justify-content: center;
}
header h1 {
font-size: 40px;
font-family: 'Roboto';
font-weight: 700;
max-width: 700px;
margin-bottom: 10px;
}
header p {
font-family: 'Roboto Slab';
font-weight: 400;
font-size: 20px;
max-width: 700px;
margin-bottom: 20px;
opacity: .65;
}
.play {
background-image: url(https://img.youtube.com/vi/YDHFM2HmYe0/default.jpg);
display: block;
width: 120px;
height: 90px;
margin: 0 auto;
/* Important for :after */
position: relative;
}
.play:hover {
background: #333;
cursor: pointer;
}
.play:after {
position: absolute;
/* Centering */
/* CSS Triangle */
}
.playcelebrity1 {
background-image: url(https://img.youtube.com/vi/ebB0eoSY4yU/default.jpg);
display: block;
/* width: 500px;
height: 297px;*/
margin: 0 auto;
/* Important for :after */
position: relative;
}
.playcelebrity1:hover {
background: #333;
cursor: pointer;
}
.playcelebrity1:after {
position: absolute;
/* Centering */
/* CSS Triangle */
}
.playcottage1 {
background-image: url(https://img.youtube.com/vi/YDHFM2HmYe0/default.jpg);
display: block;
width: 120px;
height: 90px;
margin: 0 auto;
/* Important for :after */
position: relative;
}
.playcottage1:hover {
background: #333;
cursor: pointer;
}
.playcottage1:after {
position: absolute;
/* Centering */
/* CSS Triangle */
}
.playLouie {
background-image: url(https://img.youtube.com/vi/ol43MqHED9c/default.jpg);
display: block;
width: 120px;
height: 90px;
margin: 0 auto;
/* Important for :after */
position: relative;
}
.playLouie:hover {
background: #333;
cursor: pointer;
}
.playLouie:after {
position: absolute;
/* Centering */
/* CSS Triangle */
}
.playbachelourette {
background-image: url(https://img.youtube.com/vi/qXy5sCJj2wI/default.jpg);
display: block;
width: 120px;
height: 90px;
margin: 0 auto;
/* Important for :after */
position: relative;
}
.playbachelourette:hover {
background: #333;
cursor: pointer;
}
.playbachelourette:after {
position: absolute;
/* Centering */
/* CSS Triangle */
}
.playcottage2 {
background-image: url(https://img.youtube.com/vi/7OeoQqPqxBg/default.jpg);
display: block;
width: 120px;
height: 90px;
margin: 0 auto;
/* Important for :after */
position: relative;
}
.playcottage2:hover {
background: #333;
cursor: pointer;
}
.playcottage2:after {
position: absolute;
/* Centering */
/* CSS Triangle */
}
.playcelbrity2 {
background-image: url(https://img.youtube.com/vi/lk9tse44BMc/default.jpg);
display: block;
width: 120px;
height: 90px;
margin: 0 auto;
/* Important for :after */
position: relative;
}
.playcelbrity2:hover {
background: #333;
cursor: pointer;
}
.playcelbrity2:after {
position: absolute;
/* Centering */
/* CSS Triangle */
}
/* Fullscreen Overlay */
.content {
width: 100%;
height: 100vh;
/* 50% opacity black */
background: rgba(0, 0, 0, .5);
/* Stays locked on scroll */
position: fixed;
/* On top of the rest*/
z-index: 2;
/* Hidden */
opacity: 0;
/* No interference */
left: -100%;
/* CSS3 Transition */
transition: opacity .5s;
-webkit-transition: opacity .5s;
}
/* 90% width container */
.containiframeCeleb2 {
width: 90%;
/* Centering */
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
}
.containiframeRiver2 {
width: 90%;
/* Centering */
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
}
.containiframeLouie {
width: 90%;
/* Centering */
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
}
.containiframeCeleb1 {
width: 90%;
/* Centering */
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
}
.containiframe {
width: 90%;
/* Centering */
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
}
.close {
width: 20px;
fill: white;
position: absolute;
right: 0;
/* Bring above video */
top: -30px;
}
.close:hover {
/* 50% opacity white */
fill: rgba(255, 255, 255, 0.5);
cursor: pointer;
}
/* Class to fade in overlay */
.show {
opacity: 1;
}
<title>FullScreen Vimeo Popup with Autoplay and CSS3 Transitions</title>
<body>
<div class="content">
<!--End of the new-->
<div class="containiframeCeleb2">
<!-- SVG Close (X) Icon -->
<svg class="close" xmlns="http://www.w3.org/2000/svg" viewBox="39.2 22.3 25 24.5"><path d="M39.5,46.4c0.2,0.2,0.6,0.4,0.9,0.4c0.3,0,0.6-0.1,0.9-0.4l10.3-10.3L62,46.4c0.2,0.2,0.6,0.4,0.9,0.4c0.3,0,0.6-0.1,0.9-0.4c0.5-0.5,0.5-1.3,0-1.8L53.5,34.3l9.8-9.8c0.5-0.5,0.5-1.3,0-1.8c-0.5-0.5-1.3-0.5-1.8,0l-9.8,9.8l-9.8-9.8c-0.5-0.5-1.3-0.5-1.8,0c-0.5,0.5-0.5,1.3,0,1.8l9.8,9.8L39.5,44.6C39,45.1,39,45.9,39.5,46.4z"/></svg>
<!-- Embedded video -->
<iframe id="videoCeleb2" src="https://www.youtube.com/embed/lk9tse44BMc?ecver=1" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
</div>
<div class="containiframeRiver2">
<!-- SVG Close (X) Icon -->
<svg class="close" xmlns="http://www.w3.org/2000/svg" viewBox="39.2 22.3 25 24.5"><path d="M39.5,46.4c0.2,0.2,0.6,0.4,0.9,0.4c0.3,0,0.6-0.1,0.9-0.4l10.3-10.3L62,46.4c0.2,0.2,0.6,0.4,0.9,0.4c0.3,0,0.6-0.1,0.9-0.4c0.5-0.5,0.5-1.3,0-1.8L53.5,34.3l9.8-9.8c0.5-0.5,0.5-1.3,0-1.8c-0.5-0.5-1.3-0.5-1.8,0l-9.8,9.8l-9.8-9.8c-0.5-0.5-1.3-0.5-1.8,0c-0.5,0.5-0.5,1.3,0,1.8l9.8,9.8L39.5,44.6C39,45.1,39,45.9,39.5,46.4z"/></svg>
<!-- Embedded video -->
<iframe id="videoRiver2" src="https://www.youtube.com/embed/7OeoQqPqxBg?ecver=1" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
</div>
<div class="containiframeBach">
<!-- SVG Close (X) Icon -->
<svg class="close" xmlns="http://www.w3.org/2000/svg" viewBox="39.2 22.3 25 24.5"><path d="M39.5,46.4c0.2,0.2,0.6,0.4,0.9,0.4c0.3,0,0.6-0.1,0.9-0.4l10.3-10.3L62,46.4c0.2,0.2,0.6,0.4,0.9,0.4c0.3,0,0.6-0.1,0.9-0.4c0.5-0.5,0.5-1.3,0-1.8L53.5,34.3l9.8-9.8c0.5-0.5,0.5-1.3,0-1.8c-0.5-0.5-1.3-0.5-1.8,0l-9.8,9.8l-9.8-9.8c-0.5-0.5-1.3-0.5-1.8,0c-0.5,0.5-0.5,1.3,0,1.8l9.8,9.8L39.5,44.6C39,45.1,39,45.9,39.5,46.4z"/></svg>
<!-- Embedded video -->
<iframe id="videoBach" src="https://www.youtube.com/embed/qXy5sCJj2wI?ecver=1" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
</div>
<div class="containiframeLouie">
<!-- SVG Close (X) Icon -->
<svg class="close" xmlns="http://www.w3.org/2000/svg" viewBox="39.2 22.3 25 24.5"><path d="M39.5,46.4c0.2,0.2,0.6,0.4,0.9,0.4c0.3,0,0.6-0.1,0.9-0.4l10.3-10.3L62,46.4c0.2,0.2,0.6,0.4,0.9,0.4c0.3,0,0.6-0.1,0.9-0.4c0.5-0.5,0.5-1.3,0-1.8L53.5,34.3l9.8-9.8c0.5-0.5,0.5-1.3,0-1.8c-0.5-0.5-1.3-0.5-1.8,0l-9.8,9.8l-9.8-9.8c-0.5-0.5-1.3-0.5-1.8,0c-0.5,0.5-0.5,1.3,0,1.8l9.8,9.8L39.5,44.6C39,45.1,39,45.9,39.5,46.4z"/></svg>
<!-- Embedded video -->
<iframe id="videoLouie" src="https://www.youtube.com/embed/ol43MqHED9c?ecver=1" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
</div>
<div class="containiframeRiver1">
<!-- SVG Close (X) Icon -->
<svg class="close" xmlns="http://www.w3.org/2000/svg" viewBox="39.2 22.3 25 24.5"><path d="M39.5,46.4c0.2,0.2,0.6,0.4,0.9,0.4c0.3,0,0.6-0.1,0.9-0.4l10.3-10.3L62,46.4c0.2,0.2,0.6,0.4,0.9,0.4c0.3,0,0.6-0.1,0.9-0.4c0.5-0.5,0.5-1.3,0-1.8L53.5,34.3l9.8-9.8c0.5-0.5,0.5-1.3,0-1.8c-0.5-0.5-1.3-0.5-1.8,0l-9.8,9.8l-9.8-9.8c-0.5-0.5-1.3-0.5-1.8,0c-0.5,0.5-0.5,1.3,0,1.8l9.8,9.8L39.5,44.6C39,45.1,39,45.9,39.5,46.4z"/></svg>
<!-- Embedded video -->
<iframe id="videoRiver1" src="https://www.youtube.com/embed/YDHFM2HmYe0?ecver=1" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
</div>
<div class="containiframeCeleb1">
<!-- SVG Close (X) Icon -->
<svg class="close" xmlns="http://www.w3.org/2000/svg" viewBox="39.2 22.3 25 24.5"><path d="M39.5,46.4c0.2,0.2,0.6,0.4,0.9,0.4c0.3,0,0.6-0.1,0.9-0.4l10.3-10.3L62,46.4c0.2,0.2,0.6,0.4,0.9,0.4c0.3,0,0.6-0.1,0.9-0.4c0.5-0.5,0.5-1.3,0-1.8L53.5,34.3l9.8-9.8c0.5-0.5,0.5-1.3,0-1.8c-0.5-0.5-1.3-0.5-1.8,0l-9.8,9.8l-9.8-9.8c-0.5-0.5-1.3-0.5-1.8,0c-0.5,0.5-0.5,1.3,0,1.8l9.8,9.8L39.5,44.6C39,45.1,39,45.9,39.5,46.4z"/></svg>
<!-- Embedded video -->
<iframe id="videoCeleb1" src="https://www.youtube.com/embed/ebB0eoSY4yU?ecver=1" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
</div>
<div class="containiframe">
<!-- SVG Close (X) Icon -->
<svg class="close" xmlns="http://www.w3.org/2000/svg" viewBox="39.2 22.3 25 24.5"><path d="M39.5,46.4c0.2,0.2,0.6,0.4,0.9,0.4c0.3,0,0.6-0.1,0.9-0.4l10.3-10.3L62,46.4c0.2,0.2,0.6,0.4,0.9,0.4c0.3,0,0.6-0.1,0.9-0.4c0.5-0.5,0.5-1.3,0-1.8L53.5,34.3l9.8-9.8c0.5-0.5,0.5-1.3,0-1.8c-0.5-0.5-1.3-0.5-1.8,0l-9.8,9.8l-9.8-9.8c-0.5-0.5-1.3-0.5-1.8,0c-0.5,0.5-0.5,1.3,0,1.8l9.8,9.8L39.5,44.6C39,45.1,39,45.9,39.5,46.4z"/></svg>
<!-- Embedded video -->
<iframe id="video" src="https://www.youtube.com/embed/YDHFM2HmYe0?ecver=1" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
</div>
</div>
<header>
<div>
<span class="play"> </span>
</div>
<div>
<span class="playcelebrity1"> </span>
</div>
<div>
<span class="playcottage1"> </span>
</div>
<div>
<span class="playLouie"> </span>
</div>
<div>
<span class="playbachelourette"> </span>
</div>
<div>
<span class="playcottage2"> </span>
</div>
<div>
<span class="playcelbrity2"> </span>
</div>
</header>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
Here is my progress so far (jsfiddle)
I had a project which I should embed multi videos. this is how I done it :
I used Bootstrap modal :
<div id="videoModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<iframe id="videoIframe" class="full-width height-480"
src="https://www.youtube.com/watch?v=UM-ZPAF2Dpw" frameborder="0" allowfullscreen></iframe>
</div>
</div>
add this one only once, and in your button pass the youtube video ID like this :
<button onclick="showVideo('UM-ZPAF2Dpw')"><span class="glyphicon glyphicon-triangle-right"></span> Show Video 1</button>
you can have as many as button you like with different video ID
and in your script file you need to have this :
function showVideo(youtubeID){
var url = 'https://www.youtube.com/embed/' + youtubeID
document.getElementById('videoIframe').src = url;
// Get the modal
var modal = document.getElementById('videoModal');
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
modal.style.display = "block";
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
document.getElementById('videoIframe').src = '';
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
document.getElementById('videoIframe').src = '';
}
}
}

Categories