File: D:/HostingSpaces/SBogers10/spire-checkout.komma-mediadesign.nl/wwwroot/js/site/app.js
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
/* ==========================================================================
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
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.body.classList.add('ie');
}
},
getBrowserInfo: function getBrowserInfo() {
var ua = navigator.userAgent,
tem = void 0,
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();
/* ==========================================================================
Checkout Handler
========================================================================== */
var CheckoutHandler = {
checkoutForm: null,
otherShippingAddress: false,
shoppingCartCurrency: null,
shippingCountryElement: null,
shoppingCartTotalElement: null,
shippingCountryIso: null,
preLoadedShippingCost: null,
preLoadedTotal: null,
stateNotRequiredCountries: ['Al', 'AD', 'AM', 'AT', 'AZ', 'BY', 'BE', 'BA', 'BG', 'HR', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR', 'GE', 'DE', 'GR', 'HU', 'IS', 'IE', 'IT', 'KZ', 'LV', 'LI', 'LT', 'LU', 'MK', 'MT', 'MD', 'MC', 'ME', 'NL', 'NO', 'PL', 'PT', 'RO', 'RU', 'SM', 'RS', 'SK', 'SI', 'ES', 'SE', 'CH', 'TR', 'UA', 'UK', 'VA'],
init: function init() {
CheckoutHandler.checkoutForm = document.getElementById('checkoutForm');
CheckoutHandler.preLoadedShippingCost = document.querySelector('.shopping-cart-summary .pricing .shipping-cost');
CheckoutHandler.preLoadedTotal = document.querySelector('.shopping-cart-summary .pricing .total');
if (isset(CheckoutHandler.checkoutForm)) {
// Create the select for the salutation
new Selectr(CheckoutHandler.checkoutForm.querySelector('select#salutation'), {
defaultSelected: true,
searchable: false
});
// Create the select for the invoice country
var countrySelectElement = CheckoutHandler.checkoutForm.querySelector('select#country');
var countrySelector = new Selectr(countrySelectElement, {
placeholder: countrySelectElement.getAttribute('data-placeholder'),
defaultSelected: false
});
countrySelector.on('selectr.select', function (selectedOption) {
CheckoutHandler.setShippingCountry(selectedOption, false);
// If state is required show the field
if (inArray(CheckoutHandler.stateNotRequiredCountries, selectedOption.value)) {
CheckoutHandler.checkoutForm.querySelector('#invoice-state').classList.add('hidden');
} else {
CheckoutHandler.checkoutForm.querySelector('#invoice-state').classList.remove('hidden');
}
});
// Create the select for the shipping country
var shippingCountrySelectElement = CheckoutHandler.checkoutForm.querySelector('select#shippingCountry');
var shippingCountrySelector = new Selectr(shippingCountrySelectElement, {
placeholder: shippingCountrySelectElement.getAttribute('data-placeholder'),
defaultSelected: false
});
shippingCountrySelector.on('selectr.select', function (selectedOption) {
CheckoutHandler.setShippingCountry(selectedOption, true);
// If state is required show the field
if (inArray(CheckoutHandler.stateNotRequiredCountries, selectedOption.value)) {
CheckoutHandler.checkoutForm.querySelector('#shipping-state').classList.add('hidden');
} else {
CheckoutHandler.checkoutForm.querySelector('#shipping-state').classList.remove('hidden');
}
});
// Get the checkout summary variables
CheckoutHandler.shippingCountryElement = CheckoutHandler.checkoutForm.querySelector('.checkout-shopping-cart-summary .shipping-cost');
CheckoutHandler.shoppingCartTotalElement = CheckoutHandler.checkoutForm.querySelector('.checkout-shopping-cart-summary .total');
// Submit button
CheckoutHandler.checkoutForm.querySelector('.submit p').addEventListener('click', function () {
CheckoutHandler.checkoutForm.submit();
});
// Shipping Address area checkbox
var shippingAddressCheckbox = CheckoutHandler.checkoutForm.querySelector('#otherShippingAddress');
shippingAddressCheckbox.addEventListener('change', function () {
var shippingAddressAreaFieldsWrapper = CheckoutHandler.checkoutForm.querySelector('.shipping-information');
if (shippingAddressCheckbox.checked) {
shippingAddressAreaFieldsWrapper.classList.remove('hidden');
CheckoutHandler.otherShippingAddress = true;
CheckoutHandler.setShippingCountry(shippingCountrySelectElement[shippingCountrySelectElement.selectedIndex], true);
} else {
shippingAddressAreaFieldsWrapper.classList.add('hidden');
CheckoutHandler.otherShippingAddress = false;
CheckoutHandler.setShippingCountry(countrySelectElement[countrySelectElement.selectedIndex], false);
}
});
}
},
setShippingCountry: function setShippingCountry(selectedOption, otherShippingSelect) {
// If the right select is send to this function
// Change the shipping country
if (isset(selectedOption) && otherShippingSelect === CheckoutHandler.otherShippingAddress) {
CheckoutHandler.shippingCountryIso = selectedOption.value;
// Save shipping country to cookie so PHP can calculate the shopping cart formula's without javascript
Cookie.set('shipping-country-iso', CheckoutHandler.shippingCountryIso, 1);
// Remove warning messages
var warningIcon = CheckoutHandler.shippingCountryElement.querySelector('span.warning');
if (isset(warningIcon)) warningIcon.remove();
var noShippingCountryWarning = CheckoutHandler.checkoutForm.querySelector('.no-shipping-country');
if (isset(noShippingCountryWarning)) noShippingCountryWarning.remove();
CheckoutHandler.shippingCountryElement.classList.remove('hidden');
CheckoutHandler.shippingCountryElement.querySelector('.selected-country').setAttribute('data-shipping-country', CheckoutHandler.shippingCountryIso);
// Also update the pre loaded shipping costs by php if it isset
if (isset(CheckoutHandler.preLoadedShippingCost)) {
CheckoutHandler.preLoadedShippingCost.querySelector('.selected-country').setAttribute('data-shipping-country', CheckoutHandler.shippingCountryIso);
}
CheckoutHandler.updateShoppingCartSummary();
}
},
updateShoppingCartSummary: function updateShoppingCartSummary() {
// Create new XHR Object
var request = new XMLHttpRequest();
request.open('GET', '/shopping-cart/get-shopping-cart-summary', true);
// bind our event listener to the "load" event.
// "load" is fired when the response to our request is completed and without error.
request.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {
var summary = JSON.parse(this.responseText);
CheckoutHandler.shippingCountryElement.querySelector('.formatted-shipping-costs').innerHTML = summary.shippingCosts;
CheckoutHandler.shoppingCartTotalElement.classList.remove('hidden');
CheckoutHandler.shoppingCartTotalElement.querySelector('.total-formatted').innerHTML = summary.total;
// Also update the pre loaded total by php if it isset
if (isset(CheckoutHandler.preLoadedShippingCost)) CheckoutHandler.preLoadedShippingCost.querySelector('.formatted-shipping-costs').innerHTML = summary.shippingCosts;
if (isset(CheckoutHandler.preLoadedTotal)) CheckoutHandler.preLoadedTotal.querySelector('.total-formatted').innerHTML = summary.total;
} else {
// Error :(
console.log('Something went wrong...');
}
}
};
request.send();
request = null;
}
};
CheckoutHandler.init();
/* ==========================================================================
Cookie handler
- Primary usage for toggling the cookie message and/or switch
========================================================================== */
var CookieHandler = {
cookieMessage: null,
cookieSwitch: null,
cookieFadeOutAnimationDuration: 400,
acceptTracking: false,
// Initialize cookie handler
init: function init() {
// Bind cookie message without tracking to Handler
CookieHandler.cookieMessage = document.getElementById('cookie-message');
// If isset init the functions for cookie message without tracking
if (isset(CookieHandler.cookieMessage)) {
CookieHandler.initCookieMessageWithoutTracking();
} else {
// Else try to connect cookie message with tracking to Handler
CookieHandler.cookieMessage = document.getElementById('cookie-message-overlay');
// If isset init the functions for cookie message with tracking
if (isset(CookieHandler.cookieMessage)) {
CookieHandler.initCookieMessageWithTracking();
}
}
// 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.getElementById('cookie-switch');
// If isset init the functions for cookie switch
if (isset(CookieHandler.cookieSwitch)) {
CookieHandler.initCookieSwitch();
}
},
// Init the cookie message actions without tracking
initCookieMessageWithoutTracking: function initCookieMessageWithoutTracking() {
var closeButton = CookieHandler.cookieMessage.querySelector('.close-button');
if (isset(closeButton)) {
closeButton.addEventListener('click', CookieHandler.closeCookieMessage);
}
},
// Init the cookie message actions with tracking
initCookieMessageWithTracking: function initCookieMessageWithTracking() {
// Open the cookie settings event
var openCookieSettingsButton = CookieHandler.cookieMessage.querySelector('.open-menu');
if (isset(openCookieSettingsButton)) {
openCookieSettingsButton.addEventListener('click', CookieHandler.openCookieSettings);
}
// Toggle of the tracking input
var toggleTrackingInputWrapper = CookieHandler.cookieMessage.querySelector('#cookie-settings-menu #trackingCookie');
if (isset(toggleTrackingInputWrapper)) {
var toggleTrackingInput = toggleTrackingInputWrapper.querySelector('input');
toggleTrackingInput.addEventListener('change', CookieHandler.toggleTrackingSetting);
if (toggleTrackingInput.checked === true) {
CookieHandler.acceptTracking = true;
}
}
// Accept / Save cookies button event
var acceptButton = CookieHandler.cookieMessage.querySelector('.accept-cookie-button');
if (isset(acceptButton)) {
acceptButton.addEventListener('click', CookieHandler.setCookieSettings);
}
},
// Init the cookie switch actions
initCookieSwitch: function initCookieSwitch() {
// Toggle of the tracking input
var toggleTrackingInputWrapper = CookieHandler.cookieSwitch.querySelector('#trackingCookie');
if (isset(toggleTrackingInputWrapper)) {
var toggleTrackingInput = toggleTrackingInputWrapper.querySelector('input');
toggleTrackingInput.addEventListener('change', CookieHandler.toggleTrackingSetting);
// 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;
}
}
// Save cookies button event
var saveButton = CookieHandler.cookieSwitch.querySelector('#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('accepted');
} else {
CookieHandler.cookieMessage.classList.remove('accepted');
}
},
closeCookieMessage: function closeCookieMessage() {
Cookie.set('cookieMessage', true, 90);
CookieHandler.cookieMessage.classList.add('transition-out');
},
openCookieSettings: function openCookieSettings() {
CookieHandler.cookieMessage.querySelector('#cookie-settings-menu').classList.add('edit');
CookieHandler.cookieMessage.querySelector('#message-description').classList.add('hide');
},
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();
/* ==========================================================================
Google Maps handler
- https://developers.google.com/maps/documentation/javascript/adding-a-google-map
========================================================================== */
var MapsHandler = {
map: '',
key: 'AIzaSyCVGPUmRmQRxXvzzWu3Xyu77XebQxQ-f4Y',
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();
/* ==========================================================================
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();
/* ==========================================================================
Search Form Handler
========================================================================== */
var SearchFormHandler = {
searchForm: null,
searchFormInput: null,
init: function init() {
SearchFormHandler.searchForm = document.getElementById('searchForm');
if (isset(SearchFormHandler.searchForm)) {
// Add event listeners to form elements
SearchFormHandler.searchForm.addEventListener('submit', SearchFormHandler.submit);
SearchFormHandler.searchForm.querySelector('.submit').addEventListener('click', function () {
SearchFormHandler.submit(event);
});
SearchFormHandler.searchFormInput = SearchFormHandler.searchForm.querySelector('.search-input');
}
},
submit: function submit(e) {
e.preventDefault();
// Create redirect link / search link
var redirectLink = SearchFormHandler.searchForm.getAttribute('action');
redirectLink += SearchFormHandler.searchFormInput.value;
// Send user to link
window.location.href = redirectLink;
}
};
SearchFormHandler.init();
/* ==========================================================================
Shopping Cart Handler
========================================================================== */
var ShoppingCartHandler = {
shoppingCart: null,
shoppingCartCurrency: null,
shoppingCartItems: null,
shoppingCartItemsLength: null,
shoppingCartSubTotalElement: null,
shippingCountriesSelectPopUp: null,
shippingCountriesSelectLinks: null,
shippingCountryElement: null,
shippingCountryIso: null,
shoppingCartTotalElement: null,
init: function init() {
ShoppingCartHandler.shoppingCart = document.querySelector('.shopping-cart-row');
if (isset(ShoppingCartHandler.shoppingCart)) {
// Get currency for javascript formatting
ShoppingCartHandler.shoppingCartCurrency = ShoppingCartHandler.shoppingCart.getAttribute('data-currency');
// Get the shopping cart items
ShoppingCartHandler.shoppingCartItems = document.querySelectorAll('.shopping-cart-overview .items article');
ShoppingCartHandler.shoppingCartItemsLength = ShoppingCartHandler.shoppingCartItems.length;
// Get the shopping cart sub total variables
ShoppingCartHandler.shoppingCartSubTotalElement = document.querySelector('.shopping-cart-summary .pricing .sub-total');
// Get the shopping cart total variables
ShoppingCartHandler.shoppingCartAmountElement = document.querySelector('.shopping-cart-summary .shopping-cart-amount');
ShoppingCartHandler.shoppingCartTotalElement = document.querySelector('.shopping-cart-summary .pricing .total');
// Get the shipping country variables
ShoppingCartHandler.shippingCountryElement = document.querySelector('.shopping-cart-summary .pricing .shipping-cost');
ShoppingCartHandler.shippingCountryIso = ShoppingCartHandler.shippingCountryElement.querySelector('.selected-country').getAttribute('data-shipping-country');
// Shipping country selector elements
ShoppingCartHandler.shippingCountriesSelectPopUp = document.querySelector('.shipping-country-pop-up');
ShoppingCartHandler.shippingCountriesSelectLinks = document.querySelectorAll('.open-shipping-countries-pop-up');
// If the needed element are there, init the shipping country selector
if (isset(ShoppingCartHandler.shippingCountriesSelectPopUp) && isset(ShoppingCartHandler.shippingCountriesSelectLinks)) {
ShoppingCartHandler.initShippingCountrySelector();
}
if (isset(ShoppingCartHandler.shoppingCartItemsLength) && ShoppingCartHandler.shoppingCartItemsLength !== 0) {
ShoppingCartHandler.initShoppingCartItems();
}
}
},
/**
* Define the shopping cart items interaction
*/
initShoppingCartItems: function initShoppingCartItems() {
var _loop = function _loop(i) {
var shoppingCartItem = ShoppingCartHandler.shoppingCartItems[i];
var ProductUnitsInput = shoppingCartItem.querySelector('.units input');
var incrementProductUnitsButton = shoppingCartItem.querySelector('.units .increment');
var decrementProductUnitsButton = shoppingCartItem.querySelector('.units .decrement');
var removeProductButton = shoppingCartItem.querySelector('.remove');
incrementProductUnitsButton.addEventListener('click', function () {
ShoppingCartHandler.changeShoppingCartItemUnit(shoppingCartItem.id, 1);
});
decrementProductUnitsButton.addEventListener('click', function () {
ShoppingCartHandler.changeShoppingCartItemUnit(shoppingCartItem.id, -1);
});
removeProductButton.addEventListener('click', function () {
ShoppingCartHandler.removeShoppingCartItem(shoppingCartItem.id);
});
ProductUnitsInput.addEventListener('change', function () {
ShoppingCartHandler.changeShoppingCartItemUnit(shoppingCartItem.id, 0);
});
};
for (var i = 0; i < ShoppingCartHandler.shoppingCartItemsLength; i++) {
_loop(i);
}
},
/**
* Change a shopping cart item unit
*
* @param shoppingCartItemId
* @param changeValue
*/
changeShoppingCartItemUnit: function changeShoppingCartItemUnit(shoppingCartItemId, changeValue) {
// Get the product
var shoppingCartItem = document.getElementById(shoppingCartItemId);
// Get the product units input
var shoppingCartItemUnitsInput = shoppingCartItem.querySelector('#' + shoppingCartItemId + '-units');
var shoppingCartItemUnit = parseInt(shoppingCartItemUnitsInput.value);
var shoppingCartItemPricePcs = shoppingCartItem.querySelector('#' + shoppingCartItemId + '-price .individual');
// Check if the unit is a number else reset it to 1
if (isNaN(shoppingCartItemUnit)) {
shoppingCartItemUnit = 1;
} else {
// Change the product unit with the desired change value
shoppingCartItemUnit += changeValue;
}
// But it can't be below zero then you should remove it, and add/remove disabled on the decrement button
if (shoppingCartItemUnit <= 1) {
shoppingCartItemUnit = 1;
shoppingCartItemUnitsInput.parentNode.querySelector('.decrement').classList.add('disabled');
shoppingCartItemPricePcs.classList.remove('show');
} else {
shoppingCartItemUnitsInput.parentNode.querySelector('.decrement').classList.remove('disabled');
shoppingCartItemPricePcs.classList.add('show');
}
// Set the limit to 100 for a product
if (shoppingCartItemUnit >= 100) shoppingCartItemUnit = 100;
// Set the product unit
shoppingCartItemUnitsInput.value = shoppingCartItemUnit;
var shoppingCartItemPrice = shoppingCartItem.querySelector('#' + shoppingCartItemId + '-price');
shoppingCartItemPrice.querySelector('.total').innerHTML = ShoppingCartHandler.shoppingCartCurrency + ' ' + number_format(shoppingCartItemUnit * parseInt(shoppingCartItemPrice.getAttribute('data-price')) / 100, 2, ',', '.');
// Prepare ajax data
var ajaxRequestData = {
productId: shoppingCartItem.getAttribute('data-product-id'),
categoryId: shoppingCartItem.getAttribute('data-category-id'),
units: shoppingCartItemUnit
};
// Send ajax request
ShoppingCartHandler.sendPostRequest('change-shopping-cart-item-unit', ajaxRequestData);
// Wait a few ms because of cookie queue....
setTimeout(function () {
ShoppingCartHandler.updateShoppingCartSummary();
}, 400);
},
/**
* Remove a shopping cart item
*
* @param shoppingCartItemId
*/
removeShoppingCartItem: function removeShoppingCartItem(shoppingCartItemId) {
// Get the product
var shoppingCartItem = document.getElementById(shoppingCartItemId);
shoppingCartItem.classList.add('removed');
var ajaxRequestData = {
productId: shoppingCartItem.getAttribute('data-product-id'),
categoryId: shoppingCartItem.getAttribute('data-category-id')
};
ShoppingCartHandler.sendPostRequest('remove-shopping-cart-item', ajaxRequestData);
// Wait till animation is done
setTimeout(function () {
shoppingCartItem.remove();
ShoppingCartHandler.updateShoppingCartSummary();
}, 400);
},
// Functions belonging to the country selector
initShippingCountrySelector: function initShippingCountrySelector() {
var countrySelectLinks = ShoppingCartHandler.shippingCountriesSelectLinks.length;
for (var i = 0; i < countrySelectLinks; i++) {
var countrySelectLink = ShoppingCartHandler.shippingCountriesSelectLinks[i];
countrySelectLink.addEventListener('click', function () {
ShoppingCartHandler.shippingCountriesSelectPopUp.classList.toggle('show');
});
}
var selectorElement = ShoppingCartHandler.shippingCountriesSelectPopUp.querySelector('select');
var selector = new Selectr(selectorElement, {
placeholder: selectorElement.getAttribute('data-placeholder'),
defaultSelected: false
});
selector.on('selectr.open', function () {
ShoppingCartHandler.shippingCountriesSelectPopUp.classList.add('select-opened');
});
selector.on('selectr.select', function (selectedOption) {
var moveShippingCountrySelectContainer = false;
// Check if shipping country is defined by PHP
// Because else we need to move the select to an other element
if (!isset(ShoppingCartHandler.shippingCountryIso) || ShoppingCartHandler.shippingCountryIso === '') {
moveShippingCountrySelectContainer = true;
}
ShoppingCartHandler.shippingCountryIso = selectedOption.value;
ShoppingCartHandler.setShippingCountry(moveShippingCountrySelectContainer);
});
selector.on('selectr.close', function () {
ShoppingCartHandler.shippingCountriesSelectPopUp.classList.remove('select-opened');
ShoppingCartHandler.shippingCountriesSelectPopUp.classList.remove('show');
});
},
/**
* Set shipping cost and also trigger updateShoppingCartSummary
*
* @param moveShippingCountrySelectContainer
*/
setShippingCountry: function setShippingCountry(moveShippingCountrySelectContainer) {
// Set the shipping country
ShoppingCartHandler.shippingCountryElement.querySelector('.selected-country').setAttribute('data-shipping-country', ShoppingCartHandler.shippingCountryIso);
// Move shipping country select from element, show shipping cost paragraph and remove the no shipping div
if (moveShippingCountrySelectContainer) {
ShoppingCartHandler.shippingCountryElement.classList.remove('hidden');
var noShippingElement = ShoppingCartHandler.shippingCountriesSelectPopUp.parentNode;
ShoppingCartHandler.shippingCountryElement.appendChild(ShoppingCartHandler.shippingCountriesSelectPopUp);
noShippingElement.remove();
ShoppingCartHandler.shoppingCartTotalElement.classList.remove('hidden');
}
// Save shipping country to cookie so PHP can calculate the shopping cart formula's without javascript
Cookie.set('shipping-country-iso', ShoppingCartHandler.shippingCountryIso, 1);
// Wait a few ms because of cookie queue....
setTimeout(function () {
ShoppingCartHandler.updateShoppingCartSummary();
}, 400);
},
updateShoppingCartSummary: function updateShoppingCartSummary() {
// Create new XHR Object
var request = new XMLHttpRequest();
request.open('GET', '/shopping-cart/get-shopping-cart-summary', true);
// bind our event listener to the "load" event.
// "load" is fired when the response to our request is completed and without error.
request.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {
var summary = JSON.parse(this.responseText);
// console.log(summary);
// Update Shopping Cart
console.log(summary);
document.querySelector('header .main-row .shopping-cart-icon .icon').setAttribute('data-amount', summary.units);
ShoppingCartHandler.shoppingCartAmountElement.innerHTML = summary.units + ' items';
ShoppingCartHandler.shoppingCartSubTotalElement.querySelector('span').innerHTML = summary.subTotal;
ShoppingCartHandler.shippingCountryElement.querySelector('.formatted-shipping-costs').innerHTML = summary.shippingCosts;
ShoppingCartHandler.shoppingCartTotalElement.querySelector('.total-formatted').innerHTML = summary.total;
// console.log('update done');
} else {
// Error :(
console.log('Something went wrong...');
}
}
};
request.send();
request = null;
},
sendPostRequest: function sendPostRequest(subUrl, dataObject) {
// Convert object to data string for ajax call
var dataString = '';
Object.entries(dataObject).forEach(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
key = _ref2[0],
value = _ref2[1];
dataString += key + '=' + value + '&';
});
dataString = dataString.slice(0, -1);
// Create new XHR Object
var request = new XMLHttpRequest();
request.open('POST', '/shopping-cart/' + subUrl);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// bind our event listener to the "load" event.
// "load" is fired when the response to our request is completed and without error.
request.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {
// Success!
var resp = this.responseText;
// console.log(subUrl+ ' done');
} else {
// Error :(
console.log('Something went wrong...');
}
}
};
request.send(encodeURI(dataString));
request = null;
}
};
ShoppingCartHandler.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');
}
};
}
/* ==========================================================================
Youtube handler
========================================================================== */
var YoutubeHandler = {
youtubeClass: '.youtube-player',
players: [],
init: function init() {
// Get the youtube players containers
var youtubePlayers = document.querySelectorAll(YoutubeHandler.youtubeClass);
var youtubePlayersAmount = youtubePlayers.length;
for (var _i7 = 0; _i7 < youtubePlayersAmount; _i7++) {
var youtubePlayer = youtubePlayers[_i7];
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 _i8 = 0; _i8 < youtubePlayersAmount; _i8++) {
var youtubePlayer = YoutubeHandler.players[_i8];
// 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,
showinfo: 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();