File: D:/HostingSpaces/SBogers10/helder.komma.pro/wwwroot/js/site/app.js
/* ==========================================================================
Input handler
This handler can be remove when the css support for :focus-within is better
========================================================================== */
var InputHandler = {
inputFields: null,
init: function init() {
// Get the form inputs
InputHandler.inputFields = document.querySelectorAll('form input, form textarea');
var inputLength = InputHandler.inputFields.length;
for (var i = 0; i < inputLength; i++) {
var input = InputHandler.inputFields[i];
var inputId = input.getAttribute('id'); // Check if there is an id on the input
if (isset(inputId)) {
var inputLabel = document.querySelector('form label[for="' + inputId + '"'); // // And if there is a belonging label
if (isset(inputLabel)) {
InputHandler.addEventListenersToInput(input);
}
}
}
},
addEventListenersToInput: function addEventListenersToInput(input) {
// Add the fill class and trigger removeFocus so the input will be automatic be marked as filled or not
parentElement = input.parentNode;
parentElement.classList.add('filled');
InputHandler.removeFocus(input);
input.addEventListener('focus', function () {
// We loop through the input elements because autocomplete (on chrome) triggers al the focus elements but none focus out
var inputLength = InputHandler.inputFields.length;
for (var i = 0; i < inputLength; i++) {
var loopedInput = InputHandler.inputFields[i]; // Trigger add focus on this focused element
if (loopedInput === input) {
InputHandler.addFocus(this);
} // Remove focus on all other input/textarea elements
else {
InputHandler.removeFocus(loopedInput);
}
}
});
input.addEventListener('focusout', function () {
InputHandler.removeFocus(this);
});
},
addFocus: function addFocus(input) {
if (isset(input)) {
var inputId = input.getAttribute('id');
parentElement = input.parentNode;
parentElement.classList.add('focused');
parentElement.classList.add('filled'); // If there is a error message remove it on focus
var errorMessage = document.querySelector('form .error-message#' + inputId + '-error');
if (isset(errorMessage)) {
errorMessage.classList.add('fade-out');
}
}
},
// Reset the label location only if the input is empty
removeFocus: function removeFocus(input) {
if (isset(input)) {
var inputValue = input.value;
parentElement = input.parentNode;
parentElement.classList.remove('focused');
if (!isset(inputValue) || inputValue === '') {
parentElement.classList.remove('filled');
}
}
}
};
InputHandler.init();
/* ==========================================================================
Accordion handler
- Handles the accordion component which has the proper classes.
========================================================================== */
var AccordionHandler = {
init: function init() {
var accordionList = document.querySelectorAll('.js-accordion');
var accordionListCount = accordionList.length;
if (isset(accordionList) && accordionListCount !== 0) {
for (var i = 0; i < accordionListCount; i++) {
var accordion = accordionList[i];
AccordionHandler.initAccordion(accordion);
}
}
},
initAccordion: function initAccordion(accordion) {
/*
* Set "pointer events: none" on all direct children of the toggle
* Because we don't want clicks on them to register, only on the parent toggle element
*/
var toggleList = accordion.querySelectorAll('.js-accordion-toggle');
for (var i = 0; i < toggleList.length; i++) {
var toggleItem = toggleList[i];
for (var j = 0; j < toggleItem.children.length; j++) {
var toggleChild = toggleItem.children[j];
toggleChild.style.pointerEvents = "none";
}
}
accordion.addEventListener('click', AccordionHandler.toggleAccordion, false);
},
toggleAccordion: function toggleAccordion(event) {
var item = event.target.parentNode;
var itemList = item.parentNode.children; // Bail if we didn't click on the toggle element
if (!event.target.classList.contains('js-accordion-toggle')) return; // Check if content element exists
if (!item.querySelector('.js-accordion-content')) return; // Prevent default link behavior
event.preventDefault(); // If the item is already active, collapse it and quit
if (item.classList.contains('is-active')) {
item.classList.remove('is-active');
return;
} // Loop through all open accordion items, and close them
for (var i = 0; i < itemList.length; i++) {
itemList[i].classList.remove('is-active');
} // Toggle our content by setting the active class
item.classList.toggle('is-active');
}
};
AccordionHandler.init();
/* ==========================================================================
Browser Handler
========================================================================== */
var BrowserHandler = {
userAgent: '',
browserInfo: '',
init: function init() {
BrowserHandler.userAgent = window.navigator.userAgent;
BrowserHandler.browserInfo = BrowserHandler.getBrowserInfo();
BrowserHandler.handleIE();
BrowserHandler.handleSafari();
},
handleIE: function handleIE() {
// Detect versions below ie11
var msie = BrowserHandler.userAgent.indexOf('MSIE ');
var ielt11 = msie > 0; // Detect ie11
var ie11 = !!navigator.userAgent.match(/Trident.*rv\:11\./); // If Internet Explorer
if (ielt11 || ie11) {
// Default version
var version = '11'; // Way to detect version < 11
if (ielt11) version = parseInt(BrowserHandler.userAgent.substring(msie + 5, BrowserHandler.userAgent.indexOf(".", msie))); // Append classes to HTML (we have to do this separately because else ie will fail)
document.body.classList.add('ie');
document.body.classList.add('v' + version);
}
},
// Fallback for older safari version
handleSafari: function handleSafari() {
if (BrowserHandler.browserInfo.name === 'Safari' && BrowserHandler.browserInfo.version <= 10) {
document.getElementsByTagName('html')[0].classList.add('ie');
}
},
getBrowserInfo: function getBrowserInfo() {
var ua = navigator.userAgent,
tem,
M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if (/trident/i.test(M[1])) {
tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
return {
name: 'IE ',
version: tem[1] || ''
};
}
if (M[1] === 'Chrome') {
tem = ua.match(/\bOPR\/(\d+)/);
if (tem != null) {
return {
name: 'Opera',
version: tem[1]
};
}
}
M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
if ((tem = ua.match(/version\/(\d+)/i)) != null) {
M.splice(1, 1, tem[1]);
}
return {
name: M[0],
version: M[1]
};
}
};
BrowserHandler.init();
/* ==========================================================================
Cookie handler
- Primary usage for toggling the cookie message and/or switch
========================================================================== */
var CookieHandler = {
cookieBar: null,
cookieOverlay: null,
cookieMessage: null,
cookieSwitch: null,
cookieFadeOutAnimationDuration: 400,
acceptTracking: false,
// Initialize cookie handler
init: function init() {
// Bind cookie bar or overlay to cookieMessage
CookieHandler.cookieMessage = document.querySelector('.js-cookie-bar, .js-cookie-overlay'); // Bind cookie bar to cookieBar
CookieHandler.cookieBar = document.querySelector('.js-cookie-bar'); // If isset init the functions for cookie bar
if (isset(CookieHandler.cookieBar)) {
CookieHandler.initCookieBar();
} else {
// Else try to connect cookie overlay with tracking to cookieOverlay
CookieHandler.cookieOverlay = document.querySelector('.js-cookie-overlay'); // If isset init the functions for cookie overlay
if (isset(CookieHandler.cookieOverlay)) {
CookieHandler.initCookieOverlay();
}
} // If either type of cookie has been found check if settings are defined
if (isset(CookieHandler.cookieMessage)) {
CookieHandler.checkForCookieSettings();
} // Bind cookie switch to Handler
CookieHandler.cookieSwitch = document.querySelector('.js-cookie-switch'); // If isset init the functions for cookie switch
if (isset(CookieHandler.cookieSwitch)) {
CookieHandler.initCookieSwitch();
}
},
// Init the cookie bar actions
initCookieBar: function initCookieBar() {
var closeButton = CookieHandler.cookieBar.querySelector('.js-disable-cookie-bar');
if (isset(closeButton)) {
closeButton.addEventListener('click', CookieHandler.closeCookieMessage);
}
},
// Init the cookie overlay actions
initCookieOverlay: function initCookieOverlay() {
// Open the cookie settings event
var openCookieSettingsButton = CookieHandler.cookieMessage.querySelector('.js-change-cookies-settings');
if (isset(openCookieSettingsButton)) {
openCookieSettingsButton.addEventListener('click', CookieHandler.openCookieSettings);
} // Toggle of the tracking input
var toggleTrackingInput = CookieHandler.cookieMessage.querySelector('.c-cookie-type__input--tracking');
if (isset(toggleTrackingInput)) {
if (toggleTrackingInput.checked === true) {
CookieHandler.acceptTracking = true;
}
toggleTrackingInput.addEventListener('change', CookieHandler.toggleTrackingSetting);
} // Accept / Save cookies button event
var acceptButton = CookieHandler.cookieMessage.querySelector('.js-accept-cookies');
if (isset(acceptButton)) {
acceptButton.addEventListener('click', CookieHandler.setCookieSettings);
}
},
// Init the cookie switch actions
initCookieSwitch: function initCookieSwitch() {
// Toggle of the tracking input
var toggleTrackingInput = CookieHandler.cookieSwitch.querySelector('.c-cookie-type__input--tracking');
if (isset(toggleTrackingInput)) {
// Force the state of the cookie switch input because the pop-up is forced on checked
// while the switch checks by php if the cookie really exist or not
if (toggleTrackingInput.checked === true) {
CookieHandler.acceptTracking = true;
} else {
CookieHandler.acceptTracking = false;
}
toggleTrackingInput.addEventListener('change', CookieHandler.toggleTrackingSetting);
} // Save cookies button event
var saveButton = CookieHandler.cookieSwitch.querySelector('.js-save-cookie-settings');
if (isset(saveButton)) {
saveButton.addEventListener('click', function () {
CookieHandler.cookieFadeOutAnimationDuration = 0; // On the switch click we want no delay :)
CookieHandler.setCookieSettings();
});
}
},
checkForCookieSettings: function checkForCookieSettings() {
if (Cookie.get('cookieMessage')) {
CookieHandler.cookieMessage.classList.add('is-accepted');
} else {
CookieHandler.cookieMessage.classList.remove('is-accepted');
}
},
closeCookieMessage: function closeCookieMessage() {
Cookie.set('cookieMessage', true, 90);
CookieHandler.cookieMessage.classList.add('fade-out');
},
openCookieSettings: function openCookieSettings() {
CookieHandler.cookieOverlay.querySelector('.js-cookie-settings').classList.remove('is-hidden');
CookieHandler.cookieOverlay.querySelector('.js-cookie-info').classList.add('is-hidden');
},
toggleTrackingSetting: function toggleTrackingSetting() {
if (CookieHandler.acceptTracking) {
CookieHandler.acceptTracking = false;
} else {
CookieHandler.acceptTracking = true;
}
},
setCookieSettings: function setCookieSettings() {
// Set tracking cookie or delete it if isset according to the desired settings
if (CookieHandler.acceptTracking) {
Cookie.set('trackingCookieAccepted', 'true', 90);
} else {
if (Cookie.get('trackingCookieAccepted')) {
Cookie.erase('trackingCookieAccepted');
}
}
CookieHandler.closeCookieMessage(); // Reload after animation to automatically trigger the tracking after accepting it
setTimeout(function () {
location.reload();
}, CookieHandler.cookieFadeOutAnimationDuration);
}
};
CookieHandler.init();
/* ==========================================================================
Navigation handler
========================================================================== */
/**
* Main navigation
*/
var Header = {
// Initialize click event
init: function init() {
// Bind clicks to burger button and overlay
$('.userMenu .bar').bind('click', function (ev) {
$(this).parent().toggleClass('open');
}); //$('#close-navigation').bind('click',nav.close)
}
};
Header.init();
/* ==========================================================================
Google Maps handler
- https://developers.google.com/maps/documentation/javascript/adding-a-google-map
========================================================================== */
var MapsHandler = {
map: '',
key: '',
location: {
lat: 51.2618222,
lng: 5.5965538
},
styling: '',
init: function init() {
// Get map by id
MapsHandler.map = document.getElementById('map'); // Check if a map is defined
if (isset(MapsHandler.map)) {
if (MapsHandler.map.hasAttribute('data-google-lat')) MapsHandler.location.lat = parseFloat(MapsHandler.map.getAttribute('data-google-lat'));
if (MapsHandler.map.hasAttribute('data-google-lng')) MapsHandler.location.lng = parseFloat(MapsHandler.map.getAttribute('data-google-lng'));
MapsHandler.setCustomStyling(); // See if google variable exists
if (typeof google == 'undefined' || typeof google.maps == 'undefined') {
// Load external script
getScript('https://maps.googleapis.com/maps/api/js?key=' + MapsHandler.key, MapsHandler.drawMap);
} else {
MapsHandler.drawMap();
}
}
},
drawMap: function drawMap() {
// Create a map
var map = new google.maps.Map(MapsHandler.map, {
zoom: 11,
center: MapsHandler.location,
disableDefaultUI: true,
styles: MapsHandler.styling
}); // Add a marker
var marker = new google.maps.Marker({
position: MapsHandler.location,
map: map
});
},
setCustomStyling: function setCustomStyling() {
MapsHandler.styling = [{
"featureType": "poi",
"elementType": "labels.text.fill",
"stylers": [{
"color": "#747474"
}, {
"lightness": "23"
}]
}, {
"featureType": "poi.attraction",
"elementType": "geometry.fill",
"stylers": [{
"color": "#f38eb0"
}]
}, {
"featureType": "poi.government",
"elementType": "geometry.fill",
"stylers": [{
"color": "#ced7db"
}]
}, {
"featureType": "poi.medical",
"elementType": "geometry.fill",
"stylers": [{
"color": "#ffa5a8"
}]
}, {
"featureType": "poi.park",
"elementType": "geometry.fill",
"stylers": [{
"color": "#c7e5c8"
}]
}, {
"featureType": "poi.place_of_worship",
"elementType": "geometry.fill",
"stylers": [{
"color": "#d6cbc7"
}]
}, {
"featureType": "poi.school",
"elementType": "geometry.fill",
"stylers": [{
"color": "#c4c9e8"
}]
}, {
"featureType": "poi.sports_complex",
"elementType": "geometry.fill",
"stylers": [{
"color": "#b1eaf1"
}]
}, {
"featureType": "road",
"elementType": "geometry",
"stylers": [{
"lightness": "100"
}]
}, {
"featureType": "road",
"elementType": "labels",
"stylers": [{
"visibility": "off"
}, {
"lightness": "100"
}]
}, {
"featureType": "road.highway",
"elementType": "geometry.fill",
"stylers": [{
"color": "#ffd4a5"
}]
}, {
"featureType": "road.arterial",
"elementType": "geometry.fill",
"stylers": [{
"color": "#ffe9d2"
}]
}, {
"featureType": "road.local",
"elementType": "all",
"stylers": [{
"visibility": "simplified"
}]
}, {
"featureType": "road.local",
"elementType": "geometry.fill",
"stylers": [{
"weight": "3.00"
}]
}, {
"featureType": "road.local",
"elementType": "geometry.stroke",
"stylers": [{
"weight": "0.30"
}]
}, {
"featureType": "road.local",
"elementType": "labels.text",
"stylers": [{
"visibility": "on"
}]
}, {
"featureType": "road.local",
"elementType": "labels.text.fill",
"stylers": [{
"color": "#747474"
}, {
"lightness": "36"
}]
}, {
"featureType": "road.local",
"elementType": "labels.text.stroke",
"stylers": [{
"color": "#e9e5dc"
}, {
"lightness": "30"
}]
}, {
"featureType": "transit.line",
"elementType": "geometry",
"stylers": [{
"visibility": "on"
}, {
"lightness": "100"
}]
}, {
"featureType": "water",
"elementType": "all",
"stylers": [{
"color": "#d2e7f7"
}]
}];
}
};
MapsHandler.init();
/* ==========================================================================
NavigationHandler handler
- Primary usage for mobile NavigationHandler
- Secondary if site used a pop-up/slide-in menu
========================================================================== */
var NavigationHandler = {
navElement: '',
scrolled: 0,
isActive: false,
// Initialize click event
init: function init() {
// Bind Navigation to Handler
NavigationHandler.navElement = document.getElementById('mobile-navigation'); // Bind clicks to menu button
var mobileMenuButton = document.getElementById('mobile-menu-trigger');
if (isset(mobileMenuButton)) {
mobileMenuButton.addEventListener('click', function () {
NavigationHandler.open();
});
} // Bind clicks to sticky menu button
var stickyMenuButton = document.getElementById('sticky-menu-trigger');
if (isset(stickyMenuButton)) {
stickyMenuButton.addEventListener('click', function () {
NavigationHandler.open();
});
}
var mobileShade = document.getElementById('mobile-shader');
if (isset(mobileShade)) {
mobileShade.addEventListener('click', function () {
NavigationHandler.close();
});
}
var mobileClose = document.getElementById('mobile-close');
if (isset(mobileClose)) {
mobileClose.addEventListener('click', function () {
NavigationHandler.close();
});
}
if (isset(NavigationHandler.navElement)) {
setTimeout(function () {
NavigationHandler.navElement.classList.add('allow-animation');
}, 500);
}
},
// Toggle navigation
toggle: function toggle() {
if (!NavigationHandler.isActive) NavigationHandler.open();else NavigationHandler.close();
},
// Open Navigation
open: function open() {
NavigationHandler.scrolled = window.pageYOffset;
NavigationHandler.navElement.classList.add('active');
NavigationHandler.navElement.classList.add('shader-active');
NavigationHandler.isActive = true;
setTimeout(function () {
document.body.classList.add('preventScroll');
}, 400);
},
// Close Navigation
close: function close() {
NavigationHandler.navElement.classList.remove('active');
NavigationHandler.navElement.classList.remove('shader-active');
NavigationHandler.isActive = false;
document.body.classList.remove('preventScroll');
window.scrollTo(0, NavigationHandler.scrolled);
}
};
NavigationHandler.init();
/* ==========================================================================
Navigation handler
========================================================================== */
/**
* Main navigation
*/
var Product = {
// Initialize click event
init: function init() {
$('body.products .order-box .increase').bind('click', function (ev) {
Product.updateProductValue(1);
ev.preventDefault();
return false;
});
$('body.products .order-box .decrease').bind('click', function (ev) {
Product.updateProductValue(-1);
ev.preventDefault();
return false;
});
},
updateProductValue: function updateProductValue(update) {
var el = $('body.products .order-box .amount');
var amount = parseInt(el.val());
if (amount + update > 0) {
amount += update;
el.val(amount);
}
}
};
Product.init();
/* ==========================================================================
Resize handler
- Handler the objects which are or need to be recalculated on resize
========================================================================== */
var ResizeHandler = {
time: Date.now(),
timeout: null,
waitThrottle: 1000,
waitDebounce: 500,
//Initialisation
init: function init() {
// Trigger start up resize
ResizeHandler.triggerOnInit(); // Throttle Resize
window.addEventListener('resize', function () {
if (ResizeHandler.time + ResizeHandler.waitThrottle - Date.now() < 0) {
ResizeHandler.triggerThrottle();
ResizeHandler.time = Date.now();
}
}); // Smooth Resize
window.addEventListener('resize', function () {
ResizeHandler.triggerSmooth();
}); // Debounce Resize
window.addEventListener('resize', function () {
if (isset(ResizeHandler.timeout)) clearTimeout(ResizeHandler.timeout);
ResizeHandler.timeout = setTimeout(ResizeHandler.triggerDebounce, ResizeHandler.waitDebounce);
});
},
// Trigger on start up
// All function should be in here
triggerOnInit: function triggerOnInit() {// ResizeHandler.resizeWhatDoesItCostAdvantageFigure();
// console.log('Initial Resize');
},
// Trigger resize functions with throttle (preferred)
triggerThrottle: function triggerThrottle() {// console.log('Throttled Resize');
},
// Trigger resize on debounce
triggerDebounce: function triggerDebounce() {// console.log('Debounce Resize');
// ResizeHandler.resizeWhatDoesItCostAdvantageFigure();
},
// Trigger resize on the flight
triggerSmooth: function triggerSmooth() {// console.log('Smooth Resize');
} // ------------------------------ CUSTOM SCROLL HANDLERS ------------------------------------
// Example function
// resizeWhatDoesItCostAdvantageFigure: function () {
// var el = document.querySelector('.advantages-own-guiding-row figure');
// if(isset(el)){
// el.style.maxHeight = 'none';
// el.style.maxHeight = el.offsetHeight + 'px';
// }
// },
};
ResizeHandler.init();
/* ==========================================================================
Scroll handler
- Handler the objects which are bind on scroll events or visible in viewport
========================================================================== */
var ScrollHandler = {
// Variables for debounce and throttle effects
time: Date.now(),
timeout: null,
waitThrottle: 1000,
waitDebounce: 300,
// Variables for scroll direction
lastScrollTopPosition: 0,
scrollDirectionDown: true,
scrollDirectionUp: false,
//Initialisation
init: function init() {
// Trigger start on start up
ScrollHandler.triggerOnInit(); // Throttle scroll
window.addEventListener('scroll', function () {
if (ScrollHandler.time + ScrollHandler.waitThrottle - Date.now() < 0) {
ScrollHandler.triggerThrottle();
ScrollHandler.time = Date.now();
}
}); // Smooth scroll
window.addEventListener('scroll', function () {
ScrollHandler.triggerSmooth();
}); // Debounce scroll
window.addEventListener('scroll', function () {
if (isset(ScrollHandler.timeout)) clearTimeout(ScrollHandler.timeout);
ScrollHandler.timeout = setTimeout(ScrollHandler.triggerDebounce, ScrollHandler.waitDebounce);
});
},
// Trigger on start up
triggerOnInit: function triggerOnInit() {
ScrollHandler.triggerElementInViewportAnimation();
},
// Trigger scroll functions with throttle (preferred)
triggerThrottle: function triggerThrottle() {
// console.log('Throttled scroll');
ScrollHandler.triggerElementInViewportAnimation();
},
// Trigger scroll on debounce
triggerDebounce: function triggerDebounce() {// console.log('Debounce scroll');
},
// Trigger scroll on the flight
triggerSmooth: function triggerSmooth() {
// console.log('Smooth scroll');
ScrollHandler.detectScrollDirection();
ScrollHandler.toggleStickyNavigation();
},
// Detect if part of a given element is visible in the viewport
// El must be a node element
detectIfElementIsPartlyInViewport: function detectIfElementIsPartlyInViewport(el) {
if (isset(el)) {
var rect = el.getBoundingClientRect(); // DOMRect { x: 8, y: 8, width: 100, height: 100, top: 8, right: 108, bottom: 108, left: 8 }
var windowHeight = window.innerHeight || document.documentElement.clientHeight;
var windowWidth = window.innerWidth || document.documentElement.clientWidth;
var verticalInView = rect.top <= windowHeight && rect.top + rect.height >= 0;
var horizontalInView = rect.left <= windowWidth && rect.left + rect.width >= 0;
return verticalInView && horizontalInView;
}
},
// Detect if a given element is fully visible in the viewport
// El must be a node element
detectIfElementIsFullyInViewport: function detectIfElementIsFullyInViewport(el) {
if (isset(el)) {
var rect = el.getBoundingClientRect();
return rect.top >= 0 && rect.bottom <= window.innerHeight;
}
},
detectScrollDirection: function detectScrollDirection() {
var scrollTopPosition = window.pageYOffset || document.documentElement.scrollTop; // Credits: "https://github.com/qeremy/so/blob/master/so.dom.js#L426"
if (scrollTopPosition >= ScrollHandler.lastScrollTopPosition) {
ScrollHandler.scrollDirectionDown = true;
ScrollHandler.scrollDirectionUp = false;
} else {
ScrollHandler.scrollDirectionDown = false;
ScrollHandler.scrollDirectionUp = true;
}
ScrollHandler.lastScrollTopPosition = scrollTopPosition;
},
// Trigger animation on elements that have 'element-in-viewport' and that are in the viewport
// These animation can only be triggered once, if you want more then that you should write an specific function for this
triggerElementInViewportAnimation: function triggerElementInViewportAnimation() {
var elements = document.querySelectorAll('.element-in-viewport');
var elementsLength = elements.length;
for (var e = 0; e < elementsLength; e++) {
var element = elements[e];
if (ScrollHandler.detectIfElementIsPartlyInViewport(element)) {
element.classList.remove('element-in-viewport');
}
}
},
// ------------------------------ CUSTOM SCROLL HANDLERS ------------------------------------
// Hide or show sticky navigation when header isn't visible
toggleStickyNavigation: function toggleStickyNavigation() {
var mainNavigation = document.querySelector('body >header');
var stickyNavigation = document.getElementById('sticky-navigation');
if (isset(stickyNavigation) && isset(mainNavigation)) {
// Show sticky navigation
if (!ScrollHandler.detectIfElementIsFullyInViewport(mainNavigation) && ScrollHandler.scrollDirectionUp) {
stickyNavigation.classList.add('active');
} // Hide sticky navigation
if (ScrollHandler.scrollDirectionDown || ScrollHandler.detectIfElementIsPartlyInViewport(mainNavigation)) {
stickyNavigation.classList.remove('active');
}
}
}
};
ScrollHandler.init();
/* ==========================================================================
Scroll To Click handler
========================================================================== */
var ScrollToHandler = {
// Animation settings
offset: 60,
//pixel
duration: 1400,
//ms
// Animation variables
body: null,
start: 0,
change: 0,
currentTime: 0,
allowAnimation: false,
scrollToAnimation: null,
// Watch the EasingFunction helper for the available methods
easing: 'easeInOutQuad',
init: function init() {
var anchorLinks = document.querySelectorAll('.scroll-to-target');
var anchorLinksAmount = anchorLinks.length;
for (var i = 0; i < anchorLinksAmount; i++) {
var anchorLink = anchorLinks[i];
anchorLink.addEventListener('click', function (event) {
ScrollToHandler.prepareScrollTo(this.getAttribute('href'));
event.preventDefault();
});
}
},
/**
* Prepare the Handler for the animation
*/
prepareScrollTo: function prepareScrollTo(elementId) {
// Get the scroll to element
elementId = elementId.substr(elementId.indexOf('#') + 1);
var scrollToElement = document.getElementById(elementId);
var scrollToElementPosition = scrollToElement.getBoundingClientRect(); // Reset or define the Handler variables
ScrollToHandler.body = document.documentElement;
ScrollToHandler.start = Math.max(ScrollToHandler.body.scrollTop, document.body.scrollTop, window.pageYOffset); //Use Math.max because safari doesn't support document.documentElement.scrollTop
ScrollToHandler.change = scrollToElementPosition.top + ScrollToHandler.start - ScrollToHandler.start - ScrollToHandler.offset;
ScrollToHandler.startTime = 'now' in window.performance ? performance.now() : new Date().getTime();
ScrollToHandler.allowAnimation = true; // Trigger animation
scrollToAnimation = requestAnimationFrame(ScrollToHandler.animateScroll); // Stop on scroll
window.addEventListener('mousedown', ScrollToHandler.abortScrollAnimation);
window.addEventListener('wheel', ScrollToHandler.abortScrollAnimation);
window.addEventListener('DOMMouseScroll', ScrollToHandler.abortScrollAnimation);
window.addEventListener('mousewheel', ScrollToHandler.abortScrollAnimation);
window.addEventListener('keyup', ScrollToHandler.abortScrollAnimation);
window.addEventListener('touchmove', ScrollToHandler.abortScrollAnimation);
},
/*
* Animate the scroll position
*/
animateScroll: function animateScroll(timestamp) {
// Calculate progress from 0 - 1
var progress = Math.min(1, (timestamp - ScrollToHandler.startTime) / ScrollToHandler.duration);
if (progress < 0) progress = 0; // Convert progress with easing function
progress = EasingFunctions[ScrollToHandler.easing](progress);
var newScrollTop = ScrollToHandler.start + ScrollToHandler.change * progress;
ScrollToHandler.body.scrollTop = newScrollTop;
if (ScrollToHandler.body.scrollTop === 0) document.body.scrollTop = newScrollTop; // Safari doesn't support so if ScrollToHandler.body.scrollTop is 0 force the scroll position through document.body.scrollTop
if (progress < 1 && ScrollToHandler.allowAnimation) {
scrollToAnimation = requestAnimationFrame(ScrollToHandler.animateScroll);
}
},
/*
* Abort the scroll animation
*/
abortScrollAnimation: function abortScrollAnimation(event) {
ScrollToHandler.allowAnimation = false;
cancelAnimationFrame(ScrollToHandler.scrollToAnimation);
}
};
ScrollToHandler.init();
var SearchHandler = {
form: document.getElementById('searchForm'),
searchBar: document.getElementById('searchbar'),
resultHolder: document.getElementById('searchresults'),
searchUrl: null,
init: function init() {
if (this.form && isset(this.form.dataset.searchUrl)) {
this.searchUrl = this.form.dataset.searchUrl;
var languageId = this.searchBar.dataset.languageId;
console.debug('searchHandler initialized with searchUrl: ' + this.searchUrl);
this.searchBar.addEventListener('keydown', debounce(function () {
SearchHandler.search(SearchHandler.searchBar.value, 1, 5, languageId);
}, 200));
}
},
search: function search(term) {
var page = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
var amount = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 10;
var language_id = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
if (term === "") return;
var xhr = new XMLHttpRequest();
var token = document.querySelector('meta[name="csrf-token"]').content;
var queryParams = {
'term': term,
'page': page,
'amount': amount,
'language_id': language_id
};
var queryUrlPart = '';
for (var param in queryParams) {
queryUrlPart += (queryUrlPart !== '' ? '&' : '?') + param + '=' + encodeURIComponent(queryParams[param]);
}
xhr.open('get', this.searchUrl + queryUrlPart, true);
xhr.responseType = 'json';
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.setRequestHeader('X-CSRF-TOKEN', token);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
SearchHandler.processSearchResponse(xhr.response);
} else {
console.error('SearchHandler: Could not search because of an error. ' + xhr.statusText);
}
}
};
xhr.send();
},
processSearchResponse: function processSearchResponse(response) {
if (!SearchHandler.validateSearchResponse(response)) return;
if (typeof response.data !== 'undefined' && response.data.length > 0) {
while (this.resultHolder.children.length > 0) {
this.resultHolder.removeChild(this.resultHolder.firstChild);
}
console.log(response.data);
length = response.data.length;
var items = [];
for (var index = 0; index < length; index++) {
console.log(response.data[index]);
var item = {
id: response.data[index].id,
type: response.data[index].type,
name: response.data[index].attributes.translation[0].attributes.name
};
items.push(item);
}
this.resultHolder.appendChild(document.createElement('ul'));
for (var _index = 0; _index < length; _index++) {
var element = document.createElement('li');
element.setAttribute('data-id', items[_index].id);
element.setAttribute('data-type', items[_index].type);
element.innerText = items[_index].name;
this.resultHolder.children[0].appendChild(element);
}
} else {
while (this.resultHolder.children.length > 0) {
this.resultHolder.removeChild(this.resultHolder.firstChild);
}
this.resultHolder.innerHTML = "<p>Geen zoekresultaten</p>";
}
},
validateSearchResponse: function validateSearchResponse(response) {
if (isset(response) && response.hasOwnProperty('data') && response.hasOwnProperty('meta')) return response;
console.error('Search response was not valid');
return false;
}
};
SearchHandler.init();
/* ==========================================================================
Share buttons handler
========================================================================== */
var ShareButtonsHandler = {
shareButtonsElement: null,
shareMessageElement: null,
shareMessage: null,
init: function init() {
// Get the youtube players containers
ShareButtonsHandler.shareButtonsElement = document.getElementById('js-shareButtons');
ShareButtonsHandler.shareMessageElement = document.getElementById('js-shareButtonData');
if (isset(ShareButtonsHandler.shareButtonsElement) && isset(ShareButtonsHandler.shareMessageElement)) {
ShareButtonsHandler.convertShareMessageToObject();
var items = ShareButtonsHandler.shareButtonsElement.querySelectorAll('.js-social-media-item');
var buttons = ShareButtonsHandler.shareButtonsElement.querySelectorAll('.js-social-media-button');
var buttonsLength = buttons.length;
var _loop = function _loop(i) {
var button = buttons[i];
var item = items[i];
button.addEventListener('click', function () {
var social = item.getAttribute('data-social');
var functionName = 'click' + capitalizeFirstLetter(social) + 'Button';
if (typeof ShareButtonsHandler[functionName] === 'function') {
ShareButtonsHandler[functionName]();
} else {
console.log('Method not build yet: ' + functionName);
}
});
};
for (var i = 0; i < buttonsLength; i++) {
_loop(i);
}
}
},
convertShareMessageToObject: function convertShareMessageToObject() {
var messageObject = {};
for (var i = 0, attributes = ShareButtonsHandler.shareMessageElement.attributes, attributesLength = attributes.length; i < attributesLength; i++) {
var attribute = attributes[i];
var attributeName = attribute.name;
attributeName = attributeName.replace(/data-/g, '');
attributeName = snakeToCamel(attributeName);
messageObject[attributeName] = attribute.value;
}
ShareButtonsHandler.shareMessage = messageObject;
},
clickFacebookButton: function clickFacebookButton() {
FB.ui({
method: 'share',
mobile_iframe: true,
href: ShareButtonsHandler.shareMessage.url
}, function (response) {});
},
clickTwitterButton: function clickTwitterButton() {
window.open('https://twitter.com/intent/tweet?text=' + ShareButtonsHandler.shareMessage.encodeName + '&url=' + ShareButtonsHandler.shareMessage.encodeUrl, 'newwindow', 'width=500, height=600');
},
clickLinkedinButton: function clickLinkedinButton() {
window.open('https://www.linkedin.com/shareArticle?mini=true&url=' + ShareButtonsHandler.shareMessage.encodeUrl + '&title=' + ShareButtonsHandler.shareMessage.encodeName + '&summary=' + ShareButtonsHandler.shareMessage.encodeSummary, 'newwindow', 'width=500, height=600');
},
clickMailButton: function clickMailButton() {
window.open('mailto:?subject=' + ShareButtonsHandler.shareMessage.name + '&body=' + ShareButtonsHandler.shareMessage.url, '_self');
},
clickLinkButton: function clickLinkButton() {
ShareButtonsHandler.shareMessageElement.select();
document.execCommand("copy");
var flashMessage = ShareButtonsHandler.shareButtonsElement.querySelector('.js-link-copied-message');
flashMessage.classList.add('clicked');
setTimeout(function () {
flashMessage.classList.remove('clicked');
}, 2000);
}
};
ShareButtonsHandler.init();
/* ==========================================================================
Navigation handler
========================================================================== */
/**
* Main navigation
*/
var SideMenu = {
// Initialize click event
init: function init() {
// Bind clicks to burger button and overlay
$('.category-menu>ul>li>a').bind('click', function () {
var id = $(this).parent().data("id");
$(this).parent().addClass('active');
$(".category-menu ul[data-parent-id=" + id + "]").addClass('open');
$(".category-menu ul.open li.subcategory-header span, .category-menu ul.open .bg").bind('click', function () {
$(".category-menu ul.open").removeClass('open').prev().removeClass('active');
});
return false; //$(this).child('ul').show();
});
$(".category-menu ul.open li.subcategory-header span, .category-menu ul.open .bg").bind('click', function () {
$(".category-menu ul.open").removeClass('open').prev().removeClass('active');
}); //$('#close-navigation').bind('click',nav.close)
}
};
SideMenu.init();
/**
* Created by Pascal on 06/12/17.
*/
/* Example
const headerImageSliderSetting = new SliderSetting({
sliderId: 'header-image-slider',
slideQuery: '#header-image-slider .placeholder figure',
dots: '#header-image-slider .slider-navigation-labels .navigation span',
captions: '#header-image-slider .slider-navigation-labels .caption p',
autoSlider: true,
sliderInterval: 4000
});
headerImageSliderSetting = headerImageSliderSetting.prepareParameters();
const headerImageSlider = new Slider(headerImageSliderSetting).init();
*/
var imageSliders = [];
var imageSliderContainers = document.querySelectorAll('.image-slider');
var imageSliderContainersLength = imageSliderContainers.length;
for (var i = 0; i < imageSliderContainersLength; i++) {
var imageSlider = imageSliderContainers[i];
var imageSliderId = imageSlider.getAttribute('id');
if (imageSliderId !== null) {
var imageSliderSetting = new SliderSetting({
sliderId: imageSliderId,
slideQuery: '#' + imageSliderId + ' .placeholder figure',
navigationButtons: '#' + imageSliderId + ' .placeholder .controllers .nav-item',
autoSlider: true,
sliderInterval: 4000
});
imageSliders.push(new Slider(imageSliderSetting.prepareParameters()).init());
} else console.log('An image slider has no id...');
}
function SliderSetting(settingsObject) {
var self = this;
this.sliderId = '';
this.definedPreviousNext = true;
this.autoSlider = false;
this.sliderInterval = 4000;
this.navigationButtons = '';
this.dots = '';
this.captions = '';
this.slideQuery = '';
this.setSliderId = function (string) {
this.sliderId = string;
return this;
};
this.setDefinedPreviousNext = function (boolean) {
this.definedPreviousNext = boolean;
return this;
};
this.setAutoSlider = function (boolean) {
this.autoSlider = boolean;
return this;
};
this.setSliderInterval = function (integer) {
this.sliderInterval = integer;
return this;
};
this.setSlideQuery = function (string) {
this.slideQuery = string;
return this;
};
this.setNavigationButtons = function (string) {
this.navigationButtons = string;
return this;
};
this.setDots = function (string) {
this.dots = string;
return this;
};
this.setCaptions = function (string) {
this.captions = string;
return this;
};
this.getSliderId = function () {
return this.sliderId;
};
this.getDefinedPreviousNext = function () {
return this.definedPreviousNext;
};
this.getAutoSlider = function () {
return this.autoSlider;
};
this.getSliderInterval = function () {
return this.sliderInterval;
};
this.getSlideQuery = function () {
return this.slideQuery;
};
this.getNavigationButtons = function () {
return this.navigationButtons;
};
this.getDots = function () {
return this.dots;
};
this.getCaptions = function () {
return this.captions;
}; // Invert setters to getters
this.prepareParameters = function () {
return {
sliderId: self.getSliderId(),
definedPreviousNext: self.getDefinedPreviousNext(),
autoSlider: self.getAutoSlider(),
sliderInterval: self.getSliderInterval(),
navigationButtons: self.getNavigationButtons(),
dots: self.getDots(),
captions: self.getCaptions(),
slideQuery: self.getSlideQuery()
};
}; // Mass assign settings
this.fill = function () {
// Object.keys(settingsObject).forEach(function (key) {
// self[key] = settingsObject[key];
// });
var settingsObjectKeys = Object.keys(settingsObject);
var settingsObjectLength = settingsObjectKeys.length;
for (var _i = 0; _i < settingsObjectLength; _i++) {
var key = settingsObjectKeys[_i];
self[key] = settingsObject[key];
}
};
this.fill();
return {
sliderId: self.setSliderId,
definedPreviousNext: self.setDefinedPreviousNext,
autoSlider: self.setAutoSlider,
sliderInterval: self.setSliderInterval,
navigationButtons: self.setNavigationButtons,
dots: self.setDots,
captions: self.setCaptions,
slideQuery: self.setSlideQuery,
prepareParameters: self.prepareParameters
};
}
function Slider(settings) {
//Define Slider object
var self = this;
this.sliderObject = ''; //SlideParameters
this.activeSlideId = 0;
this.previousSlideId = 0;
this.nextSlideId = 0;
this.availableSlides = 1;
this.slides = [];
this.autoSliderInterval = null;
this.settings = {};
this.init = function () {
//Append settings to self
this.settings = settings; //Assign needed elements and calculations
this.sliderObject = document.getElementById(this.settings.sliderId);
this.slides = document.querySelectorAll(this.settings.slideQuery);
this.availableSlides = this.slides.length;
this.activeSlideId = 0; //Define previous and next if we want to use those
if (self.settings.definedPreviousNext) this.setPreviousAndNextSlide(); // Set active slide (and possible previous and next classes)
this.setSlide(); // Swipe interaction
var swipeGestures = new Hammer(this.sliderObject);
swipeGestures.on('swipeleft', function () {
self.resetAutoSlider();
self.nextSlide();
self.setSlide();
});
swipeGestures.on('swiperight', function () {
self.resetAutoSlider();
self.previousSlide();
self.setSlide();
});
if (this.settings.navigationButtons !== '') {
// Click interaction
var navigationButtons = document.querySelectorAll(this.settings.navigationButtons);
var navigationButtonsLength = navigationButtons.length;
for (var _i2 = 0; _i2 < navigationButtonsLength; _i2++) {
var navigationButton = navigationButtons[_i2];
navigationButton.addEventListener('click', function () {
self.clickNavigationButton(this);
});
}
}
if (this.settings.dots !== '') {
// Click interaction
var dots = document.querySelectorAll(this.settings.dots);
var dotsLength = dots.length; // console.log(this.settings.dots);
// console.log(dots);
for (var _i3 = 0; _i3 < dotsLength; _i3++) {
var dot = dots[_i3]; // console.log('hier');
dot.addEventListener('click', function () {
self.clickDot(this);
});
}
}
self.autoSlider();
};
this.autoSlider = function () {
if (this.autoSliderInterval !== null) clearInterval(this.autoSliderInterval);
if (this.settings.autoSlider && Number.isInteger(this.settings.sliderInterval)) {
this.autoSliderInterval = setInterval(function () {
self.nextSlide();
self.setSlide();
}, this.settings.sliderInterval);
}
};
this.resetAutoSlider = self.autoSlider;
this.nextSlide = function () {
this.activeSlideId++;
if (this.activeSlideId >= this.availableSlides) this.activeSlideId = 0;
if (self.settings.definedPreviousNext) this.setPreviousAndNextSlide();
};
this.previousSlide = function () {
this.activeSlideId--;
if (this.activeSlideId < 0) this.activeSlideId = this.availableSlides - 1;
if (self.settings.definedPreviousNext) this.setPreviousAndNextSlide();
};
this.setPreviousAndNextSlide = function () {
this.nextSlideId = this.activeSlideId + 1;
if (this.nextSlideId >= this.availableSlides) this.nextSlideId = 0;
this.previousSlideId = this.activeSlideId - 1;
if (this.previousSlideId < 0) this.previousSlideId = this.availableSlides - 1;
};
this.setSlide = function () {
// Loop through the form elements
var slidesLength = self.slides.length;
for (var _i4 = 0; _i4 < slidesLength; _i4++) {
var slide = self.slides[_i4]; // Convert data set attribute to desired type
var slideOrder = parseInt(slide.getAttribute('data-order')); // Remove and set active for all slides
if (slideOrder !== self.activeSlideId) slide.classList.remove('active');else slide.classList.add('active'); // If we use the previous and next, also set those classes
if (self.settings.definedPreviousNext) {
if (slideOrder !== self.previousSlideId) slide.classList.remove('previous');else slide.classList.add('previous');
if (slideOrder !== self.nextSlideId) slide.classList.remove('next');else slide.classList.add('next');
}
}
if (self.settings.dots !== '') {
self.setActiveDot();
}
if (self.settings.captions !== '') {
self.setActiveCaption();
}
};
this.clickNavigationButton = function (navButton) {
self.activeSlideId = parseInt(navButton.getAttribute('data-order'));
if (self.settings.definedPreviousNext) self.setPreviousAndNextSlide();
self.setSlide();
var next = document.querySelector(self.settings.navigationButtons + '.next');
var previous = document.querySelector(self.settings.navigationButtons + '.previous');
next.setAttribute('data-order', self.nextSlideId);
previous.setAttribute('data-order', self.previousSlideId);
self.resetAutoSlider(); // next.querySelector('p').innerHTML = self.slides[self.nextSlideId].dataset.name;
// previous.querySelector('p').innerHTML = self.slides[self.previousSlideId].dataset.name;
};
this.clickDot = function (clickedDot) {
self.activeSlideId = parseInt(clickedDot.getAttribute('data-order'));
self.setSlide();
self.resetAutoSlider();
};
this.setActiveDot = function () {
var dots = document.querySelectorAll(this.settings.dots);
var dotsLength = dots.length;
for (var _i5 = 0; _i5 < dotsLength; _i5++) {
var dot = dots[_i5];
dotOrder = parseInt(dot.getAttribute('data-order'));
if (dotOrder !== self.activeSlideId) dot.classList.remove('active');else dot.classList.add('active');
}
};
this.setActiveCaption = function () {
var captions = document.querySelectorAll(this.settings.captions);
var captionsLength = captions.length;
for (var _i6 = 0; _i6 < captionsLength; _i6++) {
var caption = captions[_i6];
captionOrder = parseInt(caption.getAttribute('data-order'));
if (captionOrder !== self.activeSlideId) caption.classList.remove('active');else caption.classList.add('active');
}
};
}
/* ==========================================================================
Snippet handler
========================================================================== */
/**
* The Snippet handler used to hide and show snippets of code
* todo: rewrite without jquery
*/
var Snippet = {
init: function init() {
// Bind clicks to burger button and overlay
$('.c-snippet__navigation-item').bind('click', function () {
var scope = $(this).parent().parent().parent();
var isActive = $(this).hasClass('is-active');
$(scope).find('.c-snippet__navigation-item.is-active').removeClass('is-active');
$(scope).find('.c-snippet__code.is-active').removeClass('is-active');
if (!isActive) {
$(this).addClass('is-active');
var target = $(this).data('target');
$(scope).find('.' + target).addClass('is-active');
}
});
}
};
Snippet.init();
var imageSwipers = document.querySelectorAll('.swiper-container');
var imageSwipersLength = imageSwipers.length;
for (var _i7 = 0; _i7 < imageSwipersLength; _i7++) {
var imageSwiper = imageSwipers[_i7];
var imageSwiperId = imageSwiper.getAttribute('id');
if (imageSwiperId !== null) {
var swiper = new Swiper({
el: '#' + imageSwiperId,
initialSlide: 1,
spaceBetween: 50,
slidesPerView: 1,
centeredSlides: true,
slideToClickedSlide: true,
grabCursor: true,
scrollbar: {
el: '#' + imageSwiperId + ' .swiper-scrollbar'
},
mousewheel: {
enabled: true
},
keyboard: {
enabled: true
},
pagination: {
el: '#' + imageSwiperId + ' .swiper-pagination'
},
navigation: {
nextEl: '#' + imageSwiperId + ' .swiper-button-next',
prevEl: '#' + imageSwiperId + ' .swiper-button-prev'
}
});
} else console.log('An image swiper has no id...');
}
/* ==========================================================================
Tabslider handler
- Handles the tabslider component which has the proper classes.
========================================================================== */
var TabsliderHandler = {
init: function init() {
var tabsliderList = document.querySelectorAll('.js-tabslider');
var tabsliderListCount = tabsliderList.length;
if (isset(tabsliderList) && tabsliderListCount !== 0) {
for (var _i8 = 0; _i8 < tabsliderListCount; _i8++) {
var tabslider = tabsliderList[_i8];
TabsliderHandler.initTabslider(tabslider);
}
}
},
initTabslider: function initTabslider(tabslider) {
tabslider.addEventListener('click', TabsliderHandler.toggleTabslider, false);
},
toggleTabslider: function toggleTabslider(event) {
var tabslider = this;
var tabsliderContainer = tabslider.querySelector('.js-tabslider-container');
var tabsliderTriggers = tabslider.querySelectorAll(".js-tabslider-trigger");
var tabsliderTabs = tabsliderContainer.querySelectorAll(".js-tabslider-content");
var tabsliderTabId = event.target.dataset.tabId; // Bail if we didn't click on the trigger element
if (!event.target.classList.contains('js-tabslider-trigger')) return; // Bail if already active
if (event.target.classList.contains('is-active')) {
return;
} // Check if content element exists
if (!tabsliderContainer) return;
if (isset(tabsliderTabs) && tabsliderTabs.length !== 0) {
// Loop through all tabs
for (var _i9 = 0; _i9 < tabsliderTabs.length; _i9++) {
var tabsliderTab = tabsliderTabs[_i9];
tabsliderTriggers[_i9].classList.remove('is-active');
tabsliderTab.classList.remove('is-active');
if (tabsliderTab.dataset.tabId == tabsliderTabId) {
tabsliderTab.classList.toggle('is-active');
event.target.classList.toggle('is-active');
}
;
}
}
}
};
TabsliderHandler.init();
/* ==========================================================================
Youtube handler
========================================================================== */
var YoutubeHandler = {
youtubeClass: '.js-youtube-player',
players: [],
init: function init() {
// Get the youtube players containers
var youtubePlayers = document.querySelectorAll(YoutubeHandler.youtubeClass);
var youtubePlayersAmount = youtubePlayers.length;
for (var _i10 = 0; _i10 < youtubePlayersAmount; _i10++) {
var youtubePlayer = youtubePlayers[_i10];
var youtubePlayerId = youtubePlayer.getAttribute('id');
if (youtubePlayerId !== null) {
// Strip the necessary data from the html and create objects from it
var youtubeElement = {
id: youtubePlayer.getAttribute('id'),
link: youtubePlayer.getAttribute('data-youtube-link'),
autoPlay: parseInt(youtubePlayer.getAttribute('data-auto-play'))
};
YoutubeHandler.players.push(youtubeElement);
} else {
console.log("Element not include because there isn't a id on the player");
console.log(youtubePlayer);
}
}
if (youtubePlayersAmount >= 1) YoutubeHandler.initYoutube();
},
/**
* Check if external script is loaded
*
*/
initYoutube: function initYoutube() {
// See if YT variable exists
if (typeof YT == 'undefined' || typeof YT.Player == 'undefined') {
// Setup API ready function
window.onYouTubePlayerAPIReady = function () {
YoutubeHandler.loadPlayers();
}; // Load external script
getScript('https://www.youtube.com/iframe_api'); // If YT already exists load player
} else {
YoutubeHandler.loadPlayers();
}
},
/**
* Create the Youtube player(s) with parameters
* And rewrite the players to key them by the element id
*
*/
loadPlayers: function loadPlayers() {
var players = [];
var youtubePlayersAmount = YoutubeHandler.players.length;
for (var _i11 = 0; _i11 < youtubePlayersAmount; _i11++) {
var youtubePlayer = YoutubeHandler.players[_i11]; // Load player
youtubePlayer.player = new YT.Player(youtubePlayer.id, {
height: 200,
width: 200,
videoId: youtubePlayer.link,
host: 'https://www.youtube-nocookie.com',
playerVars: {
modestbranding: 0,
rel: 0,
disablekb: 1,
autoplay: youtubePlayer.autoPlay
},
events: {
// 'onReady': YoutubeHandler.onReady,
'onStateChange': YoutubeHandler.onStateChange
}
});
players[youtubePlayer.id] = youtubePlayer;
}
YoutubeHandler.players = players;
},
/**
* When player is ready to play
*/
onReady: function onReady(event) {
var playerContainerId = event.target.getIframe().getAttribute('id');
var player = YoutubeHandler.players[playerContainerId].player; // Show video
// setTimeout(function(){ $('#' + playerContainerId).stop().animate({ opacity: 1 },1000) },800);
// If not on tablet or mobile, play on high quality
// player.mute();
// player.playVideo();
// player.setPlaybackQuality('hd1080');
},
/**
* Listener for Youtube state change
*/
onStateChange: function onStateChange(event) {
var playerContainerId = event.target.getIframe().getAttribute('id');
var player = YoutubeHandler.players[playerContainerId].player;
var videoState = event.data; // Loop video
if (event.data === YT.PlayerState.ENDED) {
player.playVideo();
}
}
};
YoutubeHandler.init();