Why my javascript dispatchEvent is not working - javascript

below is my javascript code. previousPage and NextPage are working properly with HTML button elements.
But I am not sure why addEventListener('wheel') is not working. So I inserted some console.log, then I realize var delta is corret. But, I guess there is a problem 'if (delta ~ ~' area...
const pageList = document.querySelectorAll('.verticalPaging');
const previousPage = document.querySelector('#previousScroller');
const nextPage = document.querySelector('#nextScroller');
const idlePeriod = 100;
const animationDuration = 1000;
let lastAnimation = 0;
let pageIndex = 0;
previousPage.addEventListener('click', ()=> {
if (pageIndex < 1) return;
pageIndex--;
pageList.forEach((section, i) => {
if (i === pageIndex) {
section.scrollIntoView({behavior: "smooth"});
}
});
});
nextPage.addEventListener('click', () => {
if (pageIndex > 4) return;
pageIndex++;
pageList.forEach((section, i) => {
if (i === pageIndex) {
section.scrollIntoView({behavior: "smooth"});
}
})
});
document.addEventListener('wheel', event => {
var delta = event.wheelDelta;
var timeNow = new Date().getTime();
// Cancel scroll if currently animating or within quiet period
if(timeNow - lastAnimation < idlePeriod + animationDuration) {
event.preventDefault();
return;
}
if (delta < 0) {
var event = new Event('click');
nextPage.dispatchEvent(event);
} else {
var event = new Event('click');
previousPage.dispatchEvent(event);
}
lastAnimation = timeNow;
},{passive: false});

The wheel event doesn't have a wheelDelta property, but it has deltaY which I guess you are actually after.
document.addEventListener('wheel', event => {
const timeNow = new Date().getTime();
// Cancel scroll if currently animating or within quiet period
if(timeNow - lastAnimation < idlePeriod + animationDuration) {
event.preventDefault();
return;
}
const clickEvent = new Event('click')
if (event.deltaY < 0) {
nextPage.dispatchEvent(clickEvent);
} else {
previousPage.dispatchEvent(clickEvent);
}
lastAnimation = timeNow;
},{passive: false});
I took the liberty to get rid of var

Related

Memory game with javascript

I have a small problem that could ruin the game. Once you click a card you need to search for the other card with the same picture right? but the problem is you can also double click and it will think you found the other card. Anyone know how o solf this problem?
const cards = document.querySelectorAll(".cards .card");
cards.forEach((card) => {
card.addEventListener("click", () => {
card.classList.add("clicked");
if (counter === 0) {
firstSelection = card.getAttribute("meme");
counter++;
} else {
secondSelection = card.getAttribute("meme");
counter = 0;
if (firstSelection === secondSelection) {
const correctCards = document.querySelectorAll(".card[meme='" + firstSelection + "']");
score.innerHTML = parseInt(score.innerHTML) + 1
if (score.innerHTML >= 8)
correctCards[0].classList.add("checked");
correctCards[0].classList.remove("clicked");
correctCards[1].classList.add("checked");
correctCards[1].classList.remove("clicked");
} else {
const incorrectCards = document.querySelectorAll(".card.clicked");
incorrectCards[0].classList.add("red");
incorrectCards[1].classList.add("red");
setTimeout(() => {
incorrectCards[0].classList.remove("red");
incorrectCards[0].classList.remove("clicked");
incorrectCards[1].classList.remove("red");
incorrectCards[1].classList.remove("clicked");
}, 600);
}
}
});
});
You can set 2 global vars firstClickedCard and secondClickedCard, and on click, assign the card element (event.currentTarget) to these variables. Then on second click, check if (secondClickedCard === firstClickedCard) before any of your other logic, and reject the click event if this is true.
This should verify if the actual clicked element (not just the meme attribute) are the same or not.
Note: this is untested, and would be easier to verify if your question included a minimal, reproducible example.
const cards = document.querySelectorAll(".cards .card");
var firstClickedCard;
var secondClickedCard;
cards.forEach((card) => {
card.addEventListener("click", (e) => {
card.classList.add("clicked");
if (counter === 0) {
firstClickedCard = e.currentTarget;
firstSelection = card.getAttribute("meme");
counter++;
} else {
secondClickedCard = e.currentTarget;
// reject this click
if (secondClickedCard === firstClickedCard) {
secondClickedCard = null;
return false;
}
secondSelection = card.getAttribute("meme");
counter = 0;
if (firstSelection === secondSelection) {
const correctCards = document.querySelectorAll(".card[meme='" + firstSelection + "']");
score.innerHTML = parseInt(score.innerHTML) + 1
if (score.innerHTML >= 8)
correctCards[0].classList.add("checked");
correctCards[0].classList.remove("clicked");
correctCards[1].classList.add("checked");
correctCards[1].classList.remove("clicked");
} else {
const incorrectCards = document.querySelectorAll(".card.clicked");
incorrectCards[0].classList.add("red");
incorrectCards[1].classList.add("red");
setTimeout(() => {
incorrectCards[0].classList.remove("red");
incorrectCards[0].classList.remove("clicked");
incorrectCards[1].classList.remove("red");
incorrectCards[1].classList.remove("clicked");
}, 600);
}
}
});
});
Although there is a double click event (dblclick), it is not supported by all browsers. The way around this is to test for double clicks within your click event handlers and use a timer function (to see if two clicks happened within a select amount of time). I use 300ms for the timer, but you may have to play around with that a bit.
const cards = document.querySelectorAll(".cards .card");
let clickCount = 0;
cards.forEach((card) => {
card.addEventListener("click", () => {
clickCount ++;
if (clickCount == 1) {
clickTimer = setTimeout(() => {
clickCount = 0;
//single click functionality here
card.classList.add("clicked");
if (counter === 0) {
firstSelection = card.getAttribute("meme");
counter++;
} else {
secondSelection = card.getAttribute("meme");
counter = 0;
if (firstSelection === secondSelection) {
const correctCards = document.querySelectorAll(".card[meme='" + firstSelection + "']");
score.innerHTML = parseInt(score.innerHTML) + 1
if (score.innerHTML >= 8)
correctCards[0].classList.add("checked");
correctCards[0].classList.remove("clicked");
correctCards[1].classList.add("checked");
correctCards[1].classList.remove("clicked");
} else {
const incorrectCards = document.querySelectorAll(".card.clicked");
incorrectCards[0].classList.add("red");
incorrectCards[1].classList.add("red");
setTimeout(() => {
incorrectCards[0].classList.remove("red");
incorrectCards[0].classList.remove("clicked");
incorrectCards[1].classList.remove("red");
incorrectCards[1].classList.remove("clicked");
}, 600);
}
}
}, 300);
} else if (clickCount == 2) {
clearTimeout(clickTimer);
clickCount = 0;
console.log("This was a double click!");
}
});
});

setstate isn't setting value to state

i'm setting my state after calculating it in mouseup and mouse leave event but it's not updating it how to solve in mouseup and mouse leave
Cannot update during an existing state transition (such as within render). Render methods should be a pure function of props and state.
onMouseMove = (e) => {
if (!this.isDown) {
return;
}
e.preventDefault();
var x = e.pageX - this.slider.current.offsetLeft;
var walk = x - this.startX;
this.startX = x;
var z = walk;
var finalValue = this.state.left + (z / 3);
finalValue = Math.floor(finalValue * 100) / 100;
this.setState({ left: finalValue }, () => { });
this.setState({ percent: false })
}
onMouseLeave = () => {
this.isDown = false;
var left = this.state.left;
for (let i = 0; i < 6; i++) {
this.el = 306*[i]
console.log(this.el);
if (left<=this.el) {
this.setState({left:this.el},()=>{})
// return
}
console.log(this.state.left);
}
}
onMouseUp = () => {
this.isDown = false;
this.slider.current.style.cursor = 'pointer';
var left = this.state.left;
for (let i = 0; i < 6; i++) {
this.el = 306*[i]
console.log(this.el);
if (left<=this.el) {
this.setState({left:this.el},()=>{})
// return
}
console.log(this.state.left);
}
}
render() {
return (
<div className="slider-wrapper" >
<div onMouseDown={this.onMouseDown}
style={this.state.percent ? this.goLeftPercent() : this.mouseMove()}
onMouseUp={this.onMouseUp} onMouseLeave={this.onMouseLeave}
onMouseMove={this.onMouseMove} ref={this.slider} className="slider-container">
)
}
If I understand correctly you can try the below changes.
Constructor
constructor() {
super();
this.onMouseLeave = this.onMouseLeave.bind(this);
this.onMouseUp = this.onMouseUp.bind(this);
}
Render()
<li onMouseUp={this.onMouseUp} onMouseLeave={this.onMouseLeave} >

Run function only once until onmouseout

I have an anchor tag that plays a sound everytime the link is hovered:
<a onmouseenter="playAudio();">LINK</a>
However, when hovered, the link creates some characters that, if I keep moving the mouse inside the element, it keeps playing the sound over and over again.
Is there a way to play the onmouseenter function only once until it has detected the event onmouseout?
I've tried adding:
<a onmouseenter="playAudio();this.onmouseenter = null;">LINK</a>
but then it only plays the sound once.
Here goes the TextScramble animation function:
// ——————————————————————————————————————————————————
// TextScramble
// ——————————————————————————————————————————————————
class TextScramble {
constructor(el) {
this.el = el
this.chars = '!<>-_\\/[]{}—=+*^?#________'
this.update = this.update.bind(this)
}
setText(newText) {
const oldText = this.el.innerText
const length = Math.max(oldText.length, newText.length)
const promise = new Promise((resolve) => this.resolve = resolve)
this.queue = []
for (let i = 0; i < length; i++) {
const from = oldText[i] || ''
const to = newText[i] || ''
const start = Math.floor(Math.random() * 40)
const end = start + Math.floor(Math.random() * 40)
this.queue.push({
from,
to,
start,
end
})
}
cancelAnimationFrame(this.frameRequest)
this.frame = 0
this.update()
return promise
}
update() {
let output = ''
let complete = 0
for (let i = 0, n = this.queue.length; i < n; i++) {
let {
from,
to,
start,
end,
char
} = this.queue[i]
if (this.frame >= end) {
complete++
output += to
} else if (this.frame >= start) {
if (!char || Math.random() < 0.28) {
char = this.randomChar()
this.queue[i].char = char
}
output += `<span class="dud">${char}</span>`
} else {
output += from
}
}
this.el.innerHTML = output
if (complete === this.queue.length) {
this.resolve()
} else {
this.frameRequest = requestAnimationFrame(this.update)
this.frame++
}
}
randomChar() {
return this.chars[Math.floor(Math.random() * this.chars.length)]
}
}
// ——————————————————————————————————————————————————
// Configuration
// ——————————————————————————————————————————————————
const phrases = [
'MAIN_HUB'
]
const el = document.querySelector('.link_mainhub')
const fx = new TextScramble(el)
let counter = 0
const next = () => {
fx.setText(phrases[counter]).then(() => {});
}
el.addEventListener('mouseenter', next);
<a class="link_mainhub" onmouseenter="playAudio();">LINK</a>
Thanks.
Set a variable when you start playing the audio, and check for this before playing it again. Have the animation unset the variable when it's done.
function audioPlaying = false;
function playAudio() {
if (!audioPlaying) {
audioPlaying = true;
audioEl.play();
}
}
const next = () => {
fx.setText(phrases[counter]).then(() => {
audioPlaying = false;
});
}

Class button timeout

So i have a class that has some functions that are making a carousel work. But pressing the next button fast deletes the previous animation and starts the next so i want to make the button wait for the animation to end. The animation inside css is 0.6 seconds but the timeous i set inside goNext functions is completely ignored when i fast click the button. What am I doing wrong here?
index.js
let carousel = document.getElementById("carousel");
let seats = document.querySelectorAll("ul > li");
if (seats.length === 1)
carousel.style.left = 0;
class SLID {
constructor() {
this.nextDisable = true;
this.changeNextDisable = this.changeNextDisable.bind(this);
}
changeNextDisable() {
this.nextDisable = false;
}
goToNext() {
if(this.nextDisable===false){
this.nextDisable = true;
var el, i, j, new_seat, ref;
el = document.querySelector("ul > li.is-ref");
el.classList.remove('is-ref');
new_seat = el.nextElementSibling || seats[0];
new_seat.classList.add('is-ref');
new_seat.style.order = 1;
for (i = j = 2, ref = seats.length; (2 <= ref ? j <= ref : j >= ref); i = 2 <= ref ? ++j : --j) {
new_seat = new_seat.nextElementSibling || seats[0];
new_seat.style.order = i;
}
carousel.classList.remove('toPrev');
carousel.classList.add('toNext');
carousel.classList.remove('is-set');
return setTimeout(()=> {
this.changeNextDisable();
carousel.classList.add('is-set');
}, 60);
}
goToPrev() {
var el, i, j, new_seat, ref;
el = document.querySelector("ul > li.is-ref");
el.classList.remove('is-ref');
new_seat = el.previousElementSibling || seats[seats.length - 1];
new_seat.classList.add('is-ref');
new_seat.style.order = 1;
for (i = j = 2, ref = seats.length; (2 <= ref ? j <= ref : j >= ref); i = 2 <= ref ? ++j : --j) {
new_seat = new_seat.nextElementSibling || seats[0];
new_seat.style.order = i;
}
carousel.classList.remove('toNext');
carousel.classList.add('toPrev');
carousel.classList.remove('is-set');
return setTimeout((function () {
return carousel.classList.add('is-set');
}), 50);
}
}
}
let s = new SLID();
document.getElementById("nextButton").addEventListener("click", () => {
s.goToNext();
});
document.getElementById("prevButton").addEventListener("click", () => {
s.goToPrev();
});
According to your animation type (transition or animation) you can replace
return setTimeout(()=> {
this.changeNextDisable();
carousel.classList.add('is-set');
}, 60);
(and trying avoid it) to:
carousel.addEventListener("animationend", () => {
this.changeNextDisable();
carousel.classList.add('is-set');
}, {
once: true,
});
or
carousel.addEventListener("transitionend", () => {
this.changeNextDisable();
carousel.classList.add('is-set');
}, {
once: true,
});
same thing for goToPrev method.
You tell us that the CSS animation has a duration of 0.6 seconds, which is 600 milliseconds, not 60 or 50 milliseconds, which is what you set your setTimeout delay to.
So:
return setTimeout(()=> {
this.changeNextDisable();
carousel.classList.add('is-set');
}, 600);
// ^^^^
Having said that, you should look into listening to the transactionend event, as then you don't need to know how long the CSS transition takes.
That would look like this:
const done = () => {
carousel.removeEventListener("transactionend", done);
this.changeNextDisable();
carousel.classList.add('is-set');
}
return carousel.addEventListener("transactionend", done);

disable scrolling while scrolling

I am writting a code , which animates scroll of 100% body.height. Everything works fine , but i am trying to disable the scrolling while the animation last to prevent further unwanted behavior.
i am using this code
function animate(x) {
var start = new Date();
var id = setInterval(function (e) {
var timepassed = new Date() - start;
var progress = timepassed / x.duration;
if (progress > 1) {
progress = 1;
}
var delta = x.delta(progress);
x.step(delta);
if (progress == 1) {
clearInterval(id);
}
}, x.delay);
}
function fak(e) {
e.preventDefault();
return false;
}
function move(e) {
e.preventDefault();
var wheel = e.wheelDelta;
wheel = (wheel == 120) ? "-1" : "1";
var body_height = document.body.offsetHeight;
var scrollIt = body_height * wheel;
var page = window.pageYOffset;
animate({
delay: 10,
duration: 700,
delta: function (p) {
return p;
},
step: function (delta) {
window.scrollTo(0, page + (delta * scrollIt));
}
});
return false;
}
document.body.addEventListener("mousewheel", move, false);
document.body.addEventListener("DOMMouseScroll", move, false);
I tried to assign function fak , on mousewheel , mousescroll in interval and then restoring original assigment to them at the end using
function animate(x) {
var start = new Date();
var id = setInterval(function (e) {
document.body.addEventListener("mousewheel", fak, false);
document.body.addEventListener("DOMMouseScroll", fak, false);
var timepassed = new Date() - start;
var progress = timepassed / x.duration;
if (progress > 1) {
progress = 1;
}
var delta = x.delta(progress);
x.step(delta);
if (progress == 1) {
clearInterval(id);
document.body.addEventListener("mousewheel", move, false);
document.body.addEventListener("DOMMouseScroll", move, false);
}
}, x.delay);
}
But didnt work either. Live demo : http://jsfiddle.net/Trolstover/o2pvo2t8/ Did i overlook something?
i changed a bit on your code.
http://jsfiddle.net/o2pvo2t8/2/
just set a flag "running" while scrolling (at start of animate() ), and clear it at the end.
and execute mov only when no scrolling appears.
hope it helps.
var running;
function animate(x) {
running = 1;
var start = new Date();
var id = setInterval(function (e) {
var timepassed = new Date() - start;
var progress = timepassed / x.duration;
if (progress > 1) {
progress = 1;
}
var delta = x.delta(progress);
x.step(delta);
if (progress == 1) {
clearInterval(id);
running = 0;
}
}, x.delay);
}
function fak(e) {
e.preventDefault();
return false;
}
function move(e) {
e.preventDefault();
if (running==1) return;
var wheel = e.wheelDelta;
console.log(wheel);
wheel = (wheel == 120) ? "-1" : "1";
var body_height = document.body.offsetHeight;
var scrollIt = body_height * wheel;
var page = window.pageYOffset;
animate({
delay: 10,
duration: 700,
delta: function (p) {
return p;
},
step: function (delta) {
window.scrollTo(0, page + (delta * scrollIt));
}
});
return false;
}
document.body.addEventListener("mousewheel", move, false);
document.body.addEventListener("DOMMouseScroll", move, false);

Categories

Resources