How to match '/#' in href - javascript

I'm using this code to match if href attribute starts with # and according to that to add class:
$('.navbar-nav a').each(function(index, element) {
if($(element).attr("href").match("^#"))
{
//Add class to inernal links
$(element).addClass("internal");
}
else
{
//Add class to external links
$(element).addClass("external");
}
});
Now I have problem to match if href starts with /#. I tried with '^/#' but it doesn't work.
I'll appreciate any help.
Update
Here is the whole code I'm using:
jQuery.noConflict();
(function( $ ) {
$(function() {
/*********************************************************************************************************/
/* -------------------------------------- Navigation ------------------------------------------ */
/*********************************************************************************************************/
//Add class to inernal and external links
$('.navbar-nav a').each(function(index, element) {
if($(element).attr("href").match(/^\/?#/))
{
//Add class to inernal links
$(element).addClass("internal");
}
else
{
//Add class to external links
$(element).addClass("external");
}
});
var lastId,
topMenu = $(".navbar-nav"),
topMenuHeight = topMenu.outerHeight(),
// All list items without external links
menuItems = topMenu.find("a").not(".external"),
// Anchors corresponding to menu items
scrollItems = menuItems.map(function() {
var item = $($(this).attr("href"));
if (item.length) {
return item;
}
});
// Bind click handler to menu items
// so we can get a fancy scroll animation
menuItems.click(function(e) {
if (!$(this).hasClass("dropdown-toggle")) {
var href = $(this).attr("href"),
offsetTop = href === "#" ? 0 : $(href).offset().top - topMenuHeight + 1;
$('html, body').stop().animate({
scrollTop: offsetTop
}, 1450, 'easeInOutQuart');
e.preventDefault();
}
});
// Bind to scroll
$(window).scroll(function() {
// Get container scroll position
var fromTop = $(this).scrollTop() + topMenuHeight;
// Get id of current scroll item
var cur = scrollItems.map(function() {
if ($(this).offset().top < fromTop)
return this;
});
// Get the id of the current element
cur = cur[cur.length - 1];
var id = cur && cur.length ? cur[0].id : "";
if (lastId !== id) {
lastId = id;
// Set/remove active class
menuItems
.parent().removeClass("active")
.end().filter("[href=#" + id + "]").parent().addClass("active");
}
});
/*********************************************************************************************************/
/* -------------------------------------- Home part - 100% hight ------------------------------------------ */
/*********************************************************************************************************/
jQuery.fn.refresh = function() {
var s = skrollr.get();
if (s) {
s.refresh(this);
}
return this;
};
function fullHeight() {
windowHeight = $(window).height();
$('#home, .tp-banner-container').css('height', windowHeight).refresh();
};
fullHeight();
$(window).resize(function() {
fullHeight();
});
/*********************************************************************************************************/
/* -------------------------------------- H2 big shadow ------------------------------------------ */
/*********************************************************************************************************/
$("h2").each(function () {
var h2 = $(this);
var span = h2.parent().find("span.title-shadow");
span.append(h2.html());
});
/*********************************************************************************************************/
/* -------------------------------------- Back to top ------------------------------------------ */
/*********************************************************************************************************/
$(".logo").click(function() {
$("html, body").animate({ scrollTop: 0 }, "easeInOutQuart");
return false;
});
/*********************************************************************************************************/
/* -------------------------------------- Contact form ------------------------------------------ */
/*********************************************************************************************************/
(function(e) {
function n(e, n) {
this.$form = e;
this.indexes = {};
this.options = t;
for (var r in n) {
if (this.$form.find("#" + r).length && typeof n[r] == "function") {
this.indexes[r] = n[r]
} else {
this.options[r] = n[r]
}
}
this.init()
}
var t = {
_error_class: "error",
_onValidateFail: function() {}
};
n.prototype = {
init: function() {
var e = this;
e.$form.on("submit", function(t) {
e.process();
if (e.hasErrors()) {
e.options._onValidateFail();
t.stopImmediatePropagation();
return false
}
return true
})
},
notEmpty: function(e) {
return e != "" ? true : false
},
isEmail: function(e) {
return /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(e)
},
isUrl: function(e) {
var t = new RegExp("(^(http[s]?:\\/\\/(www\\.)?|ftp:\\/\\/(www\\.)?|(www\\.)?))[\\w-]+(\\.[\\w-]+)+([\\w-.,#?^=%&:/~+#-]*[\\w#?^=%&;/~+#-])?", "gim");
return t.test(e)
},
elClass: "",
setClass: function(e) {
this.elClass = e
},
process: function() {
this._errors = {};
for (var t in this.indexes) {
this.$el = this.$form.find("#" + t);
if (this.$el.length) {
var n = e.proxy(this.indexes[t], this, e.trim(this.$el.val()))();
if (this.elClass) {
this.elClass.toggleClass(this.options._error_class, !n);
this.elClass = ""
} else {
this.$el.toggleClass(this.options._error_class, !n)
}
if (!n) {
this._errors[t] = n
}
}
this.$el = null
}
},
_errors: {},
hasErrors: function() {
return !e.isEmptyObject(this._errors)
}
};
e.fn.isValid = function(t) {
return this.each(function() {
var r = e(this);
if (!e.data(r, "is_valid")) {
e.data(r, "is_valid", new n(r, t))
}
})
}
})(jQuery)
/*********************************************************************************************************/
/* -------------------------------------- Ajax contact form ------------------------------------------ */
/*********************************************************************************************************/
$('#forms').isValid({
'name': function(data) {
this.setClass(this.$el.parent());
return this.notEmpty(data);
},
'email': function(data) {
this.setClass(this.$el.parent());
return this.isEmail(data);
},
'subject': function(data) {
this.setClass(this.$el.parent());
return this.notEmpty(data);
},
'message': function(data) {
this.setClass(this.$el.parent());
return this.notEmpty(data);
}
}).submit(function(e) {
e.preventDefault();
var $this = $(this);
$.ajax({
'url': $(this).attr('action'),
'type': 'POST',
'dataType': 'html',
'data': $(this).serialize()
}).done(function(response) {
$this.find('.notification').show();
$this.find('input[type="text"], input[type="email"], textarea').val('');
});
return false;
});
$('.notification').on('click', function() {
var $this = $(this);
$this.hide();
});
/*********************************************************************************************************/
/* -------------------------------------- Sticky navigation ------------------------------------------ */
/*********************************************************************************************************/
$("#navigation").sticky({
topSpacing: 0,
className: 'sticky',
wrapperClassName: 'main-menu-wrapper'
});
/*********************************************************************************************************/
/* -------------------------------------- Wow Scroll Animate ------------------------------------------ */
/*********************************************************************************************************/
wow = new WOW({
boxClass: 'wow',
animateClass: 'animated',
offset: 100,
movile: true
});
/*********************************************************************************************************/
/* -------------------------------------- Skrollr and Wow init ------------------------------------------ */
/*********************************************************************************************************/
if (!/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
//Skrollr
var s = skrollr.init({
edgeStrategy: 'set',
forceHeight: true,
smoothScrolling: true,
easing: {
wtf: Math.random,
inverted: function(p) {
return 1 - p;
}
}
});
//Wow init
wow.init();
}
/*********************************************************************************************************/
/* -------------------------------------- Charts, Skils ------------------------------------------ */
/*********************************************************************************************************/
$('.chart').waypoint(function() {
$(this).easyPieChart({
animate: 1000,
size: 200,
lineWidth: 5,
trackColor: "#fff",
barColor:"#de3926",
scaleColor: false,
size: 200,
onStep: function(from, to, percent) {
jQuery(this.el).find('.percent').text(Math.round(percent));
}
});
}, {
triggerOnce: true,
offset: 'bottom-in-view'
});
$(document).ready(function() {
/*********************************************************************************************************/
/* -------------------------------------- Ajax our team ------------------------------------------ */
/*********************************************************************************************************/
$('.ajax-popup-team').magnificPopup({
type: 'ajax',
showCloseBtn: true,
modal: true,
closeOnContentClick: false,
overflowY: 'scroll'
});
/*********************************************************************************************************/
/* -------------------------------------- Ajax portfolio page ------------------------------------------ */
/*********************************************************************************************************/
$('.ajax-popup-portfolio').magnificPopup({
type: 'ajax',
showCloseBtn: true,
modal: true,
closeOnContentClick: false,
overflowY: 'scroll',
gallery: {
enabled: true,
arrowMarkup: '<button title="%title%" type="button" class="portfolio mfp-arrow mfp-arrow-%dir%"></button>'
}
});
/*********************************************************************************************************/
/* -------------------------------------- Portfolio gallery ------------------------------------------ */
/*********************************************************************************************************/
$('.gallery-item-content').each(function() { // the containers for all your galleries
$(this).magnificPopup({
delegate: '.gallery-item', // the selector for gallery item
type: 'image',
gallery: {
enabled: true
}
});
});
/*********************************************************************************************************/
/* -------------------------------------- Video ------------------------------------------ */
/*********************************************************************************************************/
$('.popup-youtube, .popup-vimeo, .popup-gmaps').magnificPopup({
disableOn: 700,
type: 'iframe',
mainClass: 'mfp-fade',
removalDelay: 160,
preloader: true,
fixedContentPos: true
});
/*********************************************************************************************************/
/* -------------------------------------- Owl carousel ------------------------------------------ */
/*********************************************************************************************************/
$("#carousel-our-testimonials").owlCarousel({
autoPlay: 3000,
stopOnHover: true,
navigation: false,
paginationSpeed: 1000,
goToFirstSpeed: 2000,
singleItem: true,
autoHeight: true,
transitionStyle: "fade"
});
$("#carousel-our-clients").owlCarousel({
autoPlay: 10000,
stopOnHover: true,
navigation: true,
paginationSpeed: 1000,
goToFirstSpeed: 3500,
singleItem: false,
autoHeight: true,
transitionStyle: "fade",
navigationText: [
"<i class='fa fa-angle-left'></i>",
"<i class='fa fa-angle-right'></i>"
]
});
$("#blog-single").owlCarousel({
navigation: true, // Show next and prev buttons
pagination: false,
slideSpeed: 300,
paginationSpeed: 400,
navigationText: [
"<i class='fa fa-chevron-left'></i>",
"<i class='fa fa-chevron-right'></i>"
],
singleItem: true
});
/*********************************************************************************************************/
/* -------------------------------------- Dropdown Menu Fade ------------------------------------------ */
/*********************************************************************************************************/
$(".dropdown").hover(
function() {
$('.dropdown-menu', this).fadeIn(275);
$(this).addClass("open");
},
function() {
$('.dropdown-menu', this).fadeOut(275);
$(this).removeClass("open");
});
/*********************************************************************************************************/
/* -------------------------------------- Placeholder fix for IE ------------------------------------------ */
/*********************************************************************************************************/
(function($) {
if (!Modernizr.csstransforms3d) {
$('[placeholder]').focus(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur().parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
}
})
});
/*********************************************************************************************************/
/* -------------------------------------- Count ------------------------------------------ */
/*********************************************************************************************************/
$('#statistic').waypoint(function() {
$('.timer').countTo();
}, {
triggerOnce: true,
offset: 'bottom-in-view'
});
/*********************************************************************************************************/
/* -------------------------------------- Show and hide color-switcher ------------------------------------------ */
/*********************************************************************************************************/
$(".color-switcher .switcher-button").click(function(){
$( ".color-switcher" ).toggleClass("show-color-switcher", "hide-color-switcher", 800);
});
/*********************************************************************************************************/
/* -------------------------------------- Color Skins ------------------------------------------ */
/*********************************************************************************************************/
$('a.color').click(function(){
var title = $(this).attr('title');
$('#style-colors').attr('href', 'css/color-schemes/' + title + '.css');
return false;
});
/*********************************************************************************************************/
/* -------------------------------------- Loader ------------------------------------------ */
/*********************************************************************************************************/
$(window).load(function() {
$("#loader").delay(450).fadeOut(800);
$(".preload-gif").addClass('fadeOut');
});
});
})(jQuery);

If you want to match both, you could change the Regular expression to:
/^\/?#/
The question mark is a 0 or 1 quantifier, that will match whether there is 1 or no / at the beginning.
Check it out here: http://www.regexr.com/3ajoo
Also i used your code and tried to find the error you have: I think there is no error from the answer of this question. Your error must be something else. Try and wrap the function in $(document).ready() to make sure the DOM is loaded before searching the elements.
$(document).ready(function() {
$('.navbar-nav a').each(function(index, element) {
if ($(element).attr("href").match(/^\/?#/)) {
//Add class to inernal links
$(element).addClass("internal");
} else {
//Add class to external links
$(element).addClass("external");
}
});
});
.external {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="navbar-nav">
Link
</li>
<li class="navbar-nav">
Link
</li>
<li class="navbar-nav">
Link
</li>
<li class="navbar-nav">
Link
</li>
<li class="navbar-nav">
Link
</li>
</ul>

Use / as delimiter.
if($(element).attr("href").match(/^\/#/))

Related

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

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?

How can I use javascript to make it so the user can only trigger the hover event once the Lottie animation has played in full?

How can I make it so the user is only able to trigger the mouse hover & mouse left events, once the Lottie animation has initially played in full.
Currently the user is able to cause the hover event when the animation is mid-playing, something I don't want to be able to happen.
Thanks
var anim4;
var anim5 = document.getElementById('lottie5')
var animation5 = {
container: anim5,
renderer: 'svg',
loop: true,
autoplay: false, /*MAKE SURE THIS IS FALSE*/
rendererSettings: {
progressiveLoad: false},
path: 'https://assets1.lottiefiles.com/packages/lf20_H2PpYV.json',
name: 'myAnimation',
};
anim4 = lottie.loadAnimation(animation5);
// SCROLLING DOWN
var waypoint5 = new Waypoint({
element: document.getElementById('lottie5'),
handler: function(direction) {
if (direction === 'down') {
anim4.playSegments([[130,447],[358,447]], true);
this.destroy()
}
},
offset: '50%'
})
anim5.addEventListener("mouseenter", myScript1);
anim5.addEventListener("mouseleave", myScript2);
function myScript1(){
anim4.goToAndStop(500, true);
}
function myScript2(){
anim4.playSegments([358,447],true);
};
var anim4;
var anim5 = document.getElementById('lottie5')
var animation5 = {
container: anim5,
renderer: 'svg',
loop: false,
autoplay: true, /*MAKE SURE THIS IS FALSE*/
rendererSettings: {
progressiveLoad: false},
path: 'https://assets1.lottiefiles.com/packages/lf20_H2PpYV.json',
name: 'myAnimation',
};
anim4 = lottie.loadAnimation(animation5);
// SCROLLING DOWN
var waypoint5 = new Waypoint({
element: document.getElementById('lottie5'),
handler: function(direction) {
if (direction === 'down') {
anim4.playSegments([[130,447],[358,447]], true);
this.destroy()
}
},
offset: '50%'
})
anim4.addEventListener("complete", function(){
console.log('Animation completed!!');
anim5.addEventListener("mouseenter", myScript1);
anim5.addEventListener("mouseleave", myScript2);
});
function myScript1(){
anim4.goToAndStop(500, true);
}
function myScript2(){
anim4.playSegments([358,447],true);
};
Figure it out in case anyone is interested.
This might not be the most efficient way, but worked for me!
anim4.addEventListener('complete', function(e) {
console.log('Animation completed');
});
anim4.addEventListener('complete', function(e) {
var elem = document.getElementById('lottie5');
elem.addEventListener('mouseover', mouseElem)
elem.addEventListener('mouseleave', mouseElem2)
function mouseElem() {
anim4.goToAndStop(150, true);
}
function mouseElem2() {
anim4.goToAndStop(30, true);
}

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()"

ReferenceError: jQuery is not defined in main.js file

I am running into this error all of a sudden. I haven't anything with the Javascript or jQuery code so not sure why I'm getting this error all of a sudden.
This is the error I'm getting when trying to run my code:
Debugger listening on [::]:15454
/home/ubuntu/workspace/assets/js/main.js:232
}(jQuery);
^
ReferenceError: jQuery is not defined
Code:
(function($) {
skel.breakpoints({
xxlarge: '(max-width: 1920px)',
xlarge: '(max-width: 1680px)',
large: '(max-width: 1280px)',
medium: '(max-width: 1000px)',
small: '(max-width: 736px)',
xsmall: '(max-width: 480px)',
});
$(function() {
var $window = $(window),
$body = $('body'),
$header = $('#header'),
$all = $body.add($header);
// Disable animations/transitions until the page has loaded.
$body.addClass('is-loading');
$window.on('load', function() {
window.setTimeout(function() {
$body.removeClass('is-loading');
}, 0);
});
// Touch mode.
skel.on('change', function() {
if (skel.vars.mobile || skel.breakpoint('small').active)
$body.addClass('is-touch');
else
$body.removeClass('is-touch');
});
// Fix: Placeholder polyfill.
$('form').placeholder();
// Fix: IE flexbox fix.
if (skel.vars.IEVersion <= 11
&& skel.vars.IEVersion >= 10) {
var $main = $('.main.fullscreen'),
IEResizeTimeout;
$window
.on('resize.ie-flexbox-fix', function() {
clearTimeout(IEResizeTimeout);
IEResizeTimeout = setTimeout(function() {
var wh = $window.height();
$main.each(function() {
var $this = $(this);
$this.css('height', '');
if ($this.height() <= wh)
$this.css('height', (wh - 50) + 'px');
});
});
})
.triggerHandler('resize.ie-flexbox-fix');
}
// Prioritize "important" elements on small.
skel.on('+small -small', function() {
$.prioritize(
'.important\\28 small\\29',
skel.breakpoint('small').active
);
});
// Gallery.
$window.on('load', function() {
var $gallery = $('.gallery');
$gallery.poptrox({
baseZIndex: 10001,
useBodyOverflow: false,
usePopupEasyClose: false,
overlayColor: '#1f2328',
overlayOpacity: 0.65,
usePopupDefaultStyling: false,
usePopupCaption: true,
popupLoaderText: '',
windowMargin: 50,
usePopupNav: true
});
// Hack: Adjust margins when 'small' activates.
skel
.on('-small', function() {
$gallery.each(function() {
$(this)[0]._poptrox.windowMargin = 50;
});
})
.on('+small', function() {
$gallery.each(function() {
$(this)[0]._poptrox.windowMargin = 5;
});
});
});
// Section transitions.
if (skel.canUse('transition')) {
var on = function() {
// Galleries.
$('.gallery')
.scrollex({
top: '30vh',
bottom: '30vh',
delay: 50,
initialize: function() { $(this).addClass('inactive'); },
terminate: function() { $(this).removeClass('inactive'); },
enter: function() { $(this).removeClass('inactive'); },
leave: function() { $(this).addClass('inactive'); }
});
// Generic sections.
$('.main.style1')
.scrollex({
mode: 'middle',
delay: 100,
initialize: function() { $(this).addClass('inactive'); },
terminate: function() { $(this).removeClass('inactive'); },
enter: function() { $(this).removeClass('inactive'); },
leave: function() { $(this).addClass('inactive'); }
});
$('.main.style2')
.scrollex({
mode: 'middle',
delay: 100,
initialize: function() { $(this).addClass('inactive'); },
terminate: function() { $(this).removeClass('inactive'); },
enter: function() { $(this).removeClass('inactive'); },
leave: function() { $(this).addClass('inactive'); }
});
// Contact.
$('#contact')
.scrollex({
top: '50%',
delay: 50,
initialize: function() { $(this).addClass('inactive'); },
terminate: function() { $(this).removeClass('inactive'); },
enter: function() { $(this).removeClass('inactive'); },
leave: function() { $(this).addClass('inactive'); }
});
};
var off = function() {
// Galleries.
$('.gallery')
.unscrollex();
// Generic sections.
$('.main.style1')
.unscrollex();
$('.main.style2')
.unscrollex();
// Contact.
$('#contact')
.unscrollex();
};
skel.on('change', function() {
if (skel.breakpoint('small').active)
(off)();
else
(on)();
});
}
// Events.
var resizeTimeout, resizeScrollTimeout;
$window
.resize(function() {
// Disable animations/transitions.
$body.addClass('is-resizing');
window.clearTimeout(resizeTimeout);
resizeTimeout = window.setTimeout(function() {
// Update scrolly links.
$('a[href^="#"]').scrolly({
speed: 1500,
offset: $header.outerHeight() - 1
});
// Re-enable animations/transitions.
window.setTimeout(function() {
$body.removeClass('is-resizing');
$window.trigger('scroll');
}, 0);
}, 100);
})
.load(function() {
$window.trigger('resize');
});
});
})(jQuery);
Edit:
here is the code from bottom of index.html
</footer>
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.poptrox.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/skel.min.js"></script>
<script src="assets/js/util.js"></script>
<!--[if lte IE 8]><script src="assets/js/ie/respond.min.js"></script><![endif]-->
<script src="assets/js/main.js"></script>
</body>
</html>
here is the code from bottom of index.html
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.poptrox.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/skel.min.js"></script>
<script src="assets/js/util.js"></script>
<!--[if lte IE 8]><script src="assets/js/ie/respond.min.js"></script><![endif]-->
<script src="assets/js/main.js"></script>

using two fancybox methods together

So I have the code for fancybox:
$(".fancybox").fancybox({
beforeShow: function () {
var alt = this.element.find('img').attr('alt');
this.inner.find('img').attr('alt', alt);
this.title = alt;
}
});
and
$(document).ready(function () {
$(".fancybox").fancybox({
helpers: {
overlay: {
locked: false
}
}
});
});
when I try to use them both I get a syntax error:
$(document).ready(function () {
$(".fancybox").fancybox({
helpers: {
overlay: {
locked: false
}
}
beforeShow: function () {
var alt = this.element.find('img').attr('alt');
this.inner.find('img').attr('alt', alt);
this.title = alt;
}
});
});
and when I use them separately neither of the fancybox functions work.
<script>
$(document).ready(function () {
$(".fancybox").fancybox({
helpers: {
overlay: {
locked: false
}
}
});
});
</script>
<script>
$(".fancybox").fancybox({
beforeShow: function () {
var alt = this.element.find('img').attr('alt');
this.inner.find('img').attr('alt', alt);
this.title = alt;
}
});
</script>
How can I use them both?
You're missing a comma in your object properties on line 7 between helpers: { ... } and beforeShow: function() { ... }
$(document).ready(function () {
$(".fancybox").fancybox({
helpers: {
overlay: {
locked: false
}
}, // <-- this comma right here is missing in your code
beforeShow: function () {
var alt = this.element.find('img').attr('alt');
this.inner.find('img').attr('alt', alt);
this.title = alt;
}
});
});

Categories

Resources