How to make play button disabled after the animation is finished? - javascript

I have this problem: I have two buttons btStop and btRace . BtPlays clicks all the buttons bt1 and all my cars are driving at the same time. BtStop works exactly the same but it stops the animation. My problem is, that when I once click btRace and animation is done I cannot click it again unless I click btStop, which is misleading because animation is already stopped.
Is there a way to make btPlay active again after the animation is finished?
I have long code so I am pasting showButtons method
showButtons(bt1, bt2, img, editingCarId) {
let playBts = document.querySelectorAll('.play')
function animation(img) {
let status = 'started';
let aPICallCarEngineState = new APICallCarEngineState(editingCarId, status);
aPICallCarEngineState.processRequestJSON((res) => {
// let resStr = JSON.stringify(res);
// console.log('I got ' + res)
res.velocity = res.velocity * 0.01
// res.distance = res.distance * 0.001
res.distance = 500;
// ===========Animation===================
img.style.animation = `car_move ${res.velocity}s ease-in`
})
}
//================Stop Animation===============
function stopAnimation() {
img.style.animation = 'none'
console.log(bt2 + 'stopp')
}
bt1.addEventListener('click', () => {
animation(img)
});
bt2.addEventListener('click', () => {
stopAnimation()
})
//=================Button start all animations ====================
this.btRace.addEventListener('click', () => {
bt1.click();
})
//=================Button stop all animations ====================
this.btStop.addEventListener('click', () => {
bt2.click();
})
}
invoke:
constructor:
this.table.appendTableHeadButton('RACE!')
this.table.appendTableHeadButtonStop('stop')
Buttoncreator:
appendTableHeadButtonStop(text) {
let td = document.createElement('td');
this.btStop = document.createElement('button');
this.btStop.innerText = text;
this.btStop.style.backgroundColor = 'red';
td.appendChild(this.btStop);
let bt = this.btStop;
this.headeRow.appendChild(td);
}

showButtons(bt1, bt2, img, editingCarId) {
let playBts = document.querySelectorAll('.play')
let isAnimating = false;
function animation(img) {
isAnimating = true;
btRace.disabled = true;
let status = 'started';
let aPICallCarEngineState = new APICallCarEngineState(editingCarId, status);
aPICallCarEngineState.processRequestJSON((res) => {
// let resStr = JSON.stringify(res);
// console.log('I got ' + res)
res.velocity = res.velocity * 0.01
// res.distance = res.distance * 0.001
res.distance = 500;
// ===========Animation===================
img.style.animation = `car_move ${res.velocity}s ease-in`
img.addEventListener('animationend', () => {
isAnimating = false;
btRace.disabled = false;
});
});
}
//================Stop Animation===============
function stopAnimation() {
isAnimating = false;
btRace.disabled = false;
img.style.animation = 'none'
console.log(bt2 + 'stopp')
}
bt1.addEventListener('click', () => {
animation(img)
});
bt2.addEventListener('click', () => {
stopAnimation()
});
//=================Button start all animations ====================
this.btRace.addEventListener('click', () => {
bt1.click();
});
//=================Button stop all animations ====================
this.btStop.addEventListener('click', () => {
bt2.click();
});
}
I am adding a flag to check the state of animation, and then toggle disabled property of btRace button respectively.

Related

How do I make a media Query responsive in JavaScript?

I really need some help with media queries. I have made a testimonial slider and when it gets to a 800px breakpoint, I want to disable the JS for the slider and change the layout.
The problem is that I am unable to deactivate the js once it has been activated, I'm not sure if the problem is from the event handler, the if statement of from the deactivation function.
I have managed to deactivate the JS but I have to reload the page to do it, I want it to be responsive so that I don't have to reload the page every time.
If you can help, that would be a huge help, thanks!
Here is my JS code:
(All my css code works, hence, it hasn't been added).
const mQ = window.matchMedia('(max-width: 800px)');
const testimonialSlider = function () {
const slides = document.querySelectorAll('.slide');
const btnLeft = document.querySelector('.slider__btn--left');
const btnRight = document.querySelector('.slider__btn--right');
const dotContainer = document.querySelector('.dots');
const testimonialContainer = document.querySelector(
'.testimonial-outer-container'
);
//Deactivate functions
const deactivateJs = function (slide) {
slides.forEach(
(s, i) => (s.style.transform = `translateX(${0 * (i - slide)}%)`)
);
testimonialContainer.removeChild(dotContainer);
console.log('DeactivatingJs');
};
// Activate functions
const activateJs = function () {
console.log('ActivateJS');
let curSlide = 0;
const maxSlide = slides.length;
//Functions
const createDots = function () {
testimonialContainer.appendChild(dotContainer);
slides.forEach(function (_, i) {
dotContainer.insertAdjacentHTML(
'beforeend',
`<button class="dots__dot" data-slide="${i}"></button>`
);
});
};
const slideReady = function () {
createDots();
activateDot(0);
goToSlide(0);
};
const goToSlide = function (slide) {
slides.forEach(
(s, i) => (s.style.transform = `translateX(${100 * (i - slide)}%)`)
);
};
// Activate dots
const activateDot = function (slide) {
// First we remove the active class on all of the dots and then we add it to the one that it is active
document
.querySelectorAll('.dots__dot')
.forEach(dot => dot.classList.remove('dots__dot--active'));
document
.querySelector(`.dots__dot[data-slide="${slide}"]`)
.classList.add('dots__dot--active');
};
// Next slide
const nextSlide = function () {
if (curSlide === maxSlide - 1) {
curSlide = 0;
} else {
curSlide++;
}
goToSlide(curSlide);
activateDot(curSlide);
};
const prevSlide = function () {
if (curSlide === 0) {
curSlide = maxSlide - 1;
} else {
curSlide--;
}
goToSlide(curSlide);
activateDot(curSlide);
};
slideReady();
//Event Handlers
btnRight.addEventListener('click', nextSlide);
btnLeft.addEventListener('click', prevSlide);
// Creating an event with the arrows
document.addEventListener('keydown', function (e) {
console.log(e);
if (e.key === 'ArrowLeft') prevSlide();
if (e.key === 'ArrowRight') nextSlide();
});
dotContainer.addEventListener('click', function (e) {
if (e.target.classList.contains('dots__dot')) {
/// const slide = e.target.dataset.slide;
//This is the same as above, the slide part is from the html and the dataset is an HTML attribute
const { slide } = e.target.dataset;
goToSlide(slide);
activateDot(slide);
}
});
};
// if (mQ.matches) {
// deactivateJs();
// } else {
// activateJs();
// }
const js = function () {
if (mQ.matches) {
console.log('deactivate');
deactivateJs();
} else {
activateJs();
}
};
mQ.addEventListener('change', js);
};
testimonialSlider();

Counter with clearInterval, not restarting after button click

There is a word-translation card page which includes:
A 3-second countdown that runs immediately after the page loads and when you move to a new word after press the 'Correct' button.
Word and his translate which appears after 'Excellent' button pressed. This button stops and hide the counter.
Button 'Show answer' which appears if 'Excellent' didn't pressed in 3 sec.
Buttons 'Wrong' and 'Correct' which appears if 'Excellent' or 'Show answer' buttons are pressed.
The problem is how the countdown works (unstable). Sometimes it doesn't restart after clicking "Correct". I tried manage countdown in separate function, but this approach provides much more issues. So now there is a timer that is called globally and a timer that is called when you click on the "Correct" button.I think the problem is near timerId. I will be glad to any comments and ideas on the code.
<div class="deck-container">
<div class="words-container">
<h2 id="primary-word"></h2>
<h2 id="secondary-word"></h2>
</div>
<div class="btn-container">
<p id="timer-count">3</p>
<button id="btn-excellent" onClick="excellent()">Excellent!</button>
<button id="btn-show-answer" onClick="showAnswerF()">Show Answer</button>
<button id="btn-wrong">Wrong</button>
<button id="btn-correct" onClick="correctF()">Correct</button>
</div>
</div>
let currentWord = 0
let timerCount = 3
let fetched_data = {}
async function getDeck () {
let response = await fetch('/api/deck_words/2/', {
method: 'get',
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/json'
}
}
)
let data = await response.json()
let primaryElement = document.getElementById('primary-word')
primaryElement.innerText = await data[currentWord]['primary_word']
let secondaryElement = document.getElementById('secondary-word')
secondaryElement.innerText = await data[currentWord]['secondary_word']
return data
}
fetched_data = getDeck()
const getData = async () => {
return await getDeck()
}
data = getData();
function countDecrease() {
timerCount --
if (timerCount > 0) {
document.getElementById("timer-count").innerHTML = timerCount
} else {
hideExcellent()
}
}
function hideExcellent() {
showElement(true,'btn-excellent')
showElement(true,'timer-count')
showElement(false,'btn-show-answer')
}
let timerId = setInterval(() => countDecrease(), 1000)
setTimeout(() => {
clearInterval(timerId)
}, 3000)
function showElement(showProperty, elementClass) {
showProperty = !showProperty
let element = document.getElementById(elementClass)
element.style.display = (showProperty === true) ? "inline-block" : "none";
}
function showAnswerF() {
showElement(true,'btn-show-answer')
showElement(false,'secondary-word')
showElement(false,'btn-wrong')
showElement(false,'btn-correct')
}
function excellent() {
showElement(true,'timer-count')
showElement(true,'btn-excellent')
showElement(false,'btn-wrong')
showElement(false,'btn-correct')
showElement(false,'secondary-word')
clearInterval(timerId)
timerCount = 3
}
function correctF() {
currentWord++
const changeWords = () => {
fetched_data.then((data) => {
document.getElementById('primary-word').innerText = data[currentWord]['primary_word']
document.getElementById('secondary-word').innerText = data[currentWord]['secondary_word']
document.getElementById("timer-count").innerText = '3'
timerCount = 3
timerId = setInterval(() => countDecrease(), 1000)
setTimeout(() => {
clearInterval(timerId)
}, 3000)
})
}
changeWords()
let countElement = document.getElementById('timer-count')
countElement.style.display = "block"
showElement(false,'btn-excellent')
showElement(true,'btn-wrong')
showElement(true,'btn-correct')
showElement(true,'secondary-word')
}
I think this would be better handled with an async function, maybe like so.
const timerCount = document.querySelector("#timer-count")
const reset = document.querySelector("button")
function delay(ms) {
return new Promise(res => setTimeout(res, ms))
}
async function countDown(signal) {
const aborted = new Promise(resolve => signal.addEventListener("abort", resolve))
for (let i = 10; i >= 0 && signal?.aborted != true; --i) {
timerCount.textContent = i
await Promise.race([delay(1000), aborted])
}
timerCount.textContent = ""
}
async function startCountdown() {
const ac = new AbortController()
const abort = () => ac.abort()
reset.addEventListener("click", abort, { once: true })
reset.textContent = "Cancel"
await countDown(ac.signal)
reset.removeEventListener("click", abort)
reset.addEventListener("click", startCountdown, { once: true })
reset.textContent = "Start"
}
startCountdown()
<p id="timer-count"></p>
<button>Start</button>
Alternatively, you might want to model the countdown as an object that implements EventTarget.
const timerCount = document.querySelector("#timer-count")
const btn = document.querySelector("button")
class Timer extends EventTarget {
#value; #tick_rate; #enabled; #interval_handle
constructor(tick_rate = 1000) {
super()
this.#value = 0
this.#tick_rate = tick_rate
this.#enabled = false
this.#interval_handle = null
}
get value() {
return this.#value
}
set value(value) {
this.#value = value
this.dispatchEvent(new Event("update"))
}
get tick_rate() {
return this.#tick_rate
}
get enabled() {
return this.#enabled
}
start() {
if (this.#enabled) return
this.#enabled = true
this.#interval_handle = setInterval(Timer.#tick, this.#tick_rate, this)
this.dispatchEvent(new Event("start"))
}
stop() {
if (!this.#enabled) return
this.#enabled = false
clearInterval(this.#interval_handle)
this.dispatchEvent(new Event("stop"))
}
static #tick(timer) {
timer.value = Math.max(0, timer.value - 1)
if (timer.value == 0) timer.stop()
}
}
const timer = new Timer()
timer.addEventListener("start", function() {
btn.textContent = "Stop"
})
timer.addEventListener("stop", function() {
timerCount.textContent = ""
btn.textContent = "Start"
})
timer.addEventListener("update", function() {
timerCount.textContent = timer.value
})
btn.addEventListener("click", function() {
if (timer.enabled == false) {
timer.value = 5
timer.start()
} else {
timer.stop()
}
})
<p id="timer-count"></p>
<button>Start</button>
Here's a countdown. The first count is after 1 second.
let count = 3;
let timer = [];
const start = () => {
new Array(count).fill(true).forEach((_,i) => {
timer.push(setTimeout(() => console.log('count',count - i),(i+1) * 1000))
})
}
const stop = () => timer.forEach(clearTimeout);
<button onclick="stop()">STOP</button>
<button onclick="start()">START</button>

Adding auto play to Javascript image slider

I have a slider and I want to add auto play every 3 seconds. I tried to use SetInterval but nothing happened.
Also I would like to remove the code for removing elements from the slider. I want to remove all the controls also and have only the slider changing image every 3 seconds.
this is the slider code
const galleryContainer = document.querySelector('.gallery-container');
const galleryControlsContainer = document.querySelector('.gallery-controls');
const galleryControls = ['Предидущий', '', 'Следующий'];
const galleryItems = document.querySelectorAll('.gallery-item');
class Carousel {
constructor(container, items, controls) {
this.carouselContainer = container;
this.carouselControls = controls;
this.carouselArray = [...items];
}
updateGallery() {
this.carouselArray.forEach(el => {
el.classList.remove('gallery-item-1');
el.classList.remove('gallery-item-2');
el.classList.remove('gallery-item-3');
el.classList.remove('gallery-item-4');
el.classList.remove('gallery-item-5');
});
this.carouselArray.slice(0, 5).forEach((el, i) => {
el.classList.add(`gallery-item-${i+1}`);
});
}
setCurrentState(direction) {
if (direction.className == 'gallery-controls-previous') {
this.carouselArray.unshift(this.carouselArray.pop());
} else {
this.carouselArray.push(this.carouselArray.shift());
}
this.updateGallery();
}
setControls() {
this.carouselControls.forEach(control => {
galleryControlsContainer.appendChild(document.createElement('button')).className = `gallery-controls-${control}`;
document.querySelector(`.gallery-controls-${control}`).innerText = control;
});
}
useControls() {
const triggers = [...galleryControlsContainer.childNodes];
triggers.forEach(control => {
control.addEventListener('click', e => {
e.preventDefault();
if (control.className == 'gallery-controls-add') {
const newItem = document.createElement('img');
const latestItem = this.carouselArray.length;
const latestIndex = this.carouselArray.findIndex(item => item.getAttribute('data-index') == this.carouselArray.length)+1;
Object.assign(newItem,{
className: 'gallery-item',
src: `http://fakeimg.pl/300/?text=${this.carouselArray.length+1}`
});
newItem.setAttribute('data-index', this.carouselArray.length+1);
this.carouselArray.splice(latestIndex, 0, newItem);
document.querySelector(`[data-index="${latestItem}"]`).after(newItem);
this.updateGallery();
} else {
this.setCurrentState(control);
}
});
});
}
}
const exampleCarousel = new Carousel(galleryContainer, galleryItems, galleryControls);
exampleCarousel.setControls();
exampleCarousel.useControls();
See the below code, I have added auto slide functionality with interval time 5 seconds.
If you want to change the interval, Please update the setInterval time in the "constructor" and "setCurrentState" functions.
I have removed the controls. To remove the controls, we need to comment the last 2 lines
//exampleCarousel.setControls();
//exampleCarousel.useControls();
const galleryContainer = document.querySelector('.gallery-container');
const galleryControlsContainer = document.querySelector('.gallery-controls');
const galleryControls = ['Предидущий', '', 'Следующий'];
const galleryItems = document.querySelectorAll('.gallery-item');
class Carousel {
constructor(container, items, controls) {
this.carouselContainer = container;
this.carouselControls = controls;
this.carouselArray = [...items];
this.mySlideInterval = null;
this.mySlideInterval = setInterval(
this.autoSlide.bind(this),
5000
);
}
autoSlide() {
this.carouselArray.push(this.carouselArray.shift());
this.updateGallery();
}
updateGallery() {
this.carouselArray.forEach(el => {
el.classList.remove('gallery-item-1');
el.classList.remove('gallery-item-2');
el.classList.remove('gallery-item-3');
el.classList.remove('gallery-item-4');
el.classList.remove('gallery-item-5');
});
this.carouselArray.slice(0, 5).forEach((el, i) => {
el.classList.add(`gallery-item-${i+1}`);
});
}
setCurrentState(direction) {
if (direction.className == 'gallery-controls-previous') {
this.carouselArray.unshift(this.carouselArray.pop());
} else {
this.carouselArray.push(this.carouselArray.shift());
}
clearInterval(this.mySlideInterval);
this.updateGallery();
this.mySlideInterval = setInterval(
this.autoSlide.bind(this),
5000
);
}
setControls() {
this.carouselControls.forEach(control => {
galleryControlsContainer.appendChild(document.createElement('button')).className = `gallery-controls-${control}`;
document.querySelector(`.gallery-controls-${control}`).innerText = control;
});
}
useControls() {
const triggers = [...galleryControlsContainer.childNodes];
triggers.forEach(control => {
control.addEventListener('click', e => {
e.preventDefault();
if (control.className == 'gallery-controls-add') {
const newItem = document.createElement('img');
const latestItem = this.carouselArray.length;
const latestIndex = this.carouselArray.findIndex(item => item.getAttribute('data-index') == this.carouselArray.length)+1;
Object.assign(newItem,{
className: 'gallery-item',
src: `http://fakeimg.pl/300/?text=${this.carouselArray.length+1}`
});
newItem.setAttribute('data-index', this.carouselArray.length+1);
this.carouselArray.splice(latestIndex, 0, newItem);
document.querySelector(`[data-index="${latestItem}"]`).after(newItem);
this.updateGallery();
} else {
this.setCurrentState(control);
}
});
});
}
}
const exampleCarousel = new Carousel(galleryContainer, galleryItems, galleryControls);
//exampleCarousel.setControls();
//exampleCarousel.useControls();

passing a simon game from jQuery to vanilla JS

Long story short, I made this Simon Game in a bootcamp a month ago in jQuery, but the days pass and I started to feel the necesity of translate it to pure vanilla javaScript.
the thing is that I feel stuck in the last part, when I have to check the answers of the game and add that to the gamePatern array and userChosenPattern.
here is the main part in jQuery
var buttonColors = ["red", "blue", "green", "yellow"];
var gamePattern = [];
var userClickedPattern = [];
var started = false;
var level = 0;
$(document).keypress(function () {
if (!started) {
$("#level-title").text("level " + level);
nextSequence();
started = true;
}
});
function nextSequence() {
userClickedPattern = [];
level++;
$("#level-title").text("level " + level);
var randomNumber = Math.floor(Math.random() * 4);
var randomChosenColour = buttonColors[randomNumber];
gamePattern.push(randomChosenColour);
$("#" + randomChosenColour)
.fadeIn(100)
.fadeOut(100)
.fadeIn(100);
playSound(randomChosenColour);
}
$(".btn").click(function () {
var userChosenColor = $(this).attr("id");
userClickedPattern.push(userChosenColor);
playSound(userChosenColor);
animatePress(userChosenColor);
checkTheAnswer(userClickedPattern.length - 1);
});
function checkTheAnswer(currentLevel) {
if (gamePattern[currentLevel] === userClickedPattern[currentLevel]) {
console.log("success");
if (userClickedPattern.length === gamePattern.length) {
setTimeout(function () {
nextSequence();
}, 1000);
}
} else {
$("body").addClass("game-over");
setTimeout(function () {
$("body").removeClass("game-over");
}, 200);
gameOverAudio();
$("#level-title").text("Game Over, Press Any Key to Restart");
$("#level-title").css("font-size", "2rem");
startOver();
}
}
function startOver() {
level = 0;
gamePattern = [];
started = false;
}
function playSound(name) {
var audio = new Audio("sounds/" + name + ".mp3");
audio.play();
}
function gameOverAudio() {
var gameOver = new Audio("sounds/wrong.mp3");
gameOver.play();
}
function animatePress(currentColor) {
$("#" + currentColor).addClass("pressed");
setTimeout(function () {
$("#" + currentColor).removeClass("pressed");
}, 100);
}
and here is the same part and the whole code but in vanilla JS
const buttonColors = ["red", "blue", "green", "yellow"];
const gamePattern = [];
const userClickedPattern = [];
const started = false;
const level = 0;
const body = document.querySelector("body");
const levelTitle = document.getElementById("level-title");
// to start the game
document.addEventListener("keypress", () => {
if (!started) {
levelTitle.innerHTML = `level ${level}`;
nextSequence();
sarted = true;
}
});
// generete the next sequence
function nextSequence() {
var randomNumber = Math.floor(Math.random() * 4);
var randomChosenColour = buttonColors[randomNumber];
gamePattern.push(randomChosenColour);
let animationBtn = document.querySelector("#" + randomChosenColour);
animationBtn.classList.add("FadeInFadeOut");
setTimeout(() => {
animationBtn.classList.remove("FadeInFadeOut");
}, 50);
playSound(randomChosenColour);
}
// here we detect which button is pressed by the user
var bTn = document.getElementsByClassName("btn");
document.querySelectorAll(".btn").forEach((bt) => {
bt.onclick = () => {
let userChosenColor = bt.id;
userClickedPattern.push(userChosenColor);
playSound(userChosenColor);
animatePress(userChosenColor);
checkTheAnswer(userClickedPattern.length - 1);
};
});
// check the answer and dynamic of the game
const checkTheAnswer = (currentLevel) => {
if (gamePattern[currentLevel] === userClickedPattern[currentLevel]) {
console.log("succes");
if (userClickedPattern.length === gamePattern.length) {
setTimeout(() => {
nextSequence();
}, 1000);
}
} else {
body.classList.add("game-over");
setTimeout(() => {
body.classList.remove("game-over");
}, 200);
gameOverAudio();
levelTitle.innerHTML = `Game Over, Press Any Key to Restart`;
levelTitle.style.fontSize = "2rem";
startOver();
}
};
const startOver = () => {
level = 0;
gamePattern = [];
started = false;
};
// adudio stuff
const playSound = (name) => {
let audio = new Audio("sounds/" + name + ".mp3");
audio.play();
};
function gameOverAudio() {
var gameOver = new Audio("sounds/wrong.mp3");
gameOver.play();
}
//animation in button
const animatePress = (currentColor) => {
const buttons = document.querySelector(`#${currentColor}`);
buttons.classList.add("pressed");
setTimeout(() => {
buttons.classList.remove("pressed");
}, 100);
};
console.log(gamePattern);
console.log(userClickedPattern);
Also here is the game in my codepen, it’s without the sounds for obvious reasons.
Simon Game

How to make custom video player applicable to multiple videos?

I have multiple HTML videos on my page, and want to apply this custom video player to them. The thing is, this only works for the first video, and not for the second, third and fourth.
I have no idea where to start.
I made a fiddle of the current state: JSFiddle
My Javascript
/* Get Our Elements */
const player = document.querySelector('.player');
const video = player.querySelector('.viewer');
const progress = player.querySelector('.progress');
const progressBar = player.querySelector('.progress__filled');
const toggle = player.querySelector('.toggle');
const skipButtons = player.querySelectorAll('[data-skip]');
const ranges = player.querySelectorAll('.player__slider');
/* Build out functions */
function togglePlay() {
const method = video.paused ? 'play' : 'pause';
video[method]();
}
function updateButton() {
const icon = this.paused ? '►' : '❚❚';
toggle.textContent = icon;
}
function skip() {
video.currentTime += parseFloat(this.dataset.skip);
}
function handleRangeUpdate() {
video[this.name] = this.value;
}
function handleProgress() {
const percent = (video.currentTime / video.duration) * 100;
progressBar.style.flexBasis = `${percent}%`;
}
function scrub(e) {
const scrubTime = (e.offsetX / progress.offsetWidth) * video.duration;
video.currentTime = scrubTime;
}
/* Hook up the event listners */
video.addEventListener('click', togglePlay);
video.addEventListener('play', updateButton);
video.addEventListener('pause', updateButton);
video.addEventListener('timeupdate', handleProgress);
toggle.addEventListener('click', togglePlay);
skipButtons.forEach(button => button.addEventListener('click', skip));
ranges.forEach(range => range.addEventListener('change', handleRangeUpdate));
ranges.forEach(range => range.addEventListener('mousemove', handleRangeUpdate));
let mousedown = false;
progress.addEventListener('click', scrub);
progress.addEventListener('mousemove', (e) => mousedown && scrub(e));
progress.addEventListener('mousedown', () => mousedown = true);
progress.addEventListener('mouseup', () => mousedown = false);
$('video').on('ended', function() {
$.fn.fullpage.moveSlideRight();
});
I want this script to work on every video element on the page:
JSFiddle
Thanks,
Max
You can try something like this :
/* Get Our Elements */
$('.player').each(function() {
var player = $(this).get(0);
var video = player.querySelector('.viewer');
var progress = player.querySelector('.progress');
var progressBar = player.querySelector('.progress__filled');
var toggle = player.querySelector('.toggle');
var skipButtons = player.querySelectorAll('[data-skip]');
var ranges = player.querySelectorAll('.player__slider');
/* Build out functions */
function togglePlay() {
const method = video.paused ? 'play' : 'pause';
video[method]();
}
function updateButton() {
const icon = this.paused ? '►' : '❚❚';
toggle.textContent = icon;
}
function skip() {
video.currentTime += parseFloat(this.dataset.skip);
}
function handleRangeUpdate() {
video[this.name] = this.value;
}
function handleProgress() {
const percent = (video.currentTime / video.duration) * 100;
progressBar.style.flexBasis = `${percent}%`;
}
function scrub(e) {
const scrubTime = (e.offsetX / progress.offsetWidth) * video.duration;
video.currentTime = scrubTime;
}
/* Hook up the event listners */
video.addEventListener('click', togglePlay);
video.addEventListener('play', updateButton);
video.addEventListener('pause', updateButton);
video.addEventListener('timeupdate', handleProgress);
toggle.addEventListener('click', togglePlay);
skipButtons.forEach(button => button.addEventListener('click', skip));
ranges.forEach(range => range.addEventListener('change', handleRangeUpdate));
ranges.forEach(range => range.addEventListener('mousemove', handleRangeUpdate));
let mousedown = false;
progress.addEventListener('click', scrub);
progress.addEventListener('mousemove', (e) => mousedown && scrub(e));
progress.addEventListener('mousedown', () => mousedown = true);
progress.addEventListener('mouseup', () => mousedown = false);
$('video').on('ended', function() {
$.fn.fullpage.moveSlideRight();
});
});
https://jsfiddle.net/kq5hdw0m/

Categories

Resources