Slider's width isn't updating without refreshing the page - javascript

When the page resizes "sliderContainerWidth" sticks with the same width, but if i refresh the page on any width its works fine.. I've tried using resize event as u guys can see i couldn't fixed it. It's not updating without refreshing the page..
let counter = 0;
const back = document.querySelector("#back");
const next = document.querySelector("#next");
const sliderContainer = document.querySelector("#slider-container");
var sliderContainerWidth =
document.querySelector("#slider-container").clientWidth;
const slider = document.querySelector("#slider");
const max = document.querySelectorAll(".slide").length - 1;
window.addEventListener("resize", sliderFunc);
next.addEventListener("click", sliderFunc);
function sliderFunc() {
if (counter < max) {
counter++;
slider.style.left = "-" + sliderContainerWidth * counter + "px";
} else {
counter = 0;
slider.style.left = "-" + sliderContainerWidth * counter + "px";
}
}
window.addEventListener("resize", backEvent);
back.addEventListener("click", backEvent);
function backEvent() {
if (counter >= 1) {
counter--;
slider.style.left = "-" + sliderContainerWidth * counter + "px";
} else {
counter = max;
slider.style.left = "-" + sliderContainerWidth * counter + "px";
}
}
//mousevnt
let timer = setInterval(sliderFunc, 12000);
sliderContainer.addEventListener("mouseover", () => {
clearInterval(timer);
});
sliderContainer.addEventListener("mouseout", () => {
timer = setInterval(sliderFunc, 12000);
});
//mousevnt

If I'm understanding your issue correctly, you need to update the value inside of your event functions. It will not update if it's not getting set. The reason it only gets set when you refresh is because all the top-level javascript gets read when the page first loads.
function sliderFunc() {
if (counter < max) {
counter++;
slider.style.left = "-" + sliderContainerWidth * counter + "px";
} else {
counter = 0;
slider.style.left = "-" + sliderContainerWidth * counter + "px";
}
sliderContainerWidth = document.querySelector("#slider-container").clientWidth;
}

Related

Reset slider JavaScript upon window resize (NOT jQuery)

I do not want a jQuery solution.
The problem: When my page is resized, the slides in the slider are positioned incorrectly.
I'm open to any solution, but my guess is I need to reset the JS for my heroSlider upon window resizing.
Here's the JSfiddle https://jsfiddle.net/3ou0ja4c/
// HERO SLIDER
const heroSlider = () => {
const carouselSlide = document.querySelector('.carousel-slide')
let carouselImages = document.querySelectorAll('.carousel-slide .slide-bg')
// Buttons
const prevBtn = document.querySelector('#prevBtn')
const nextBtn = document.querySelector('#nextBtn')
// Timer
let interval = setInterval( () => rotateSlide(), 5000)
// Counter
let counter = 1
let size = carouselImages[0].clientWidth
carouselSlide.style.transform = 'translateX(' + (-size * counter ) + 'px)'
const rotateSlide = () => {
if (counter >= carouselImages.length -1) return
carouselSlide.style.transition = "transform 0.4s ease-in-out"
counter++
carouselSlide.style.transform = 'translateX(' + (-size * counter ) + 'px)'
}
// Button Listeners
nextBtn.addEventListener('click',() => {
clearInterval(interval)
rotateSlide()
})
prevBtn.addEventListener('click', () => {
if (counter <= 0) return
carouselSlide.style.transition = "transform 0.4s ease-in-out"
counter--
carouselSlide.style.transform = 'translateX(' + (-size * counter ) + 'px)'
clearInterval(interval)
})
carouselSlide.addEventListener('transitionend', () => {
// If image is a clone, jump to original image with no animation
if (carouselImages[counter].id === 'lastClone'){
carouselSlide.style.transition = "none"
counter = carouselImages.length - 2
carouselSlide.style.transform = 'translateX(' + (-size * counter ) + 'px)'
}
if (carouselImages[counter].id === 'firstClone'){
carouselSlide.style.transition = "none"
counter = carouselImages.length - counter
carouselSlide.style.transform = 'translateX(' + (-size * counter ) + 'px)'
}
})
}
heroSlider()
It doesn't look great on the fiddle, but you can still see it breaks upon being resized. It works on all window sizes, so long as you refresh the page, but I DO NOT want the page to refresh upon all resizes.
You can see the real deal over at http://www.justinkwapich.com/JH/index.html
Any help is really appreciated, thank you!
In your heroSlider() function you can add an event listener to check if the window is resized and create a callback where you update the size variable and anything else that depends on this size:
let counter = 1
let size = carouselImages[0].clientWidth
window.addEventListener('resize', () => {
size = carouselImages[0].clientWidth
carouselSlide.style.transform = 'translateX(' + (-size * counter ) + 'px)'
// ...
// ...
})

My script needs page refresh for it to run

Every time I load my page for the first time my script does not load, I need to refresh the page at least 3 times for it to run. How can I make my script run without a page refresh? This particular script is in BABEL.
'use strict';
var deg = 0;
var index = 0;
$('#' + index).css('opacity', '1');
$('.navbar').contextmenu(function () {
return false;
});
$('.navbar').on('mousewheel', function (e) {
var move = -60;
var nextIndex = nextIndex = (index + 1) % 6;
if (e.originalEvent.wheelDelta / 120 <= 0) {
// wheel up
move = 60;
nextIndex = index -1 < 0 ? 5 : index - 1;
}
$('.scroll-list').css('transform', 'rotateX(' + (deg + move) + 'deg)');
$('#' + index).css('opacity', '0.01');
$('#' + nextIndex).css('opacity', '1');
index = nextIndex;
deg = deg + move;
event.stopPropagation();
console.timeEnd('cache');
});
And what if you wrapped your code inside a window.onload function?
window.onload = function() {
// your code
}
Your code will only run when the html document is "ready" and fully loaded.
You are running Javascript that depends on page elements and the javascript is executed before the elements are on the page;
Wrapp all your code inside document.ready function
$(document).ready(function () {
var deg = 0;
var index = 0;
$('#' + index).css('opacity', '1');
$('.navbar').contextmenu(function () {
return false;
});
$('.navbar').on('mousewheel', function (e) {
var move = -60;
var nextIndex = nextIndex = (index + 1) % 6;
if (e.originalEvent.wheelDelta / 120 <= 0) {
// wheel up
move = 60;
nextIndex = index - 1 < 0 ? 5 : index - 1;
}
$('.scroll-list').css('transform', 'rotateX(' + (deg + move) + 'deg)');
$('#' + index).css('opacity', '0.01');
$('#' + nextIndex).css('opacity', '1');
index = nextIndex;
deg = deg + move;
event.stopPropagation();
console.timeEnd('cache');
});
});
Wrap your code in ready function, so that your JavaScript executes after DOM is loaded.

Can`t move element on setInterval function

I have a small image that may change his background-position-x on hover event. And stop moving on mouseleave. But even with setInterval my fuctuin run just 1 time. Here`s my code. Could someone help me?
let wave = document.querySelector('.wave');
wave.onmouseover = moveWave();
function moveWave() {
setInterval(function () {
wave.style.backgroundPositionX += 10 + 'px';
}, 100)
}
The problem is with below line:
wave.style.backgroundPositionX += 10 + 'px';
After first call, the wave.style.backgroundPositionX will be:
10px
After next call, the wave.style.backgroundPositionX will be:
10px10px -> which is incorrect format.
The right way is:
var count = 10;
let wave = document.querySelector('.wave');
wave.onmouseover = moveWave();
function moveWave() {
setInterval(function () {
count += 10;
wave.style.backgroundPositionX = count + 'px';
}, 100)
}
var count = 10;
let wave = document.querySelector('.wave');
wave.onmouseover = moveWave();
wave.onmouseleave = moveLeave();
var id;
function moveWave() {
id = setInterval(function () {
count += 10;
wave.style.backgroundPositionX = count + 'px';
}, 100)
}
function moveLeave() {
clearInterval(id);
}

Why won't this clearInterval work?

I'm making a race where two images move to the right a random number of px's but they won't stop with the clear interval, the alert "stop" works. I'm using a red and green picture with changing z-indexes like a stoplight for the user to start and stop the race.
<script type="text/javascript">
var ship = 0;
var ufo = 0;
function random()
{
var rand = Math.floor((Math.random() * 15) + 1);
var rand2 = Math.floor((Math.random() * 15) + 1);
ship = ship + rand;
ufo = ufo + rand2;
document.getElementById("ufo").style.left = ufo + 'px';
document.getElementById("spaceship").style.left = ship + 'px';
}
function start()
{
if(document.getElementById("red").style.zIndex == 1)
{
document.getElementById("red").style.zIndex = "0";
alert("go");
var timer = setInterval(function() {random()},1000);
}
else
{
document.getElementById("green").style.zIndex = "0";
document.getElementById("red").style.zIndex = "1";
clearInterval(timer);
alert("stop");
}
}
</script>
Because var timer only exists within the if statement. You need to move it outside of the start() function, like this:
var timer;
function start()
{
if(document.getElementById("red").style.zIndex == 1)
{
document.getElementById("red").style.zIndex = "0";
alert("go");
timer = setInterval(function() {random()},1000);
}
else
{
document.getElementById("green").style.zIndex = "0";
document.getElementById("red").style.zIndex = "1";
clearInterval(timer);
alert("stop");
}
}

Creating a game in JQuery

I am trying to create a simple game on a webpage.
The game should be like this:
The web page should display at random times images placed in random positions on the browser window.
Each image lasts on the browser window for a short period of time and then it disappears.
If the user clicks an image before it disappears, he/she gets a point.
The game ends when the user wins 10 points.
So far I managed to display all elements on a page at random positions, then delete them, and display them again.
Right now I am having problems with the count of each click.
JavaScript
$(document).ready(function () {
timeOut();
});
function timeOut() {
setInterval(function () {
deleteImages();
createImages();
}, 3000);
}
function createImages() {
var myarray = ["img/Angel.gif", "img/Angry.gif", "img/BigSmile.gif",
"img/Confused.gif", "img/Cool.gif", "img/Crying.gif",
"img/Eyebrow.gif", "img/Goofy.gif", "img/Happy.gif"];
var count = 0;
var div;
for (var i = 0; i < 9; i++) {
var randPos = 0 + Math.floor(Math.random() * 500);
this.img = document.createElement("img");
div = document.createElement("div");
$("div").attr("id", "div" + i);
var randNew = 0 + Math.floor(Math.random() * (5));
var rand = 0 + Math.floor(Math.random() * (9 - count));
this.img.src = myarray[rand];
$('#div' + i).css("left", randPosition());
$('#div' + i).css("right", randPosition());
$('#div' + i).css("top", randPosition());
$('#div' + i).css("bottom", randPosition());
$('#div' + i).css("position", "relative");
$('#div' + i).show();
div.appendChild(this.img);
$("body").prepend(div);
myarray.splice(rand, 1);
count++;
}
//setTimeout(function(){ jQuery("div").hide(); }, 3000);
}
function deleteImages() {
$("div").remove();
}
function randPosition() {
return 0 + Math.floor(Math.random() * 500);
}
$(function () {
$("div").click(function (e) {
var offset = $(this).offset();
var relativeX = (e.pageX - offset.left);
var relativeY = (e.pageY - offset.top);
alert("X: " + relativeX + " Y: " + relativeY);
});
});
css
.active-div{
position:relative;
}
.menu-div{
position:absolute;
top:0;
right:0;
display:none;
}
Use a counter and increment when you click an image:
var count = 0;
count++;
Also you need to reapply the click event because you are recreating new elements instead of moving the already created ones:
Call this:
$("div").click(function(e) {
var offset = $(this).offset();
var relativeX = (e.pageX - offset.left);
var relativeY = (e.pageY - offset.top);
});
after createImages function like so:
var count = 0;
var holder;
$(document).ready(function(){
timeOut();
});
function addOnClicks() {
$("div").on('click',function(e) {
var offset = $(this).offset();
var relativeX = (e.pageX - offset.left);
var relativeY = (e.pageY - offset.top);
count++;
if(count >= 10)
{
deleteImages();
clearInterval(holder);
alert("Game Over");
}
});
}
function timeOut(){
holder = setInterval(function(){deleteImages();createImages();addOnClicks(); }, 3000);
}
function createImages(){
var myarray=["img/Angel.gif","img/Angry.gif","img/BigSmile.gif",
"img/Confused.gif","img/Cool.gif","img/Crying.gif",
"img/Eyebrow.gif","img/Goofy.gif","img/Happy.gif"
];
var count=0;
var div;
for (var i = 0; i < 9; i++) {
var randPos = 0 + Math.floor(Math.random() * 500);
this.img = document.createElement("img");
div = document.createElement("div");
$("div").attr("id","div"+i);
var randNew = 0 + Math.floor(Math.random() * (5));
var rand = 0 + Math.floor(Math.random() * (9-count));
this.img.src = myarray[rand];
$('#div'+i).css("left", randPosition());
$('#div'+i).css("right",randPosition());
$('#div'+i).css("top",randPosition());
$('#div'+i).css("bottom",randPosition());
$('#div'+i).css("position","relative");
$('#div'+i).show();
div.appendChild(this.img);
$("body").prepend(div);
myarray.splice(rand,1);
count++;
}
//setTimeout(function(){ jQuery("div").hide(); }, 3000);
}
function deleteImages(){
$("div").remove();
}
function randPosition(){
return 0 + Math.floor(Math.random() * 500);
}
.active-div{
position:relative;
}
.menu-div{
position:absolute;
top:0;
right:0;
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Use an incremented variable like so:
$(function() {
var click_count = 0;
$("div").click(function(e) {
click_count++;
});
});

Categories

Resources