Cannot read properties of null (reading 'classList') at window. Onload. Element not in the DOM when the script ran - javascript

I converted a page that contains HTML, CSS and JavaScript to a React app. The original website is working fine. But, when I load the React app, I get this error:
Uncaught TypeError: Cannot read properties of null (reading 'classList') at window. Onload
It seems like the element I'm trying to get is not in the DOM when the script runs.
So, I tried 5 following solutions without any positive result:
Putting the defer attribute on the external scripts.
I was thinking of moving the script in script.js, but I can't because I'm using an external script.
Using the type attribute with the module value, but I can't because I'm using an external script.
Deferring with event handling, but it's not working.
Tried the Event delegation, but is not working neither.
Here is my code:
App.js with some changes to adapt the HTML to JSX:
/* eslint-disable no-unused-vars */
/* eslint-disable no-script-url */
/* eslint-disable jsx-a11y/anchor-is-valid */
import logo from './logo.svg';
import './App.css';
function App() {
return (
<div>
{/* <!-- Start preloader --> */}
<div id="preloader">
<div id="ctn-preloader" className="ctn-preloader">
<div className="animation-preloader">
<div className="spinner"></div>
<div className="txt-loading">
<span data-text-preloader="C" className="letters-loading">
{' '}
C{' '}
</span>
<span data-text-preloader="H" className="letters-loading">
{' '}
H{' '}
</span>
<span data-text-preloader="A" className="letters-loading">
{' '}
A{' '}
</span>
<span data-text-preloader="R" className="letters-loading">
{' '}
R{' '}
</span>
<span data-text-preloader="G" className="letters-loading">
{' '}
G{' '}
</span>
<span data-text-preloader="E" className="letters-loading">
{' '}
E{' '}
</span>
<span data-text-preloader="M" className="letters-loading">
{' '}
M{' '}
</span>
<span data-text-preloader="E" className="letters-loading">
{' '}
E{' '}
</span>
<span data-text-preloader="N" className="letters-loading">
{' '}
N{' '}
</span>
<span data-text-preloader="T" className="letters-loading">
{' '}
T{' '}
</span>
</div>
</div>
<div className="loader-section section-left"></div>
<div className="loader-section section-right"></div>
</div>
</div>
{/* <!-- End preloader --> */}
</div>
);
}
export default App;
script.js without any change:
'use strict';
// Preloader
const preLoader = function () {
let preloaderWrapper = document.getElementById('preloader');
window.onload = () => {
preloaderWrapper.classList.add('loaded');
};
};
preLoader();
// getSiblings
var getSiblings = function (elem) {
const siblings = [];
let sibling = elem.parentNode.firstChild;
while (sibling) {
if (sibling.nodeType === 1 && sibling !== elem) {
siblings.push(sibling);
}
sibling = sibling.nextSibling;
}
return siblings;
};
/* Slide Up */
var slideUp = (target, time) => {
const duration = time ? time : 500;
target.style.transitionProperty = 'height, margin, padding';
target.style.transitionDuration = duration + 'ms';
target.style.boxSizing = 'border-box';
target.style.height = target.offsetHeight + 'px';
target.offsetHeight;
target.style.overflow = 'hidden';
target.style.height = 0;
window.setTimeout(() => {
target.style.display = 'none';
target.style.removeProperty('height');
target.style.removeProperty('overflow');
target.style.removeProperty('transition-duration');
target.style.removeProperty('transition-property');
}, duration);
};
/* Slide Down */
var slideDown = (target, time) => {
const duration = time ? time : 500;
target.style.removeProperty('display');
let display = window.getComputedStyle(target).display;
if (display === 'none') display = 'block';
target.style.display = display;
const height = target.offsetHeight;
target.style.overflow = 'hidden';
target.style.height = 0;
target.offsetHeight;
target.style.boxSizing = 'border-box';
target.style.transitionProperty = 'height, margin, padding';
target.style.transitionDuration = duration + 'ms';
target.style.height = height + 'px';
window.setTimeout(() => {
target.style.removeProperty('height');
target.style.removeProperty('overflow');
target.style.removeProperty('transition-duration');
target.style.removeProperty('transition-property');
}, duration);
};
// Get window top offset
function TopOffset(el) {
let rect = el.getBoundingClientRect(),
scrollTop = window.pageYOffset || document.documentElement.scrollTop;
return { top: rect.top + scrollTop };
}
// Header sticky activation
const headerStickyWrapper = document.querySelector('header');
const headerStickyTarget = document.querySelector('.header__sticky');
if (headerStickyTarget) {
let headerHeight = headerStickyWrapper.clientHeight;
window.addEventListener('scroll', function () {
let StickyTargetElement = TopOffset(headerStickyWrapper);
let TargetElementTopOffset = StickyTargetElement.top;
if (window.scrollY > TargetElementTopOffset) {
headerStickyTarget.classList.add('sticky');
} else {
headerStickyTarget.classList.remove('sticky');
}
});
}
// Back to top
const scrollTop = document.getElementById('scroll__top');
if (scrollTop) {
scrollTop.addEventListener('click', function () {
window.scroll({ top: 0, left: 0, behavior: 'smooth' });
});
window.addEventListener('scroll', function () {
if (window.scrollY > 300) {
scrollTop.classList.add('active');
} else {
scrollTop.classList.remove('active');
}
});
}
// blog swiper column3 activation
var swiper = new Swiper('.blog__swiper--activation', {
slidesPerView: 3,
loop: true,
clickable: true,
spaceBetween: 30,
breakpoints: {
1200: {
slidesPerView: 3
},
992: {
slidesPerView: 3
},
768: {
slidesPerView: 2,
spaceBetween: 30
},
480: {
slidesPerView: 2,
spaceBetween: 20
},
0: {
slidesPerView: 1
}
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev'
}
});
// testimonial swiper activation
var swiper = new Swiper('.testimonial__swiper--activation', {
slidesPerView: 2,
loop: true,
clickable: true,
spaceBetween: 30,
breakpoints: {
768: {
slidesPerView: 2,
spaceBetween: 30
},
576: {
slidesPerView: 2,
spaceBetween: 20
},
0: {
slidesPerView: 1
}
},
pagination: {
clickable: true,
el: '.swiper-pagination'
}
});
// testimonial swiper column1 activation
var swiper = new Swiper('.testimonial__swiper--column1', {
slidesPerView: 1,
loop: true,
clickable: true,
spaceBetween: 30,
pagination: {
clickable: true,
el: '.swiper-pagination'
}
});
// project swiper activation
var swiper = new Swiper('.project__swiper--activation', {
slidesPerView: 4,
loop: true,
spaceBetween: 30,
clickable: true,
roundLengths: true,
centeredSlides: true,
breakpoints: {
1200: {
slidesPerView: 4,
spaceBetween: 30
},
992: {
slidesPerView: 3,
spaceBetween: 25
},
768: {
slidesPerView: 3,
spaceBetween: 25
},
400: {
slidesPerView: 2,
spaceBetween: 15
},
300: {
slidesPerView: 1,
spaceBetween: 15
},
0: {
slidesPerView: 1
}
},
pagination: {
clickable: true,
el: '.swiper-pagination'
}
});
// brand swiper activation
var swiper = new Swiper('.brand__swiper--activation', {
slidesPerView: 5,
loop: true,
spaceBetween: 50,
clickable: true,
breakpoints: {
1366: {
slidesPerView: 5,
spaceBetween: 50
},
1200: {
slidesPerView: 5,
spaceBetween: 40
},
992: {
slidesPerView: 5,
spaceBetween: 30
},
768: {
slidesPerView: 4,
spaceBetween: 30
},
400: {
slidesPerView: 3,
spaceBetween: 20
},
200: {
slidesPerView: 2,
spaceBetween: 20
},
0: {
slidesPerView: 1
}
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev'
}
});
// related project swiper activation
var swiper = new Swiper('.related__project--swiper', {
slidesPerView: 4,
loop: true,
clickable: true,
spaceBetween: 30,
breakpoints: {
992: {
slidesPerView: 4
},
768: {
slidesPerView: 3,
spaceBetween: 30
},
576: {
slidesPerView: 3,
spaceBetween: 20
},
480: {
slidesPerView: 2,
spaceBetween: 20
},
300: {
slidesPerView: 2,
spaceBetween: 15
},
0: {
slidesPerView: 1
}
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev'
}
});
// tab activation
const tab = function (wrapper) {
let tabContainer = document.querySelector(wrapper);
if (tabContainer) {
tabContainer.addEventListener('click', function (evt) {
let listItem = evt.target;
if (listItem.hasAttribute('data-toggle')) {
let targetId = listItem.dataset.target,
targetItem = document.querySelector(targetId);
listItem.parentElement
.querySelectorAll('[data-toggle="tab"]')
.forEach(function (list) {
list.classList.remove('active');
});
listItem.classList.add('active');
targetItem.classList.add('active');
setTimeout(function () {
targetItem.classList.add('show');
}, 150);
getSiblings(targetItem).forEach(function (pane) {
pane.classList.remove('show');
setTimeout(function () {
pane.classList.remove('active');
}, 150);
});
}
});
}
};
// Homepage 1 product tab
tab('.project__tab--one');
tab('.product__tab--one');
// countdown activation
document.querySelectorAll('[data-countdown]').forEach(function (elem) {
const countDownItem = function (value, label) {
return `<div class="countdown__item" ${label}"><span class="countdown__number">${value}</span><p class="countdown__text">${label}</p></div>`;
};
const date = new Date(elem.getAttribute('data-countdown')).getTime(),
second = 1000,
minute = second * 60,
hour = minute * 60,
day = hour * 24;
const countDownInterval = setInterval(function () {
let currentTime = new Date().getTime(),
timeDistance = date - currentTime,
daysValue = Math.floor(timeDistance / day),
hoursValue = Math.floor((timeDistance % day) / hour),
minutesValue = Math.floor((timeDistance % hour) / minute),
secondsValue = Math.floor((timeDistance % minute) / second);
elem.innerHTML =
countDownItem(daysValue, 'days') +
countDownItem(hoursValue, 'hrs') +
countDownItem(minutesValue, 'mins') +
countDownItem(secondsValue, 'secs');
if (timeDistance < 0) clearInterval(countDownInterval);
}, 1000);
});
// adding & removing class function
const activeClassAction = function (toggle, target) {
const to = document.querySelector(toggle),
ta = document.querySelector(target);
if (to && ta) {
to.addEventListener('click', function (e) {
e.preventDefault();
let triggerItem = e.target;
if (triggerItem.classList.contains('active')) {
triggerItem.classList.remove('active');
ta.classList.remove('active');
} else {
triggerItem.classList.add('active');
ta.classList.add('active');
}
});
document.addEventListener('click', function (event) {
if (
!event.target.closest(toggle) &&
!event.target.classList.contains(toggle.replace(/\./, ''))
) {
if (
!event.target.closest(target) &&
!event.target.classList.contains(target.replace(/\./, ''))
) {
to.classList.remove('active');
ta.classList.remove('active');
}
}
});
}
};
activeClassAction('.account__currency--link', '.dropdown__currency');
activeClassAction('.language__switcher', '.dropdown__language');
activeClassAction(
'.offcanvas__language--switcher',
'.offcanvas__dropdown--language'
);
activeClassAction(
'.offcanvas__account--currency__menu',
'.offcanvas__account--currency__submenu'
);
activeClassAction('.footer__language--link', '.footer__dropdown--language');
activeClassAction('.footer__currency--link', '.footer__dropdown--currency');
// OffCanvas Sidebar Activation
function offcanvsSidebar(openTrigger, closeTrigger, wrapper) {
let OpenTriggerprimary__btn = document.querySelectorAll(openTrigger);
let closeTriggerprimary__btn = document.querySelector(closeTrigger);
let WrapperSidebar = document.querySelector(wrapper);
let wrapperOverlay = wrapper.replace('.', '');
function handleBodyClass(evt) {
let eventTarget = evt.target;
if (!eventTarget.closest(wrapper) && !eventTarget.closest(openTrigger)) {
WrapperSidebar.classList.remove('active');
document
.querySelector('body')
.classList.remove(`${wrapperOverlay}_active`);
}
}
if (OpenTriggerprimary__btn && WrapperSidebar) {
OpenTriggerprimary__btn.forEach(function (singleItem) {
singleItem.addEventListener('click', function (e) {
if (e.target.dataset.offcanvas != undefined) {
WrapperSidebar.classList.add('active');
document
.querySelector('body')
.classList.add(`${wrapperOverlay}_active`);
document.body.addEventListener('click', handleBodyClass.bind(this));
}
});
});
}
if (closeTriggerprimary__btn && WrapperSidebar) {
closeTriggerprimary__btn.addEventListener('click', function (e) {
if (e.target.dataset.offcanvas != undefined) {
WrapperSidebar.classList.remove('active');
document
.querySelector('body')
.classList.remove(`${wrapperOverlay}_active`);
document.body.removeEventListener('click', handleBodyClass.bind(this));
}
});
}
}
// Mini Cart
offcanvsSidebar(
'.minicart__open--btn',
'.minicart__close--btn',
'.offCanvas__minicart'
);
// Search Bar
offcanvsSidebar(
'.search__open--btn',
'.predictive__search--close__btn',
'.predictive__search--box'
);
// Offcanvas filter sidebar
offcanvsSidebar(
'.widget__filter--btn',
'.offcanvas__filter--close',
'.offcanvas__filter--sidebar'
);
/* Offcanvas Mobile Menu Function */
const offcanvasHeader = function () {
const offcanvasOpen = document.querySelector(
'.offcanvas__header--menu__open--btn'
),
offcanvasClose = document.querySelector('.offcanvas__close--btn'),
offcanvasHeader = document.querySelector('.offcanvas-header'),
offcanvasMenu = document.querySelector('.offcanvas__menu'),
body = document.querySelector('body');
/* Offcanvas SubMenu Toggle */
if (offcanvasMenu) {
offcanvasMenu
.querySelectorAll('.offcanvas__sub_menu')
.forEach(function (ul) {
const subMenuToggle = document.createElement('button');
subMenuToggle.classList.add('offcanvas__sub_menu_toggle');
ul.parentNode.appendChild(subMenuToggle);
});
}
/* Open/Close Menu On Click Toggle Button */
if (offcanvasOpen) {
offcanvasOpen.addEventListener('click', function (e) {
e.preventDefault();
if (e.target.dataset.offcanvas != undefined) {
offcanvasHeader.classList.add('open');
body.classList.add('mobile_menu_open');
}
});
}
if (offcanvasClose) {
offcanvasClose.addEventListener('click', function (e) {
e.preventDefault();
if (e.target.dataset.offcanvas != undefined) {
offcanvasHeader.classList.remove('open');
body.classList.remove('mobile_menu_open');
}
});
}
/* Mobile submenu slideToggle Activation */
let mobileMenuWrapper = document.querySelector('.offcanvas__menu_ul');
if (mobileMenuWrapper) {
mobileMenuWrapper.addEventListener('click', function (e) {
let targetElement = e.target;
if (targetElement.classList.contains('offcanvas__sub_menu_toggle')) {
const parent = targetElement.parentElement;
if (parent.classList.contains('active')) {
targetElement.classList.remove('active');
parent.classList.remove('active');
parent
.querySelectorAll('.offcanvas__sub_menu')
.forEach(function (subMenu) {
subMenu.parentElement.classList.remove('active');
subMenu.nextElementSibling.classList.remove('active');
slideUp(subMenu);
});
} else {
targetElement.classList.add('active');
parent.classList.add('active');
slideDown(targetElement.previousElementSibling);
getSiblings(parent).forEach(function (item) {
item.classList.remove('active');
item
.querySelectorAll('.offcanvas__sub_menu')
.forEach(function (subMenu) {
subMenu.parentElement.classList.remove('active');
subMenu.nextElementSibling.classList.remove('active');
slideUp(subMenu);
});
});
}
}
});
}
if (offcanvasHeader) {
document.addEventListener('click', function (event) {
if (
!event.target.closest('.offcanvas__header--menu__open--btn') &&
!event.target.classList.contains(
'.offcanvas__header--menu__open--btn'.replace(/\./, '')
)
) {
if (
!event.target.closest('.offcanvas-header') &&
!event.target.classList.contains(
'.offcanvas-header'.replace(/\./, '')
)
) {
offcanvasHeader.classList.remove('open');
body.classList.remove('mobile_menu_open');
}
}
});
}
/* Remove Mobile Menu Open Class & Hide Mobile Menu When Window Width in More Than 991 */
if (offcanvasHeader) {
window.addEventListener('resize', function () {
if (window.outerWidth >= 992) {
offcanvasHeader.classList.remove('open');
body.classList.remove('mobile_menu_open');
}
});
}
};
/* Mobile Menu Active */
offcanvasHeader();
// Increment & Decrement Qunatity Button
const quantityWrapper = document.querySelectorAll('.quantity__box');
if (quantityWrapper) {
quantityWrapper.forEach(function (singleItem) {
let increaseButton = singleItem.querySelector('.increase');
let decreaseButton = singleItem.querySelector('.decrease');
increaseButton.addEventListener('click', function (e) {
let input = e.target.previousElementSibling.children[0];
if (input.dataset.counter != undefined) {
let value = parseInt(input.value, 10);
value = isNaN(value) ? 0 : value;
value++;
input.value = value;
}
});
decreaseButton.addEventListener('click', function (e) {
let input = e.target.nextElementSibling.children[0];
if (input.dataset.counter != undefined) {
let value = parseInt(input.value, 10);
value = isNaN(value) ? 0 : value;
value < 1 ? (value = 1) : '';
value--;
input.value = value;
}
});
});
}
// Modal JS
const openEls = document.querySelectorAll('[data-open]');
const closeEls = document.querySelectorAll('[data-close]');
const isVisible = 'is-visible';
for (const el of openEls) {
el.addEventListener('click', function () {
const modalId = this.dataset.open;
document.getElementById(modalId).classList.add(isVisible);
});
}
for (const el of closeEls) {
el.addEventListener('click', function () {
this.parentElement.parentElement.parentElement.classList.remove(isVisible);
});
}
document.addEventListener('click', e => {
if (e.target == document.querySelector('.modal.is-visible')) {
document.querySelector('.modal.is-visible').classList.remove(isVisible);
}
});
document.addEventListener('keyup', e => {
if (e.key == 'Escape' && document.querySelector('.modal.is-visible')) {
document.querySelector('.modal.is-visible').classList.remove(isVisible);
}
});
// Accordion
function customAccordion(accordionWrapper, singleItem, accordionBody) {
let accoridonButtons = document.querySelectorAll(accordionWrapper);
accoridonButtons.forEach(function (item) {
item.addEventListener('click', function (evt) {
let itemTarget = evt.target;
if (
itemTarget.classList.contains('accordion__items--button') ||
itemTarget.classList.contains('widget__categories--menu__label')
) {
let singleAccordionWrapper = itemTarget.closest(singleItem),
singleAccordionBody =
singleAccordionWrapper.querySelector(accordionBody);
if (singleAccordionWrapper.classList.contains('active')) {
singleAccordionWrapper.classList.remove('active');
slideUp(singleAccordionBody);
} else {
singleAccordionWrapper.classList.add('active');
slideDown(singleAccordionBody);
getSiblings(singleAccordionWrapper).forEach(function (item) {
let sibllingSingleAccordionBody = item.querySelector(accordionBody);
item.classList.remove('active');
slideUp(sibllingSingleAccordionBody);
});
}
}
});
});
}
customAccordion(
'.accordion__container',
'.accordion__items',
'.accordion__items--body'
);
customAccordion(
'.widget__categories--menu',
'.widget__categories--menu__list',
'.widget__categories--sub__menu'
);
// footer widget js
let accordion = true;
const footerWidgetAccordion = function () {
accordion = false;
let footerWidgetContainer = document.querySelector('.main__footer');
footerWidgetContainer.addEventListener('click', function (evt) {
let singleItemTarget = evt.target;
if (singleItemTarget.classList.contains('footer__widget--button')) {
const footerWidget = singleItemTarget.closest('.footer__widget'),
footerWidgetInner = footerWidget.querySelector(
'.footer__widget--inner'
);
if (footerWidget.classList.contains('active')) {
footerWidget.classList.remove('active');
slideUp(footerWidgetInner);
} else {
footerWidget.classList.add('active');
slideDown(footerWidgetInner);
getSiblings(footerWidget).forEach(function (item) {
const footerWidgetInner = item.querySelector(
'.footer__widget--inner'
);
item.classList.remove('active');
slideUp(footerWidgetInner);
});
}
}
});
};
window.addEventListener('load', function () {
if (accordion) {
footerWidgetAccordion();
}
});
window.addEventListener('resize', function () {
document.querySelectorAll('.footer__widget').forEach(function (item) {
if (window.outerWidth >= 768) {
item.classList.remove('active');
item.querySelector('.footer__widget--inner').style.display = '';
}
});
if (accordion) {
footerWidgetAccordion();
}
});
// lightbox Activation
const customLightboxHTML = `<div id="glightbox-body" class="glightbox-container">
<div class="gloader visible"></div>
<div class="goverlay"></div>
<div class="gcontainer">
<div id="glightbox-slider" class="gslider"></div>
<button class="gnext gbtn" tabindex="0" aria-label="Next" data-customattribute="example">{nextSVG}</button>
<button class="gprev gbtn" tabindex="1" aria-label="Previous">{prevSVG}</button>
<button class="gclose gbtn" tabindex="2" aria-label="Close">{closeSVG}</button>
</div>
</div>`;
const lightbox = GLightbox({
touchNavigation: true,
lightboxHTML: customLightboxHTML,
loop: true
});
// CounterUp Activation
const wrapper = document.getElementById('funfactId');
if (wrapper) {
const counters = wrapper.querySelectorAll('.js-counter');
const duration = 400;
let isCounted = false;
document.addEventListener('scroll', function () {
const wrapperPos = wrapper.offsetTop - window.innerHeight;
if (!isCounted && window.scrollY > wrapperPos) {
counters.forEach(counter => {
const countTo = counter.dataset.count;
const countPerMs = countTo / duration;
let currentCount = 0;
const countInterval = setInterval(function () {
if (currentCount >= countTo) {
clearInterval(countInterval);
}
counter.textContent = Math.round(currentCount);
currentCount = currentCount + countPerMs;
}, 1);
});
isCounted = true;
}
});
}
Anyone has the correct solution?

Related

Unable to deactivate Controls

In my Carousel, there is an option to show more than 1 item at a time. It is activated by selecting the number of items you wish to show (max 4). The code refers to this as perView.
Items to display example
This carousel is glide.js, so everything is modular. I have 2 things of note getting activated, the Controls (next/prev button) and Breakpoints (think media queries).
The goal is to turn off the controls in mobile only if perView equals anything other than NaN (not a number)... When it is inactive, it returns NaN... so I guess the comment would be:
if perView does not equal NaN, then controls = false
and because i need this in a mobile breakpoint, I would put the code in the breakpoint bracket.
import AEM from 'base/js/aem';
import Glide, { Controls, Breakpoints, Autoplay, Keyboard, Swipe } from '#glidejs/glide/dist/glide.modular.esm';
class Carousel extends AEM.Component {
init() {
this.initCarousel();
}
initCarousel() {
const el = this.element;
const props = this.props;
const pauseButton = this.element.querySelector('.pause-button');
let perView = parseInt(props.cmpPerView, 10);
let cmpDelay = parseInt(props.cmpDelay, 10);
let autoPlay = true;
if (this.props.cmpAutoplay === 'false' ||
this.props.carouselAutoplay === 'false' ||
!Number.isNaN(perView) && perView < 1 ||
window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
autoPlay = false;
}
this.modules = {
Controls: Controls,
Breakpoints: Breakpoints,
Autoplay: Autoplay,
Keyboard: Keyboard,
Swipe: Swipe
};
this.options = {
type: props.cmpType,
perView: Number.isNaN(perView) ? 1 : perView,
autoplay: autoPlay ? cmpDelay : false,
peek: 0,
keyboard: true,
animationDuration: 400,
rewind: true,
breakpoints: {
768: {
perView: Number.isNaN(perView) || perView === 1 ? 1 : 3,
},
578: {
peek: perView > 1 ? 125 : 0,
perView: 1,
controls: perView > 1,
},
375: {
peek: perView > 1 ? 85 : 0,
perView: 1,
}
}
};
const glide = new Glide(el, this.options);
if (pauseButton && autoPlay) {
const pauseClasses = pauseButton.classList;
glide.on('play', () => {
pauseClasses.add('fa-pause');
pauseClasses.remove('fa-play');
});
glide.on('pause', () => {
pauseClasses.add('fa-play');
pauseClasses.remove('fa-pause');
});
pauseButton.addEventListener('click', () => {
if (pauseClasses.contains('fa-play')) {
glide.play();
} else {
glide.pause();
}
});
} else if (pauseButton) {
pauseButton.remove();
}
if (window.Granite && window.Granite.author && window.Granite.author.MessageChannel) {
/*
* Editor message handling:
* - subscribe to "cmp.panelcontainer" message requests sent by the editor frame
* - check that the message data panel container type is correct and that the id (path) matches this specific
* - Carousel component. If so, route the "navigate" operation to enact a navigation of the Carousel based
* - on index data
*/
this.element.querySelectorAll('.glide__slide').forEach(e => {
if (!e.classList.contains('glide__slide--active')) {
e.classList.add('visually-hidden');
}
});
window.CQ = window.CQ || {};
window.CQ.CoreComponents = window.CQ.CoreComponents || {};
window.CQ.CoreComponents.MESSAGE_CHANNEL = window.CQ.CoreComponents.MESSAGE_CHANNEL ||
new window.Granite.author.MessageChannel('cqauthor', window);
window.CQ.CoreComponents.MESSAGE_CHANNEL.subscribeRequestMessage('cmp.panelcontainer', message => {
if (message.data && message.data.type === 'cmp-carousel' &&
message.data.id === el.dataset.cmpPanelcontainerId) {
if (message.data.operation === 'navigate') {
let index = message.data.index;
if (index < 0) {
return;
}
this.element.querySelectorAll('.glide__slide').forEach((slide, i) => {
if (i === index) {
slide.classList.add('glide__slide--active');
slide.classList.remove('visually-hidden');
} else {
slide.classList.remove('glide__slide--active');
slide.classList.add('visually-hidden');
}
});
}
}
});
} else {
glide.mount(this.modules);
}
}
}
export { Carousel };
So I have
controls: perView > 1
in the 578 breakpoint... but it doesn't work.

in case i have multiple monaco diff editor in the same page, diff will be only visible in the first instance

I have a Vue component that rendering diff editor of Monaco.
Once I have more than one instance of it on the same page, the diff is only shown in the first one.
template:
<template>
<div>
<div ref="diffEditor" class="vue--monaco-diff-editor"></div>
</div>
</template>
script:
async mounted(): Promise<void> {
await this.importMonacoPackage();
this.$nextTick(() => {
if (!monaco) {
throw new Error('monaco is not initialized');
}
const originalModel = monaco.editor.createModel(
this.versions[0].code,
MonacoHelper.markdownLangToMonacoLang(this.versions[0].lang),
);
const modifiedModel = monaco.editor.createModel(
this.versions[1].code,
MonacoHelper.markdownLangToMonacoLang(this.versions[1].lang),
);
let diffEditorElement = this.$refs.diffEditor;
this.diffEditor = monaco.editor.createDiffEditor(
diffEditorElement as HTMLElement,
{
scrollbar: {
vertical: 'hidden',
horizontal: 'hidden',
handleMouseWheel: true,
},
wordWrap: 'on',
readOnly: true,
scrollBeyondLastLine: false,
minimap: {
enabled: false,
},
automaticLayout: true,
},
);
if (!this.diffEditor) {
return;
}
this.diffEditor.setModel({
original: originalModel,
modified: modifiedModel,
});
// set the editor height to scale with the content height automatically
// see https://github.com/microsoft/monaco-editor/issues/794
const originalContentHeight = this.diffEditor
.getOriginalEditor()
.getContentHeight();
const modifiedContentHeight = this.diffEditor
.getModifiedEditor()
.getContentHeight();
let contentHeight = Math.max(
originalContentHeight,
modifiedContentHeight,
);
// allow for a single empty line at the bottom, default line height is 18px
contentHeight = contentHeight + 18;
const domNode = this.diffEditor.getDomNode();
domNode.style.height = `${contentHeight}px`;
this.diffEditor.layout();
});
},
methods: {
async importMonacoPackage() {
// eslint-disable-next-line import/no-unresolved
monaco = await import('../../../lib/monaco-editor');
},
},
I'm using
"monaco-editor": "^0.24.0","vue": "^2.6.13".
any ideas what I'm doing wrong ? and why just the first instance showing the diff highlights?

Javascript How to get Nested Objects Correctly

I am building an Electron app that gets a certain kind of json file from the user and logs all the data from it. But I am getting an error about getting undefined from the quantity:
Json File:
{
"tiers": [
{
"trades": [
{
"wants": [
{
"item": "minecraft:string",
"quantity": {
"min": 15,
"max": 20
}
}
],
"gives": [
{
"item": "minecraft:emerald"
}
]
},
{
"wants": [
{
"item": "minecraft:emerald"
}
],
"gives": [
{
"item": "minecraft:arrow",
"quantity": {
"min": 8,
"max": 12
}
}
]
}
]
},
{
"trades": [
{
"wants": [
{
"item": "minecraft:gravel",
"quantity": 10
},
{
"item": "minecraft:emerald",
"quantity": 1
}
],
"gives": [
{
"item": "minecraft:flint",
"quantity": {
"min": 6,
"max": 10
}
}
]
},
{
"wants": [
{
"item": "minecraft:emerald",
"quantity": {
"min": 2,
"max": 3
}
}
],
"gives": [
{
"item": "minecraft:bow"
}
]
}
]
}
]
}
And this is the main.js:
const { app, BrowserWindow, ipcMain, dialog, ipcRenderer, globalShortcut } = require('electron');
const { autoUpdater } = require('electron-updater');
const path = require('path');
const Store = require('./classes/Store.js');
const { electron } = require('process');
const { setTimeout } = require('timers');
// import Vue from 'vue';
// import Vuetify from 'vuetify';
// import "vuetify/dist/vuetify.min.css";
// Vue.use(Vuetify);
let win;
let loadingScreen;
const store = new Store({
configName: 'settings',
defaults: {
windowBounds: {
width: 800,
height: 600,
x: 0,
y: 0,
},
isMaximized: false,
fullscreen: false
}
});
function createLoadingScreen() {
loadingScreen = new BrowserWindow(Object.assign({
width: 200,
height: 220,
frame: false,
transparent: true,
icon: 'build/icons/icon.png',
webPreferences: {
worldSafeExecuteJavaScript: true
}
}));
loadingScreen.setResizable(false);
loadingScreen.loadURL('file://' + __dirname + '/extraWindows/loadingScreen/loading.html');
loadingScreen.setOverlayIcon('build/icons/icon.png', "Route");
loadingScreen.on('closed', () => loadingScreen = null);
loadingScreen.webContents.on('did-finish-load', () => {
loadingScreen.show();
});
}
function createWindow() {
let width = store.get('windowBounds.width');
let height = store.get('windowBounds.height');
let x = store.get('windowBounds.x');
let y = store.get('windowBounds.y');
let isMaximized = store.get('isMaximized');
win = new BrowserWindow({
width,
height,
x,
y,
icon: 'build/icons/icon.png',
frame: false,
titleBarStyle: "hidden",
webPreferences: {
enableRemoteModule: true,
nodeIntegration: true,
webSafeExecuteJavaScript: true
},
show: false
})
win.setOverlayIcon('build/icons/icon.png', "Route");
if(isMaximized == true) {
win.maximize();
}
win.loadFile('index.html');
win.on('closed', function() {
win = null;
settingScreen = null;
});
win.webContents.on('did-finish-load', () => {
if(loadingScreen) {
loadingScreen.close();
win.show();
}
})
win.on('resize', () => {
store.set('windowBounds', win.getBounds());
});
win.on('move', () => {
store.set('windowBounds', win.getBounds());
})
win.on('maximize', () => {
store.set('isMaximized', true);
})
win.on('unmaximize', () => {
store.set('isMaximized', false);
})
win.on('show', () => {
win.setFullScreen(store.get('fullscreen'));
})
win.once('ready-to-show', () => {
autoUpdater.checkForUpdatesAndNotify();
})
}
function createSettings() {
settingScreen = new BrowserWindow({
width: 600,
height: 800,
frame: false,
parent: win,
modal: true,
titleBarStyle: "hidden",
webPreferences: {
enableRemoteModule: true,
nodeIntegration: true,
worldSafeExecuteJavaScript: true
},
show: false
})
settingScreen.loadFile('extraWindows/settingsScreen/settings.html');
settingScreen.on('close', (event) => {
event.preventDefault();
settingScreen.hide();
})
}
app.on('ready', () => {
createLoadingScreen();
setTimeout(() => {
createWindow();
createSettings();
}, 5000); // Set to 5000
});
app.on('window-all-closed', () => {
if(process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if(BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
})
app.whenReady().then(() => {
globalShortcut.register('CmdOrCtrl+O', () => {
win.webContents.send('openFile');
})
globalShortcut.register('CmdOrCtrl+D', () => {
win.webContents.send('closeFile');
})
})
// These are all of the ipc functions needed for Route to work
ipcMain.handle('viewSettings', (event, arg) => {
if(arg === "true") {
settingScreen.show();
} else if(arg === "false") {
settingScreen.hide();
}
});
ipcMain.handle('changeSettings', (event, arg) => {
if(arg === "fullScreen") {
if(win.isFullScreen() == false) {
win.setFullScreen(true);
store.set('fullscreen', true);
} else {
win.setFullScreen(false);
store.set('fullscreen', false);
}
// Fill in the data for fullscreen
} else if(arg === 'themechooser') {
// Fill in the data for themes
}
});
ipcMain.on('appVersion', (event) => {
event.sender.send('appVersion', { version: app.getVersion() });
});
ipcMain.on('restartApp', () => {
autoUpdater.quitAndInstall();
})
autoUpdater.on('updateAvailable', () => {
win.webContents.send('updateAvailable');
});
autoUpdater.on('updateDownloaded', () => {
win.webContents.send('updateDownloaded');
})
And this is the renderer.js:
const { app, ipcRenderer } = require('electron');
const Store = require('./classes/Store.js');
const remote = require('electron').remote;
const dialog = require('electron').remote.dialog;
const fs = require('fs');
const { S_IFDIR } = require('constants');
const { electron } = require('process');
const { version } = require('os');
let currentWindow = remote.getCurrentWindow();
let $ = function(selector) {
return document.querySelector(selector);
}
let projectArray = [];
// There can only be 5 projects max. Might add more.
let projectCount = 0;
document.querySelector('#tradeSetup').addEventListener('click', () => {
//Create a new setup.
alert("This works!");
});
let fileOpenerOptions = {
title: "Open Trade File",
defaultPath: "C:\\",
buttonLabel: "Start Coding",
properties: [ 'openFile' ],
filters: [
{ name: 'Json', extensions: ['json'] },
{ name: 'All FIles', extensions: ['*'] }
]
}
//Top bar buttons
function openFile() {
dialog.showOpenDialog(currentWindow, fileOpenerOptions).then(fileNames => {
if(fileNames == undefined || fileNames == null) {
console.log("No file selected.");
return;
} else {
let projectName = path.basename(fileNames.filePaths[0], path.extname(fileNames.filePaths[0]));
let rawFileData = fs.readFileSync(fileNames.filePaths[0]);
let fileData = JSON.parse(rawFileData);
console.log(fileData);
if(projectCount < 5) {
projectCount++;
createProject(projectName, fileData);
// Run code
} else if (projectCount == 5) {
alert('Support for more projects is not available yet!\nPlease wait until a later update to have more than 5 projects.');
}
}
});
}
function openSettings() {
ipcRenderer.invoke('viewSettings', "true");
}
function closeFile() {
if(document.querySelector('.activeProjectButton') == null) {
console.log("No project to close.");
} else {
let contine = confirm("Is this project the furthest project to the right? If not, please don't close it.\nThis is a bug that is being worked on.");
if(contine == true) {
document.querySelector('.activeProjectButton').remove();
document.querySelector('.activeWorkspace').remove();
projectCount--;
document.querySelectorAll('.inactiveProjectWorkspace').j--;
}
// Add a fun little secret for users
}
}
document.querySelector('#openFile').addEventListener('click', () => {
openFile();
});
document.querySelector('#openSettings').addEventListener('click', () => {
openSettings();
});
document.querySelector('#closeFile').addEventListener('click', () => {
closeFile();
})
// Create and switch projects
function createProject(name, projectData) {
// This is a beta feature for now. It is not finished
// Create the tab
let projectInProduction = document.createElement("button");
projectInProduction.id = "project" + projectCount + "Click";
projectInProduction.classList.add("invisButton");
projectInProduction.classList.add("inactiveProjectButton");
projectInProduction.classList.add("project" + projectCount);
projectInProduction.innerHTML += (name);
// Remove the welcome message
document.querySelector('.unHidden').classList.add('hidden');
document.querySelector('.unHidden').classList.remove('unHidden');
//Create the workspace
let workspaceInProduction = document.createElement("div");
workspaceInProduction.classList.add("inactiveWorkspace");
projectArray.push(projectData);
if(projectArray[projectCount - 1].tiers == null) {
alert("This is not a trade file!\nPlease use a trade file!");
} else {
$('.projects').appendChild(projectInProduction);
$('#jsonProjectContainer').appendChild(workspaceInProduction);
let table = document.createElement('table');
table.innerHTML += '<tr><th colspan="3">Buying</th><th colspan="2">Selling</th></tr>';
table.classList.add('table' + projectCount);
workspaceInProduction.appendChild(table);
let tiers = Object.keys(projectArray[projectCount - 1].tiers).length;
console.log(tiers);
for(let i = 0; i < tiers; i++) {
let tradesC = Object.keys(projectArray[projectCount - 1].tiers[i].trades).length;
for(let j = 0; j < tradesC; j++) {
let wants = Object.keys(projectArray[projectCount - 1].tiers[i].trades[j].wants);
let wantsC = Object.keys(projectArray[projectCount - 1].tiers[i].trades[j].wants).length;
let gives = Object.keys(projectArray[projectCount - 1].tiers[i].trades[j].gives);
for(let k = 0; k < wantsC; k++) {
let wantsItem = projectArray[projectCount - 1].tiers[i].trades[j].wants[k].item;
let wantsMin = projectArray[projectCount - 1].tiers[i].trades[j].wants[k].quantity["min"];
let wantsMax = projectArray[projectCount - 1].tiers[i].trades[j].wants[k].quantity["max"];
let givesItem = projectArray[projectCount - 1].tiers[i].trades[j].gives[0].item;
console.log("Wants: " + wants[k]);
console.log("Min: " + wantsMin);
console.log("Max: " + wantsMax);
console.log("Item: " + wantsItem);
console.log("Gives: " + gives);
console.log("Item: " + givesItem);
}
}
}
}
// Add a onlclick function to make switching projects work
j = projectCount;
document.getElementById('project' + projectCount + 'Click').addEventListener('click', function(j) {
let buttonIndex = j;
let buttonNodes = $('.projects').children;
let workspaceNodes = $('#jsonProjectContainer').children;
for(let i = 0; i < buttonNodes.length; i++) {
if(i == (j - 1)) {
buttonNodes[i].classList.add('activeProjectButton');
buttonNodes[i].classList.remove('inactiveProjectButton');
workspaceNodes[i].classList.add('activeWorkspace');
workspaceNodes[i].classList.remove('inactiveWorkspace');
} else {
buttonNodes[i].classList.remove('activeProjectButton');
buttonNodes[i].classList.add('inactiveProjectButton');
workspaceNodes[i].classList.remove('activeWorkspace');
workspaceNodes[i].classList.add('inactiveWorkspace');
}
}
}.bind(null, j));
}
// Title bar scripts
ipcRenderer.on('openFile', () => {
openFile();
})
ipcRenderer.on('closeFile', () => {
closeFile();
})
// App updates
ipcRenderer.send('appVersion');
ipcRenderer.on('appVersion', (event, arg) => {
ipcRenderer.removeAllListeners('appVersion');
//version.innerText = ;
});
const updateNotifier = document.getElementById('updateNotifier');
const updateAvailability = document.getElementById('updateAvailability');
const restartButton = document.getElementById('restartButton');
ipcRenderer.on('updateAvailable', () => {
ipcRenderer.removeAllListeners('updateAvailable');
updateAvailability.innerText = 'A new version of Route is available. Downloading now...';
updateNotifier.classList.remove('hidden');
});
ipcRenderer.on('update_downloaded', () => {
ipcRenderer.removeAllListeners('updateDownloaded');
updateAvailability.innerText = 'Update downloaded. It will be installed on restart. Restart to continue.';
restartButton.classList.remove('hidden');
updateNotifier.classList.remove('hidden');
});
function restartApp() {
ipcRenderer.send('restartApp');
}
And this is the index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>route - Minecraft Addon Tool</title>
<!-- https://electronjs.org/docs/tutorial/security#csp-meta-tag -->
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
<link href="index.css" type="text/css" rel="stylesheet" />
<link href="node_modules/#mdi/font/css/materialdesignicons.min.css" type="text/css" rel="stylesheet" />
</head>
<body>
<script>
// const electron = require('electron').remote;
const path = require('path');
const customTitleBar = require('custom-electron-titlebar');
const Menu = require('electron').remote.Menu;
const MenuItem = require('electron').remote.MenuItem;
let mainTitlebar = new customTitleBar.Titlebar({
backgroundColor: customTitleBar.Color.fromHex('#391B47'),
icon: 'build/icons/icon.png'
});
const menu = new Menu();
menu.append(new MenuItem({
label: 'Github',
click: () => {
currentWindow.webContents.on('new-window', require('electron').shell.openExternal('https://github.com/Gekocaretaker/route'));
}
}));
menu.append(new MenuItem({
label: 'Discord',
click: () => {
console.log("Hiding the link!");
}
}));
menu.append(new MenuItem({
label: 'File',
submenu: [
{
label: 'Open File',
accelerator: 'Ctrl+O',
click: () => {
openFile();
}
},
{
label: 'Close File',
accelerator: 'Ctrl+D',
click: () => {
closeFile();
}
},
{
label: 'New File',
accelerator: 'Ctrl+N',
click: () => {
console.log("This is not yet available.");
}
}
]
}))
mainTitlebar.updateMenu(menu);
</script>
<div class="grid-container">
<div class="buttons">
<div class="tooltip openFileContainer">
<button id="openFile" class="invisButton"><span class="mdi mdi-file mdi-48px"></span></button>
<div>File</div>
</div>
<div class="tooltip settingsContainer">
<button id="openSettings" class="invisButton"><span class="mdi mdi-cog-outline mdi-48px"></span></button>
<div>Settings</div>
</div>
<div class="tooltip closeProjectContainer">
<button id="closeFile" class="invisButton"><span class="mdi mdi-close mdi-48px"></span></button>
<div>Close Project</div>
</div>
</div>
<div class="projects">
<!-- <div class="project1">
<button class="invisButton activeProjectButton" id="project1Click">Project 1</button>
</div> -->
</div>
<div class="jsonEditor">
<!-- <div class="workSpace1 activeWorkSpace">
<h3>This is Workspace 1</h3>
</div> -->
<div id="jsonProjectContainer"></div>
<div class="unHidden">
<p id="welcomeMessage">Hello User! Welcome to Route. I hope you enjoy using this!</p>
</div>
<div id="updateNotifier" class="hidden">
<p id="updateAvailability"></p>
<button id="restartButton" onclick="restartApp()"></button>
</div>
</div>
<div class="sidebar">
<div class="tooltip tradeBuilder">
<button id="tradeSetup" class="invisButton"><span class="mdi mdi-apache-kafka mdi-48px"></span></button>
<div>Basic Trade</div>
</div>
<div class="tooltip whatNext">
<button id="whatsNext" class="invisButton"><span class="mdi mdi-help mdi-48px"></span></button>
<div>Whats Next?</div>
</div>
</div>
</div>
<script src="renderer.js"></script>
</body>
</html>
This is the error:
Uncaught (in promise) TypeError: Cannot read property 'min' of undefined
at createProject (renderer.js:126)
at renderer.js:48
And I am pretty sure the error comes from how I get "min". I have tried using ["min"], ['min'], .min, and as a last resort, [0].
I have the code hosted on github, if needing to be shared.
If you would debug your code, you would notice that the error occurs when j=1 and k=0. Then if you check the object, you notice that at that location there is no question property:
{
"tiers": [
{
"trades": [
{
/* ... */
},
{
"wants": [
{
"item": "minecraft:emerald"
/* no quantity here */
}
],
"gives": [
/* ... */
]
}
]
},
/* ... */
So you'll have to decide what you want to happen when there is no quantity property. You can for instance use the optional chaining operator to use a default value:
let wantsMin = projectArray[projectCount - 1].tiers[i].trades[j].wants[k].quantity.?min || 0;
let wantsMax = projectArray[projectCount - 1].tiers[i].trades[j].wants[k].quantity.?max || 0;
The above would give 0 as value for the min/max values that are missing. But all depends on what you want to happen in this scenario.
This is just an example on how you can circumvent the error, but might not be the right way to deal with it in light of the rest of your code. That is up to you to determine.
This code is to access or process the values that are in nested array.we are iterating with loops and checks the iterating values that either it is an array or not with .isArray if yes we fetch the value ,if no we return the value.
var arr=[['hi'],
['hello',['welcome','bye']],
['world']];
for(var i=0; i<arr.length; i++)
{
for(var j=0; j<arr.length; j++)
{
if(Array.isArray(arr[i][j]))
{
for(var k=0; k<arr.length; k++)
{
console.log(arr[i][j][k]);
}
}
else
{
console.log(arr[i][j]);
}
}
}

Swiper JS destroy() not firing

I'm trying to disable Swiper JS (https://github.com/nolimits4web/swiper) on anything other than mobile using the destroy() function, but I get the error Uncaught TypeError: swiper.destroy is not a function.
I've tried various different things, but I can't get it to work.
import Swiper from 'swiper';
const ImageCarousel = $el => {
let swiper = Swiper;
let init = false;
function swiperMode() {
let mobile = window.matchMedia('(min-width: 0px) and (max-width: 768px)');
let tablet = window.matchMedia('(min-width: 769px) and (max-width: 1024px)');
let desktop = window.matchMedia('(min-width: 1025px)');
// Enable (for mobile)
if (mobile.matches) {
if (!init) {
init = true;
const MySwiper = new Swiper('.swiper-container-cta', {
direction: 'horizontal',
loop: false,
speed: 1000,
grabCursor: true,
watchSlidesProgress: false,
mousewheelControl: true,
keyboardControl: true,
width: 280,
spaceBetween: 16,
});
}
}
// Disable (for tablet)
else if (tablet.matches) {
swiper.destroy();
init = false;
}
// Disable (for desktop)
else if (desktop.matches) {
swiper.destroy();
init = false;
}
}
// console.log(swiper);
window.addEventListener('load', () => {
swiperMode();
});
window.addEventListener('resize', () => {
swiperMode();
});
};
export default ImageCarousel;
Did you try MySwiper.destroy(); instead of swiper.destroy();

Calling toastr makes the webpage jump to top of page

I'm seeking a solution for the toastr.js "error" that causes the webpage, if scrolled down, to jump up again when a new toastr is displayed
GitHub page containing the script
I've tried to change the top to auto, but that wasn't an accepted parameter, because nothing showed up then.
Isn't there any way to make it appear where the mouse is at the moment?
.toast-top-center {
top: 12px;
margin: 0 auto;
left: 43%;
}
this has the calling code:
<p><span style="font-family:'Roboto','One Open Sans', 'Helvetica Neue', Helvetica, sans-serif;color:rgb(253,253,255); font-size:16px ">
xxxxxxxxxxxxx
</span></p>
This is the function code:
<script type='text/javascript'> function playclip() {
toastr.options = {
"debug": false,
"positionClass": "toast-top-center",
"onclick": null,
"fadeIn": 800,
"fadeOut": 1000,
"timeOut": 5000,
"extendedTimeOut": 1000
}
toastr["error"]("This link is pointing to a page that hasn't been written yet,</ br> sorry for the inconvenience?"); } </script>
And this is the script itself:
/*
* Toastr
* Copyright 2012-2015
* Authors: John Papa, Hans Fjällemark, and Tim Ferrell.
* All Rights Reserved.
* Use, reproduction, distribution, and modification of this code is subject to the terms and
* conditions of the MIT license, available at http://www.opensource.org/licenses/mit-license.php
*
* ARIA Support: Greta Krafsig
*
* Project: https://github.com/CodeSeven/toastr
*/
/* global define */
(function (define) {
define(['jquery'], function ($) {
return (function () {
var $container;
var listener;
var toastId = 0;
var toastType = {
error: 'error',
info: 'info',
success: 'success',
warning: 'warning'
};
var toastr = {
clear: clear,
remove: remove,
error: error,
getContainer: getContainer,
info: info,
options: {},
subscribe: subscribe,
success: success,
version: '2.1.3',
warning: warning
};
var previousToast;
return toastr;
////////////////
function error(message, title, optionsOverride) {
return notify({
type: toastType.error,
iconClass: getOptions().iconClasses.error,
message: message,
optionsOverride: optionsOverride,
title: title
});
}
function getContainer(options, create) {
if (!options) { options = getOptions(); }
$container = $('#' + options.containerId);
if ($container.length) {
return $container;
}
if (create) {
$container = createContainer(options);
}
return $container;
}
function info(message, title, optionsOverride) {
return notify({
type: toastType.info,
iconClass: getOptions().iconClasses.info,
message: message,
optionsOverride: optionsOverride,
title: title
});
}
function subscribe(callback) {
listener = callback;
}
function success(message, title, optionsOverride) {
return notify({
type: toastType.success,
iconClass: getOptions().iconClasses.success,
message: message,
optionsOverride: optionsOverride,
title: title
});
}
function warning(message, title, optionsOverride) {
return notify({
type: toastType.warning,
iconClass: getOptions().iconClasses.warning,
message: message,
optionsOverride: optionsOverride,
title: title
});
}
function clear($toastElement, clearOptions) {
var options = getOptions();
if (!$container) { getContainer(options); }
if (!clearToast($toastElement, options, clearOptions)) {
clearContainer(options);
}
}
function remove($toastElement) {
var options = getOptions();
if (!$container) { getContainer(options); }
if ($toastElement && $(':focus', $toastElement).length === 0) {
removeToast($toastElement);
return;
}
if ($container.children().length) {
$container.remove();
}
}
// internal functions
function clearContainer (options) {
var toastsToClear = $container.children();
for (var i = toastsToClear.length - 1; i >= 0; i--) {
clearToast($(toastsToClear[i]), options);
}
}
function clearToast ($toastElement, options, clearOptions) {
var force = clearOptions && clearOptions.force ? clearOptions.force : false;
if ($toastElement && (force || $(':focus', $toastElement).length === 0)) {
$toastElement[options.hideMethod]({
duration: options.hideDuration,
easing: options.hideEasing,
complete: function () { removeToast($toastElement); }
});
return true;
}
return false;
}
function createContainer(options) {
$container = $('<div/>')
.attr('id', options.containerId)
.addClass(options.positionClass);
$container.appendTo($(options.target));
return $container;
}
function getDefaults() {
return {
tapToDismiss: true,
toastClass: 'toast',
containerId: 'toast-container',
debug: false,
showMethod: 'fadeIn', //fadeIn, slideDown, and show are built into jQuery
showDuration: 300,
showEasing: 'swing', //swing and linear are built into jQuery
onShown: undefined,
hideMethod: 'fadeOut',
hideDuration: 1000,
hideEasing: 'swing',
onHidden: undefined,
closeMethod: false,
closeDuration: false,
closeEasing: false,
closeOnHover: true,
extendedTimeOut: 1000,
iconClasses: {
error: 'toast-error',
info: 'toast-info',
success: 'toast-success',
warning: 'toast-warning'
},
iconClass: 'toast-info',
positionClass: 'toast-top-right',
timeOut: 5000, // Set timeOut and extendedTimeOut to 0 to make it sticky
titleClass: 'toast-title',
messageClass: 'toast-message',
escapeHtml: false,
target: 'body',
closeHtml: '<button type="button">×</button>',
closeClass: 'toast-close-button',
newestOnTop: true,
preventDuplicates: false,
progressBar: false,
progressClass: 'toast-progress',
rtl: false
};
}
function publish(args) {
if (!listener) { return; }
listener(args);
}
function notify(map) {
var options = getOptions();
var iconClass = map.iconClass || options.iconClass;
if (typeof (map.optionsOverride) !== 'undefined') {
options = $.extend(options, map.optionsOverride);
iconClass = map.optionsOverride.iconClass || iconClass;
}
if (shouldExit(options, map)) { return; }
toastId++;
$container = getContainer(options, true);
var intervalId = null;
var $toastElement = $('<div/>');
var $titleElement = $('<div/>');
var $messageElement = $('<div/>');
var $progressElement = $('<div/>');
var $closeElement = $(options.closeHtml);
var progressBar = {
intervalId: null,
hideEta: null,
maxHideTime: null
};
var response = {
toastId: toastId,
state: 'visible',
startTime: new Date(),
options: options,
map: map
};
personalizeToast();
displayToast();
handleEvents();
publish(response);
if (options.debug && console) {
console.log(response);
}
return $toastElement;
function escapeHtml(source) {
if (source == null) {
source = '';
}
return source
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>');
}
function personalizeToast() {
setIcon();
setTitle();
setMessage();
setCloseButton();
setProgressBar();
setRTL();
setSequence();
setAria();
}
function setAria() {
var ariaValue = '';
switch (map.iconClass) {
case 'toast-success':
case 'toast-info':
ariaValue = 'polite';
break;
default:
ariaValue = 'assertive';
}
$toastElement.attr('aria-live', ariaValue);
}
function handleEvents() {
if (options.closeOnHover) {
$toastElement.hover(stickAround, delayedHideToast);
}
if (!options.onclick && options.tapToDismiss) {
$toastElement.click(hideToast);
}
if (options.closeButton && $closeElement) {
$closeElement.click(function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else if (event.cancelBubble !== undefined && event.cancelBubble !== true) {
event.cancelBubble = true;
}
if (options.onCloseClick) {
options.onCloseClick(event);
}
hideToast(true);
});
}
if (options.onclick) {
$toastElement.click(function (event) {
options.onclick(event);
hideToast();
});
}
}
function displayToast() {
$toastElement.hide();
$toastElement[options.showMethod](
{duration: options.showDuration, easing: options.showEasing, complete: options.onShown}
);
if (options.timeOut > 0) {
intervalId = setTimeout(hideToast, options.timeOut);
progressBar.maxHideTime = parseFloat(options.timeOut);
progressBar.hideEta = new Date().getTime() + progressBar.maxHideTime;
if (options.progressBar) {
progressBar.intervalId = setInterval(updateProgress, 10);
}
}
}
function setIcon() {
if (map.iconClass) {
$toastElement.addClass(options.toastClass).addClass(iconClass);
}
}
function setSequence() {
if (options.newestOnTop) {
$container.prepend($toastElement);
} else {
$container.append($toastElement);
}
}
function setTitle() {
if (map.title) {
var suffix = map.title;
if (options.escapeHtml) {
suffix = escapeHtml(map.title);
}
$titleElement.append(suffix).addClass(options.titleClass);
$toastElement.append($titleElement);
}
}
function setMessage() {
if (map.message) {
var suffix = map.message;
if (options.escapeHtml) {
suffix = escapeHtml(map.message);
}
$messageElement.append(suffix).addClass(options.messageClass);
$toastElement.append($messageElement);
}
}
function setCloseButton() {
if (options.closeButton) {
$closeElement.addClass(options.closeClass).attr('role', 'button');
$toastElement.prepend($closeElement);
}
}
function setProgressBar() {
if (options.progressBar) {
$progressElement.addClass(options.progressClass);
$toastElement.prepend($progressElement);
}
}
function setRTL() {
if (options.rtl) {
$toastElement.addClass('rtl');
}
}
function shouldExit(options, map) {
if (options.preventDuplicates) {
if (map.message === previousToast) {
return true;
} else {
previousToast = map.message;
}
}
return false;
}
function hideToast(override) {
var method = override && options.closeMethod !== false ? options.closeMethod : options.hideMethod;
var duration = override && options.closeDuration !== false ?
options.closeDuration : options.hideDuration;
var easing = override && options.closeEasing !== false ? options.closeEasing : options.hideEasing;
if ($(':focus', $toastElement).length && !override) {
return;
}
clearTimeout(progressBar.intervalId);
return $toastElement[method]({
duration: duration,
easing: easing,
complete: function () {
removeToast($toastElement);
clearTimeout(intervalId);
if (options.onHidden && response.state !== 'hidden') {
options.onHidden();
}
response.state = 'hidden';
response.endTime = new Date();
publish(response);
}
});
}
function delayedHideToast() {
if (options.timeOut > 0 || options.extendedTimeOut > 0) {
intervalId = setTimeout(hideToast, options.extendedTimeOut);
progressBar.maxHideTime = parseFloat(options.extendedTimeOut);
progressBar.hideEta = new Date().getTime() + progressBar.maxHideTime;
}
}
function stickAround() {
clearTimeout(intervalId);
progressBar.hideEta = 0;
$toastElement.stop(true, true)[options.showMethod](
{duration: options.showDuration, easing: options.showEasing}
);
}
function updateProgress() {
var percentage = ((progressBar.hideEta - (new Date().getTime())) / progressBar.maxHideTime) * 100;
$progressElement.width(percentage + '%');
}
}
function getOptions() {
return $.extend({}, getDefaults(), toastr.options);
}
function removeToast($toastElement) {
if (!$container) { $container = getContainer(); }
if ($toastElement.is(':visible')) {
return;
}
$toastElement.remove();
$toastElement = null;
if ($container.children().length === 0) {
$container.remove();
previousToast = undefined;
}
}
})();
});
}(typeof define === 'function' && define.amd ? define : function (deps, factory) {
if (typeof module !== 'undefined' && module.exports) { //Node
module.exports = factory(require('jquery'));
} else {
window.toastr = factory(window.jQuery);
}
}));
Change your code to be like this:
<a href="#" style="color: rgb(255,0,0,0)" onclick="playclip(); return false;" >xxxxxxxxxxxxx </a>
However, I would reconsider using this type of javascript invokation. Take a look at this "javascript:void(0);" vs "return false" vs "preventDefault()"

Categories

Resources