i am having trouble with a script.
It works fine the first time, but when I go to another page on the site and then back to the front page the site does not load fully. I need to press refresh for it to work properly.
Does anyone have an idea why that might be?
http://wordpress.juliebrass.com/
I tried to put it inside a window.addEventListener('load', function () {
But it did nothing
This is the code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// var figure = $(".video");
// var vid = figure.find("video");
// [].forEach.call(figure, function (item,index) {
// item.addEventListener('mouseover', hoverVideo.bind(item,index), false);
// item.addEventListener('mouseout', hideVideo.bind(item,index), false);
// });
// function hoverVideo(index, e) {
// video.play();
// }
// function hideVideo(index, e) {
// video.pause();
// }
(function($) {
window.addEventListener('load', function () {
function flickity_handle_wheel_event(e, flickity_instance, flickity_is_animating) {
// do not trigger a slide change if another is being animated
if (!flickity_is_animating) {
// pick the larger of the two delta magnitudes (x or y) to determine nav direction
var direction = (Math.abs(e.deltaX) > Math.abs(e.deltaY)) ? e.deltaX : e.deltaY;
console.log("wheel scroll ", e.deltaX, e.deltaY, direction);
if (direction > 0) {
// next slide
flickity_instance.next();
} else {
// prev slide
flickity_instance.previous();
}
}
}
var carousel = document.querySelector(".carousel");
var flickity_2 = new Flickity(".carousel", {wrapAround: true, freescroll:true});
var flickity_2_is_animating = false;
flickity_2.on("settle", function(index) {
console.log("Slide settle " + index);
flickity_2_is_animating = false;
});
flickity_2.on("select", function(index) {
console.log("Slide selected " + index);
flickity_2_is_animating = true;
});
// detect mousewheel event within carousel element
carousel.onwheel = function(e) {
flickity_handle_wheel_event(e, flickity_2, flickity_2_is_animating);
}
// video
var carousel = document.querySelector('.carousel');
var flkty = new Flickity( carousel );
function onLoadeddata( event ) {
var cell = flkty.getParentCell( event.target );
flkty.cellSizeChange( cell && cell.element );
}
var videos = carousel.querySelectorAll('video');
for ( var i=0, len = videos.length; i < len; i++ ) {
var video = videos[i];
// resume autoplay for WebKit
video.play();
}
var figure = $(".video");
var vid = figure.find("video");
$(".video > video").mouseenter( hoverVideo );
$(".video > video").mouseleave( unhoverVideo );
function hoverVideo(e) {
$(this).get(0).play();
}
function unhoverVideo() {
$(this).get(0).pause();
$(this).get(0).currentTime = 0;
//$(this).hide();
}
$(".feuer").mouseout(function() {
$("feuer").get(0).currentTime = 0;
});
$(".herz").mouseout(function() {
$("herz").get(0).currentTime = 0;
});
$(".stern").mouseout(function() {
$("stern").get(0).currentTime = 0;
$(".all").mouseout(function() {
$("all").get(0).currentTime = 0;
});
// your code
});
//pause on hover
})(jQuery);
</script>
Related
I have a javascript function for a slider in the JS file of my site. When we are in a page where the slider is not called or there is no trigger element, it displays an error in the console "Uncaught TypeError: Cannot read properties of null (reading 'querySelector') ", This error is not displayed when the slider is in the page.
I would like to know how to avoid this error, and how to prevent this function from loading in pages where this slider is not present?
function slider(set) {
const sliderContainer = document.querySelector(set.name),
slider = sliderContainer.querySelector('.slider'),
sliderItem = slider.querySelectorAll('.slider__item'),
sliderArrows = sliderContainer.querySelectorAll('.arrows__item');
let dotsCreate,
dotsClass,
dotsFunk,
numberSlider,
numberSliderWork,
sliderExecutionLine,
sliderExecutionLineWork;
// calculate the maximum width of all slides
function forSliderItem(t) {
t = 0;
for(let i = 0; i < sliderItem.length - 1; i++) {
t += sliderItem[i].clientWidth;
}
return t;
}
let maxWidth = forSliderItem(sliderItem), // maximum width of all slides
slidWidth = 0, // main variable for calculating the movement of the slider
count = 0; // counter
//===== flip left
sliderArrows[0].addEventListener('click', function() {
if(count !== 0) {
count--;
slidWidth -= sliderItem[count].clientWidth;
slider.style.transform = `translateX(-${slidWidth}px)`;
} else {
count = sliderItem.length - 1;
slidWidth = maxWidth;
slider.style.transform = `translateX(-${slidWidth}px)`;
}
if(set.dots) {
dotsFunk();
}
if(set.numberSlid) {
numberSliderWork(count);
}
if(set.line) {
sliderExecutionLineWork(count);
}
});
//===== flip right
sliderArrows[1].addEventListener('click', function() {
if(count < sliderItem.length - 1) {
count++;
slidWidth += sliderItem[count].clientWidth;
slider.style.transform = `translateX(-${slidWidth}px)`;
} else {
count = 0;
slidWidth = 0;
slider.style.transform = `translateX(-${slidWidth}px)`;
}
if(set.dots) {
dotsFunk();
}
if(set.numberSlid) {
numberSliderWork(count);
}
if(set.line) {
sliderExecutionLineWork(count);
}
});
//===== dots
if(set.dots) {
dotsCreate = function() {
const dotContainer = document.createElement('div'); // create dots container
dotContainer.classList.add('dots');
// create the required number of dots and insert a container into the dots
sliderItem.forEach(() => {
let dotsItem = document.createElement('span');
dotContainer.append(dotsItem);
});
sliderContainer.append(dotContainer);
};
dotsCreate();
// add the class to the desired dots, and remove from the rest
dotsClass = function(remove, add) {
remove.classList.remove('dots_active');
add.classList.add('dots_active');
};
// move slides by clicking on the dot
dotsFunk = function() {
const dotsWork = sliderContainer.querySelectorAll('.dots span'); // we get dots
dotsWork.forEach((item, i) => {
dotsClass(dotsWork[i], dotsWork[count]);
item.addEventListener('click', function() {
count = i;
// multiply the slide size by the number of the dots, and get the number by which you need to move the slider
slidWidth = sliderItem[0].clientWidth * i;
slider.style.transform = `translateX(-${slidWidth}px)`;
for(let j = 0; j < dotsWork.length; j++) {
dotsClass(dotsWork[j], dotsWork[count]);
}
if(set.dots && set.numberSlid) {
numberSliderWork(count);
}
if(set.line) {
sliderExecutionLineWork(count);
}
});
});
};
dotsFunk();
}
//===== count slider
if(set.numberSlid) {
numberSlider = function(item) {
const countContainer = document.createElement('div'),
sliderNumber = document.createElement('span'),
slash = document.createElement('span'),
allSliderNumber = document.createElement('span');
casClient = document.createElement('p');
sliderNumber.innerHTML = item + 1;
casClient.innerHTML = 'Cas client N°';
slash.innerHTML = '/';
allSliderNumber.innerHTML = sliderItem.length;
countContainer.classList.add('count-slides');
countContainer.append(casClient, sliderNumber, slash, allSliderNumber);
sliderContainer.append(countContainer);
};
numberSlider(0);
numberSliderWork = function(item) {
const sliderNumberNow = sliderContainer.querySelector('.count-slides span');
sliderNumberNow.innerHTML = item + 1;
if(set.line) {
sliderExecutionLineWork(item);
}
};
}
}
slider({
name: ".video_users",
numberSlid: true
});
<!DOCTYPE html>
<html lang="fr">
<head>
<title>Example of a page without the slider</title>
</head>
<body class="error_404">
<h1>Example of a page without the slider</h1>
<script src="media/js/faveod.js" async></script>
</body>
</html>
Just return if the element isn't present if you don't want it to show an error.
const sliderContainer = document.querySelector(set.name);
if (!sliderContainer) return;
const slider = sliderContainer.querySelector('.slider'),
sliderItem = slider.querySelectorAll('.slider__item'),
sliderArrows = sliderContainer.querySelectorAll('.arrows__item');
If you want it to only execute on certain pages, then just add:
if (location.pathname !== '/the/page/with/slider') return;
to the beginning of the function
/*
* SCROLLBAR 2 COLUMN / SOLUTIONS
*/
var ssb = {
aConts : [],
mouseY : 0,
N : 0,
asd : 0, /*active scrollbar element*/
sc : 0,
sp : 0,
to : 0,
// constructor
scrollbar : function (cont_id) {
var cont = document.getElementById(cont_id);
// perform initialization
if (! ssb.init()) return false;
var cont_clone = cont.cloneNode(false);
cont_clone.style.overflow = "hidden";
cont.parentNode.appendChild(cont_clone);
cont_clone.appendChild(cont);
cont.style.position = 'absolute';
cont.style.left = cont.style.top = '0px';
cont.style.width = cont.style.height = '100%';
// adding new container into array
ssb.aConts[ssb.N++] = cont;
cont.sg = false;
//creating scrollbar child elements
cont.st = this.create_div('ssb_st', cont, cont_clone);
cont.sb = this.create_div('ssb_sb', cont, cont_clone);
cont.su = this.create_div('ssb_up', cont, cont_clone);
cont.sd = this.create_div('ssb_down', cont, cont_clone);
// on mouse down processing
cont.sb.onmousedown = function (e) {
if (! this.cont.sg) {
if (! e) e = window.event;
ssb.asd = this.cont;
this.cont.yZ = e.screenY;
this.cont.sZ = cont.scrollTop;
this.cont.sg = true;
// new class name
this.className = 'ssb_sb ssb_sb_down';
}
return false;
}
// on mouse down on free track area - move our scroll element too
cont.st.onmousedown = function (e) {
if (! e) e = window.event;
ssb.asd = this.cont;
ssb.mouseY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
for (var o = this.cont, y = 0; o != null; o = o.offsetParent) y += o.offsetTop;
this.cont.scrollTop = (ssb.mouseY - y - (this.cont.ratio * this.cont.offsetHeight / 2) - this.cont.sw) / this.cont.ratio;
this.cont.sb.onmousedown(e);
}
// onmousedown events
cont.su.onmousedown = cont.su.ondblclick = function (e) { ssb.mousedown(this, -1); return false; }
cont.sd.onmousedown = cont.sd.ondblclick = function (e) { ssb.mousedown(this, 1); return false; }
//onmouseout events
cont.su.onmouseout = cont.su.onmouseup = ssb.clear;
cont.sd.onmouseout = cont.sd.onmouseup = ssb.clear;
// on mouse over - apply custom class name: ssb_sb_over
cont.sb.onmouseover = function (e) {
if (! this.cont.sg) this.className = 'ssb_sb ssb_sb_over';
return false;
}
// on mouse out - revert back our usual class name 'ssb_sb'
cont.sb.onmouseout = function (e) {
if (! this.cont.sg) this.className = 'ssb_sb';
return false;
}
// onscroll - change positions of scroll element
cont.ssb_onscroll = function () {
this.ratio = (this.offsetHeight - 2 * this.sw) / this.scrollHeight;
this.sb.style.top = Math.floor(this.sw + this.scrollTop * this.ratio) + 'px';
}
// scrollbar width
cont.sw = 16;
// start scrolling
cont.ssb_onscroll();
ssb.refresh();
// binding own onscroll event
cont.onscroll = cont.ssb_onscroll;
return cont;
},
// initialization
init : function () {
if (window.oper || (! window.addEventListener && ! window.attachEvent)) { return false; }
// temp inner function for event registration
function addEvent (o, e, f) {
if (window.addEventListener) { o.addEventListener(e, f, false); ssb.w3c = true; return true; }
if (window.attachEvent) return o.attachEvent('on' + e, f);
return false;
}
// binding events
addEvent(window.document, 'mousemove', ssb.onmousemove);
addEvent(window.document, 'mouseup', ssb.onmouseup);
addEvent(window, 'resize', ssb.refresh);
return true;
},
// create and append div finc
create_div : function(c, cont, cont_clone) {
var o = document.createElement('div');
o.cont = cont;
o.className = c;
cont_clone.appendChild(o);
return o;
},
// do clear of controls
clear : function () {
clearTimeout(ssb.to);
ssb.sc = 0;
return false;
},
// refresh scrollbar
refresh : function () {
for (var i = 0, N = ssb.N; i < N; i++) {
var o = ssb.aConts[i];
o.ssb_onscroll();
o.sb.style.width = o.st.style.width = o.su.style.width = o.su.style.height = o.sd.style.width = o.sd.style.height = o.sw + 'px';
o.sb.style.height = Math.ceil(Math.max(o.sw * .5, o.ratio * o.offsetHeight) + 1) + 'px';
}
},
// arrow scrolling
arrow_scroll : function () {
if (ssb.sc != 0) {
ssb.asd.scrollTop += 6 * ssb.sc / ssb.asd.ratio;
ssb.to = setTimeout(ssb.arrow_scroll, ssb.sp);
ssb.sp = 32;
}
},
/* event binded functions : */
// scroll on mouse down
mousedown : function (o, s) {
if (ssb.sc == 0) {
// new class name
o.cont.sb.className = 'ssb_sb ssb_sb_down';
ssb.asd = o.cont;
ssb.sc = s;
ssb.sp = 100;
ssb.arrow_scroll();
}
},
// on mouseMove binded event
onmousemove : function(e) {
if (! e) e = window.event;
// get vertical mouse position
ssb.mouseY = e.screenY;
if (ssb.asd.sg) ssb.asd.scrollTop = ssb.asd.sZ + (ssb.mouseY - ssb.asd.yZ) / ssb.asd.ratio;
},
// on mouseUp binded event
onmouseup : function (e) {
if (! e) e = window.event;
var tg = (e.target) ? e.target : e.srcElement;
if (ssb.asd && document.releaseCapture) ssb.asd.releaseCapture();
// new class name
if (ssb.asd) ssb.asd.sb.className = (tg.className.indexOf('scrollbar') > 0) ? 'ssb_sb ssb_sb_over' : 'ssb_sb';
document.onselectstart = '';
ssb.clear();
ssb.asd.sg = false;
}
}
window.onload = function() {
ssb.scrollbar('container'); // scrollbar initialization
}
I was coding a simple audio player with plain javascript. when i test it in my laptop work fine but when i access it from phone isnt work.
my source code:
window.addEventListener("resize", resizeAud, false);
window.addEventListener("DOMContentLoaded", function() {
audEl = document.querySelector("#audioElement"); // Audio Element
if (audEl) {
audEl.removeAttribute("controls");
audEl.load();
// Resize audio player on load window //
resizeAud();
document.querySelector("#tc3").addEventListener("click", function() {
setTimeout(resizeAud, 10);
});
/*############################################################################################*\
|*# #*|
|*# # ADDeVENTLISTENER # #*|
|*# #*|
|*############################################################################################*/
// Toggle sound details //
document.querySelector(".show-snd-d").addEventListener("click", function(e) {
e.stopPropagation();
document.querySelector(".snd-detail").classList.toggle("active-snd-detail");
});
// Hide sound detail on click outside //
document.querySelector("html").addEventListener("click", function() {
document.querySelector(".snd-detail").classList.remove("active-snd-detail");
});
// Rest show sound detail on click inside //
document.querySelector(".snd-detail").addEventListener("click", function(e) {
e.preventDefault();
e.stopPropagation();
});
// Toggle sound playlist for mobile screen < 768px //
document.querySelector(".show-list").addEventListener("click", function() {
document.querySelector("#snd-list").classList.toggle("active-snd-list");
});
// is mouse down or up on ".git" element//
var isDown = false; // default mouse is up
document.addEventListener("mousedown", function(e) {
if (e.target.classList.contains("progressbar") || e.target.classList.contains("heared")) {isDown="progressbar"}
else if (e.target.classList.contains("snd-volume")
|| e.target.classList.contains("volume-pro")
|| e.target.classList.contains("pro")) {isDown="volPro"}
else {isDown=false}
});
document.addEventListener("mouseup", function() {
isDown = false; // is mouseup
});
// Change progressbar width on click //
document.querySelector(".proAna").addEventListener("click", (e) => { reportPro(e); });
// Change progressbar width on mousedown and move at the same time //
document.addEventListener("mousemove", (e) => { (isDown=="progressbar")?reportPro(e):false; });
// Change progrssbar on timeupdate
audEl.addEventListener("timeupdate", function() {
setInterval(function() {
reportPro("timeupdate");
},10);
})
// init play to 0 on audio ended
audEl.addEventListener("ended", () => {togglePlay("manual");});
// Change volumebar height on click //
document.querySelector(".volume-pro").addEventListener("click", (e) => { reportVol(e); });
// Change volumebar height on mousedown and move at the same time //
document.addEventListener("mousemove", (e) => { (isDown=="volPro")?reportVol(e):false; });
// Toggle mute on click on mute button
document.querySelector(".mute").addEventListener("click", () => { reportVol("mute"); })
// backward audio //
document.querySelector(".backward").addEventListener("click", () => { wardAud("backward"); });
// Toggle play audio //
document.querySelector(".play-snd").addEventListener("click", togglePlay);
// forward audio //
document.querySelector(".forward").addEventListener("click", () => { wardAud("forward"); });
}
}, false);
/*############################################################################################*\
|*# #*|
|*# # FUNCTIONS # #*|
|*# #*|
|*############################################################################################*/
var audEl = document.querySelector("#audioElement");
// Report progressbar width one click,timeupdate or mouse (down + move) //
if (audEl) {
function reportPro(event) {
var newWid;
var duration = !isNaN(audEl.duration)?audEl.duration:0;
var prWidth = document.querySelector(".progressbar").offsetWidth;
if (event!="timeupdate") {
event.preventDefault();
var bounds = document.querySelector(".progressbar").getBoundingClientRect();
var x = event.clientX - bounds.left;
if (x>prWidth) {newWid=prWidth}
else if(x<=0){newWid=0}
else {newWid=(x)}
audEl.currentTime = (newWid/prWidth)*duration;
}
var current = audEl.currentTime;
newWid = (current/duration)*100;
document.querySelector(".heared").style.width = newWid+"%";
document.querySelector(".sure").innerHTML = secondsToHms(current)+" / "+secondsToHms(duration);
}
//Convert seconds to h-m-s
function secondsToHms(d) {
d = Number(d);
var h = Math.floor(d / 3600);
var m = Math.floor(d % 3600 / 60);
var s = Math.floor(d % 3600 % 60);
return ((h>0)?h+":":"")
+((h>0)?((m<10)?"0"+m:m):((m>0)?m:"0"))+":"
+((s<10)?"0"+s:s);
}
// Change volumebar height function //
function reportVol(event) {
var volHeight = document.querySelector(".volume-pro").offsetHeight;
if (event=="mute") {
if (audEl.muted) {
audEl.muted = false;
bottom = audEl.volume*100;
}else{
audEl.muted = true;
bottom = 0;
}
var muteIcon = document.querySelector(".mute").childNodes[0];
muteIcon.classList.contains("fa-volume-up")? muteIcon.rempClass("fa-volume-up","fa-volume-mute")
: muteIcon.rempClass("fa-volume-mute","fa-volume-up");
}else{
event.preventDefault();
var bounds = document.querySelector(".volume-pro").getBoundingClientRect();
var y = bounds.bottom - event.clientY;
if ((y)>volHeight) {bottom=volHeight}
else if((y)<=0){bottom=0}
else {bottom=(y)}
bottom = (bottom/volHeight)*100;
audEl.volume = bottom/100;
}
document.querySelector(".pro").style.height = bottom+"%";
}
// Toggle Play Function //
function togglePlay(type="") {
var playBut = document.querySelector(".play-snd");
var playIcon = playBut.childNodes[0]; // icon element
if (type=="manual") {
audEl.currentTime = 0;
audEl.pause();
}else if(type=="ward"){
audEl.play();
}else{
(audEl.paused)?audEl.play():audEl.pause(); // Toggle play audio
}
// toggle play pause icon
(!audEl.paused)? playIcon.rempClass("fa-play","fa-pause")+playBut.classList.add("active-play-snd")
: playIcon.rempClass("fa-pause","fa-play")+playBut.classList.remove("active-play-snd");
}
// backward and award function //
function wardAud(wardType,elId="") {
var sndList = document.getElementsByClassName("snd-item");
var newActive;
for (var i=0; i < sndList.length; i++) {
if (sndList[i].classList.contains("active-snd")) { var activeItem = i; }
}
if (wardType=="backward") {
newActive = (activeItem!=0)? sndList[activeItem-1]:false;
}else if (wardType=="forward"){
newActive = (activeItem!=(sndList.length-1))? sndList[activeItem+1]:false;
}else if (wardType=="specific") {
newActive = sndList[elId];
console.log(elId);
}
if(newActive!=false && newActive!=sndList[activeItem]){
var newSrc= newActive.getAttribute("data-ref");
togglePlay();
document.getElementById("audSrc").setAttribute("src", newSrc);
audEl.load();
togglePlay("ward");
newActive.classList.add("active-snd");
sndList[activeItem].classList.remove("active-snd");
newActive.parentNode.scrollTop = newActive.offsetHeight*(((wardType=="backward")?activeItem-1
:(wardType=="forward"?activeItem+1:elId))-2);
newActive.children[0].children[0].rempClass("fa-play","fa-pause");
sndList[activeItem].children[0].children[0].rempClass("fa-pause","fa-play");
newActive.children[1].children[1].children[0].rempClass("fa-folder","fa-folder-open");
sndList[activeItem].children[1].children[1].children[0].rempClass("fa-folder-open","fa-folder");
}
}
// Resize player element function //
function resizeAud() {
var playerElment = document.getElementById("player").getBoundingClientRect().width;
var audElment = document.getElementById("audio").getBoundingClientRect().width;
if (document.body.getBoundingClientRect().width<=767){
document.getElementById("snd-list").style.width = "100%";
document.querySelector(".show-list").style.display = 'block';
document.getElementById("snd-list").classList.add("mobile-snd-list");
}else{
document.getElementById("snd-list").style.width = (playerElment - audElment)+"px";
document.querySelector(".show-list").style.display = 'none';
document.getElementById("snd-list").classList.remove("mobile-snd-list");
}
}
// remplace class by another class //
Element.prototype.rempClass = function(first,second) {
this.classList.remove(first);
this.classList.add(second);
};
}
as you see i have player interface and playlist menu
in pc audioplayer work fine and can get audio duration & other audio details.
but when i access from phone even audio details cant get.
Thank you all
Demo
I am using this code
http://jsfiddle.net/sagive/cAsB3/
my question is how to pause the slider when mouse is on the pictures(hover).
$.getJSON('assets/json/slides.json', function(data) {
$("h2").html(data[0].title);
$.each(data, function (i, f) {
if(i>0){
$("#exampleSlider").append("<li><img src=" + f.content + "/></li>");
}
});
});
$(function () {
/* SET PARAMETERS */
var change_img_time = 3000;
var transition_speed =200;
var simple_slideshow = $("#exampleSlider"),
listItems = simple_slideshow.children('li'),
listLen = listItems.length,
i = 0,
changeList = function () {
listItems.eq(i).fadeOut(transition_speed, function () {
i += 1;
if (i === listLen) {
i = 0;
}
listItems.eq(i).fadeIn(transition_speed);
});
};
listItems.not(':first').hide();
setInterval(changeList, change_img_time);
});
and I have another question also: when I import pic with get JSON. the directory in browser is like this:
assets/img/pic1.jpg/
how can I remove the / at the end of directory. because with / in is not shows the pic in browsers
thanks
Try:
if($('#exampleSlider').is(":hover") == true){
return false;
}
i have download the slider from this Site
I am trying to get this Slider to auto play but I can't seem to get it to work, Does anyone know how I can achieve this? i tried to play with the below code but can not get what i want.
function init() {
[].forEach.call(document.querySelectorAll('.tt-grid-wrapper'), function (el) {
var grid = el.querySelector('.tt-grid'),
items = [].slice.call(grid.querySelectorAll('li')),
navDots = [].slice.call(el.querySelectorAll('nav > a')),
isAnimating = false,
current = 0;
navDots.forEach(function (el, i) {
el.addEventListener(eventtype, function (ev) {
if (isAnimating || current === i) return false;
ev.preventDefault();
isAnimating = true;
updateCurrent(i);
loadNewSet(i);
});
});
You can try something like this:
function init() {
[].forEach.call(document.querySelectorAll('.tt-grid-wrapper'), function (el) {
var grid = el.querySelector('.tt-grid'),
items = [].slice.call(grid.querySelectorAll('li')),
navDots = [].slice.call(el.querySelectorAll('nav > a')),
isAnimating = false,
current = 0;
navDots.forEach(function (el, i) {
el.addEventListener(eventtype, function (ev) {
if (isAnimating || current === i) return false;
ev.preventDefault();
isAnimating = true;
updateCurrent(i);
loadNewSet(i);
});
});
var delay = 1000;
var num_frames = 4;
var i = 1;
setTimeout( function() {
if (isAnimating || current === i) return false;
isAnimating = true;
updateCurrent(i);
loadNewSet(i);
i >= 4 ? i = 0 : i++;
} , delay);
};
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I can't for the life of me figure out why loading this page...
http://polyphonic.hannahkingdev.com/work/cowboys-angels or any other video page sometimes causes the browser to hang and then prompts me to stop the script that is causing the browser to slowdown.
If the video is left to run, by the time you go to close the page, the browser is pretty unresponsive. This is the same in FFox, Safari & Chrome.
Any help finding the memory leak would be most appreciated. I am completely stumped on this one.
Many thanks
var $ = jQuery.noConflict();
$(document).ready(initPage);
// -- Init -- //
function initPage() {
resizeWork();
//hoverWorkImg();
};
// -- Pageload -- //
$(document).ready(function() {
$(".animsition").animsition({
inClass: 'overlay-slide-in-left',
outClass: 'overlay-slide-out-left',
inDuration: 1500,
outDuration: 800,
linkElement: 'a:not([target="_blank"]):not([href^=#]):not([href^=mailto]:not([href^=tel])',
loading: true,
loadingParentElement: 'body', //animsition wrapper element
loadingClass: 'animsition-loading',
loadingInner: '', // e.g '<img src="loading.svg" />'
timeout: false,
timeoutCountdown: 5000,
onLoadEvent: true,
browser: [ 'animation-duration', '-webkit-animation-duration'],
overlay : true,
overlayClass : 'animsition-overlay-slide',
overlayParentElement : 'body',
transition: function(url){ window.location.href = url; }
});
});
// -- Navigation -- //
if (document.getElementById('menu-button') !=null) {
var button = document.getElementById('menu-button');
var menu = document.getElementById('menu-main-navigation');
var menuPos = window.innerHeight;
var menuFixed = false;
button.addEventListener('click', function(ev){
ev.preventDefault();
menu.classList.toggle('navigation--isOpen');
button.classList.toggle('navigation-button--isOpen');
})
updateMenuPosition();
window.addEventListener('resize', updateMenuPosition);
// -- Highlight nav -- /
var $navigationLinks = $('#menu-main-navigation > li > a');
var $sections = $($("section").get().reverse());
var sectionIdTonavigationLink = {};
$sections.each(function() {
var id = $(this).attr('id');
sectionIdTonavigationLink[id] = $('#menu-main-navigation > li > a[href="#' + id + '"]');
});
function throttle(fn, interval) {
var lastCall, timeoutId;
return function () {
var now = new Date().getTime();
if (lastCall && now < (lastCall + interval) ) {
clearTimeout(timeoutId);
timeoutId = setTimeout(function () {
lastCall = now;
fn.call();
}, interval - (now - lastCall) );
} else {
lastCall = now;
fn.call();
}
};
}
function highlightNavigation() {
var scrollPosition = $(window).scrollTop();
$sections.each(function() {
var currentSection = $(this);
var sectionTop = currentSection.offset().top;
if (scrollPosition >= sectionTop) {
var id = currentSection.attr('id');
var $navigationLink = sectionIdTonavigationLink[id];
if (!$navigationLink.hasClass('active')) {
$navigationLinks.removeClass('active');
$navigationLink.addClass('active');
}
return false;
}
});
}
$(window).scroll( throttle(highlightNavigation,100) );
}
function updateMenuPosition(){
if(menuFixed){
menu.classList.remove('navigation--white');
menuPos = menu.offsetTop;
menu.classList.add('navigation--white');
} else {
menuPos = menu.offsetTop;
}
updateMenuAttachment();
}
updateMenuAttachment();
window.addEventListener('scroll', updateMenuAttachment);
function updateMenuAttachment(){
var scrollPos = document.documentElement.scrollTop || document.body.scrollTop;
if(!menuFixed && scrollPos >= window.innerHeight - 200){
menu.classList.add('navigation--white');
menuFixed = true;
} else if(menuFixed && scrollPos < window.innerHeight - 200){
menu.classList.remove('navigation--white');
menuFixed = false;
}
}
// -- Smooth scroll to anchor -- /
$('a[href*="#"]')
.not('[href="#"]')
.not('[href="#0"]')
.click(function(event) {
if (
location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
&&
location.hostname == this.hostname
) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (this.hash=="#work") {;
var offsetT = (target.offset().top)-90;
} else {
var offsetT = (target.offset().top);
}
if (target.length) {
event.preventDefault();
$('html, body').animate({
scrollTop: offsetT
}, 1000, function() {
});
}
}
});
// -- Back to top -- /
jQuery(document).ready(function($){
var offset = 300,
offset_opacity = 1200,
scroll_top_duration = 700,
$back_to_top = $('.cd-top');
$(window).scroll(function(){
( $(this).scrollTop() > offset ) ? $back_to_top.addClass('cd-is-visible') : $back_to_top.removeClass('cd-is-visible cd-fade-out');
if( $(this).scrollTop() > offset_opacity ) {
$back_to_top.addClass('cd-fade-out');
}
});
$back_to_top.on('click', function(event){
event.preventDefault();
$('body,html').animate({
scrollTop: 0 ,
}, scroll_top_duration
);
});
});
// -- Animate -- /
new WOW().init();
// -- Inline all SVGs -- /
jQuery('img.svg').each(function(){
var $img = jQuery(this);
var imgID = $img.attr('id');
var imgClass = $img.attr('class');
var imgURL = $img.attr('src');
jQuery.get(imgURL, function(data) {
// Get the SVG tag, ignore the rest
var $svg = jQuery(data).find('svg');
// Add replaced image's ID to the new SVG
if(typeof imgID !== 'undefined') {
$svg = $svg.attr('id', imgID);
}
// Add replaced image's classes to the new SVG
if(typeof imgClass !== 'undefined') {
$svg = $svg.attr('class', imgClass+' replaced-svg');
}
// Remove any invalid XML tags as per http://validator.w3.org
$svg = $svg.removeAttr('xmlns:a');
// Check if the viewport is set, if the viewport is not set the SVG wont't scale.
if(!$svg.attr('viewBox') && $svg.attr('height') && $svg.attr('width')) {
$svg.attr('viewBox', '0 0 ' + $svg.attr('height') + ' ' + $svg.attr('width'))
}
// Replace image with new SVG
$img.replaceWith($svg);
}, 'xml');
});
// -- work grid -- /
function resizeWork() {
var div = $('.work article');
div.css('height', div.width() / 1.9);
}
function hoverWorkImg() {
$('article a').on('mouseenter', function () {
$(this).find('.imagehover:hidden').fadeIn(700);
$(this).find('.second:hidden').fadeIn(700);
$(this).find('.first:visible').fadeOut(700);
})
$('article a').on('mouseleave', function () {
$(this).find('.imagehover:visible').fadeOut(700);
$(this).find('.second:visible').fadeOut(700);
$(this).find('.first:hidden').fadeIn(700);
})
}
// -- Video Page -- /
function playVideoInPage() {
showModal(false);
initPlayer();
startPlay();
}
var $video,
$playPauseButton,
$muteButton,
$seekBar,
isMouseMove=false,
$timing;
function showModal(html) {
if (html !== false) {
$('.work-video').html(html).fadeIn();
}
else {
$('.work-video').fadeIn();
}
hidePlayerControls();
}
function initPlayer() {
$('#video').css('height', $(window).height());
$video = $('.video-container'),
$playPauseButton = $('#play-pause'),
$muteButton = $('#mute'),
$seekBar = $('#seek-bar'),
$timing = $('.timing');
/*setTimeout('showPlayerControls()', 1500);*/
$playPauseButton.on('click', function () {
if ($video.get()[0].paused == true) {
$video.get()[0].play();
$playPauseButton.removeClass('paused');
}
else {
$video.get()[0].pause();
$playPauseButton.addClass('paused');
$timing.stop(true, true);
}
})
$muteButton.on('click', function () {
if ($video.get()[0].muted == false) {
$video.get()[0].muted = true;
$muteButton.addClass('muted');
}
else {
$video.get()[0].muted = false;
$muteButton.removeClass('muted');
}
})
$seekBar.on("click", function (e) {
var x = e.pageX - $(this).offset().left,
widthForOnePercent = $seekBar.width() / 100,
progress = x / widthForOnePercent,
goToTime = progress * ($video.get()[0].duration / 100);
goToPercent(progress)
$video.get()[0].currentTime = goToTime;
});
$video.get()[0].addEventListener("timeupdate", function () {
var value = (100 / $video.get()[0].duration) * $video.get()[0].currentTime;
goToPercent(value)
});
}
function startPlay() {
$playPauseButton.click();
}
function goToPercent(value) {
$timing.css('width', value + '%');
}
function showPlayerControls() {
$('.controls').fadeIn();
isMouseMove=true;
}
function hidePlayerControls() {
$('.controls').fadeOut();
}
function hidePlayerControls() {
setInterval(function() {
if (!isMouseMove) {
hidePlayerControls();
}
isMouseMove=false;
}, 4000);
$(document).mousemove(function (event) {
isMouseMove=true;
showPlayerControls();
});
}
The most likely cause is this code here:
function hidePlayerControls() {
setInterval(function() {
if (!isMouseMove) {
hidePlayerControls();
}
isMouseMove=false;
}, 4000);
so every 4 seconds you start a new interval (interval = repeat until cancelled).
In the first case, you might like to change this to setTimeout
function hidePlayerControls() {
setTimeout(function() {
if (!isMouseMove) {
hidePlayerControls();
}
isMouseMove=false;
}, 4000);
In the second, you could change this to cancel the previous timeout when the mouse moves - this is termed debouncing - though usually with a shorter interval, the principle is the same.
As a general debugging tip, liberally add console.log statements and watch your browser console (there are other ways, this is a basic debugging first-step), eg:
function hidePlayerControls() {
console.log("hidePlayerControls() called");
setInterval(function() {
console.log("hidePlayerControls - interval triggered", isMouseMove);
if (!isMouseMove) {
hidePlayerControls();
}
isMouseMove=false;
}, 4000);
to see just how many times this gets called