Adding images to class with time intervale between each image - javascript

I'm trying to add stars (images) to a class with JS.
function putStars(){
if(test){
for(var i = 0; i < 5; i++){
var star = document.createElement("img");
star.src = "star.png";
var element = document.querySelector(".java");
element.append(star);
}
test = false;
}
}
So as you can see I add images to the class Java, but what I want to do is adding images but a waiting effect between each image and not just a block of 5 images.
I found the setTimeOut function but I'm not sut if it's the best way to do this.

You can basically replace your for-loop with setInterval like this to achieve a time delay between each iteration.
let i = 0;
const interval = setInterval(() => {
i++;
var star = document.createElement("img");
star.src = "star.png";
var element = document.querySelector(".java");
element.append(star);
if (i === 5) { clearInterval(interval); } // <- after 5 iterations clear the interval
}, 1000); // <- this 1000 is 1 sec. delay
Although you can move var element = document.querySelector(".java"); outside of the interval so that you don't search for it more than once since it is unnecessary.
let i = 0;
var element = document.querySelector(".java");
const interval = setInterval(() => {
i++;
var star = document.createElement("img");
star.src = "star.png";
element.append(star);
if (i === 5) { clearInterval(interval); } // <- after 5 iterations clear the interval
}, 1000); // <- this 1000 is 1 sec. delay

Use setinterval this way, so your images will most likely already be loaded before you append them to your element.
const listToAppend = [];
const element = document.querySelector(".java");
const start = () => {
let si = setInterval(()=>{
if(listToAppend.length === 0){
clearInterval(si);
return;
}
element.append(listToAppend.shift());
}, 1000);
}
function putStars(){
if(test){
for(var i = 0; i < 5; i++){
var star = document.createElement("img");
star.src = "star.png";
listToAppend.push(star);
}
start();
test = false;
}
}

Related

how to implement click logic

hi everyone!
i have a map with dots MAP which every 3 seconds shows a block with info
a function that is already in progress, and I want the function to stop when clicking on a point and display an infoblock for me(and i did it).
sorry in advance below is my code
// map with dots
var isActive = 0;
var isLoading = 1;
const count = document.querySelectorAll("[data-id]");//circle svg around dot
function removeClass() {
let infoCards = document.querySelectorAll("[data-info-id]");// info page name of the project
infoCards.forEach((el) => {
el.classList.remove("show");
});
}
function removeCircle() {
count.forEach((el) => {
el.style.display = "none";
});
}
function ready() {
function setAround(percent, idx) {
removeCircle();
let beforeElemIdx = idx === 0 ? count.length - 1 : idx - 1;
let beforeElem = document.querySelector(
'[data-id="' + beforeElemIdx + '"]'
);
let elem = document.querySelector('[data-id="' + idx + '"]');
elem.style.display = "block";
elem.classList.remove('active-circle');
beforeElem.style.display = "block";
const math = 2 * Math.PI * elem.r.baseVal.value;
elem.style.strokeDasharray = `${math} 1000`;
let a = math * (1 - percent / 100);
elem.style.strokeDashoffset = a;
if (percent >= 99.5) {
removeClass();
let infoShow = document.querySelector(`[data-info-id="${idx}"]`);
infoShow.classList.add("show");
isLoading++;
if (isLoading === count.length) {
isLoading = 0;
}
}
}
requestAnimationFrame(draw);
function draw(t) {
let idx = isLoading;
requestAnimationFrame(draw);
setAround((t / 30) % 100, idx);//timer 3sec
}
}
document.addEventListener("DOMContentLoaded", ready);
and i did this
var dots = document.querySelectorAll(".dota");
var infoCards = document.querySelectorAll("[data-info-id]");
let circle = document.querySelectorAll('[data-id]');
dots.forEach((el) => {
el.addEventListener('click', () => {
let idx = el.dataset.dota;
let circle = el.dataset.dota;
showInfo(idx);
addCircle(idx);
});
});
function showInfo(idx) {
removeClass();
let elem = document.querySelector(`[data-info-id='${idx}']`);
elem.classList.add('show');
}
function addCircle(idx) {
let circle = document.querySelector(`[data-id='${idx}']`);
circle.classList.add('active-circle');
}
and if u want my site pls dm me i'll send my github page
PUG CODE
TY ALL!
Have you tried making a condition into the drawing function that pauses it?
If it's paused you can call another function that will draw the info of the specific dot only once and then create a condition in which it will resume the drawing normally.
When I used drawing function I've simply added a bool variable that stored if paused or not in the recursive function.

How to create a screensaver in javascript

I want to create a screensaver in JavaScript but I don't know how can I set the time between the images,.
I have an Ajax call and I see if the time is, for example, 2s or 90s, but I don't know how to set that time between images, this is my code:
var cont = 0;
var time = 1000
setInterval(function() {
console.log(tiempo);
if(cont == imagenes.length){
return cont = 0;
}else{
var imagen = imagenes[cont].imagen;
$('#imgZona').attr('src', imagen);
var time = imagenes[cont].tiempoVisible;
finalTime = Number(time);
}
cont++;
}, Number(finalTime ));
but the time between images is always the same, 1000, how can I change it for the time that I receive in the Ajax call? Which is imagenes[cont].tiempoVisible
I cannot comment as I don't have enough reputation, but take a look at this fiddle
https://jsfiddle.net/kidino/4mbpR/
var mousetimeout;
var screensaver_active = false;
var idletime = 5;
function show_screensaver(){
$('#screensaver').fadeIn();
screensaver_active = true;
screensaver_animation();
}
function stop_screensaver(){
$('#screensaver').fadeOut();
screensaver_active = false;
}
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.round(Math.random() * 15)];
}
return color;
}
$(document).mousemove(function(){
clearTimeout(mousetimeout);
if (screensaver_active) {
stop_screensaver();
}
mousetimeout = setTimeout(function(){
show_screensaver();
}, 1000 * idletime); // 5 secs
});
function screensaver_animation(){
if (screensaver_active) {
$('#screensaver').animate(
{backgroundColor: getRandomColor()},
400,
screensaver_animation);
}
}
It will change background-color on idle mouse for 5 seconds, you can replace the code to change image, instead of background color.
Control set every timeout on each iteration.
var cont = 0;
var time = 1000
function next () {
console.log(tiempo);
if(cont == imagenes.length){
cont = 0;
}
var imagen = imagenes[cont].imagen;
$('#imgZona').attr('src', imagen);
cont++;
setTimeout(next, Number(imagenes[cont].tiempoVisible));
}
setTimeout(next, Number(initialTime));
Also I fixed a frindge condition.

How can I reuse a function properly?

I try to make 3 basic slideshow.
I made this code for the first one and wanted to use it on the other 2 as well with the New slideS() method and with some parameter changing.But it's not working,even the first function is'nt working if I put parameter in it.
Can somebody explain me why is this not working and how to fix it?Thanks beforehand!
var img = document.getElementById("asd");
var imgArr = ["1.jpg", "3.png", "3.png"];
var i = 0;
function slideS(a) {
a.src = imgArr[i];
if (i < imgArr.length - 1) {
i++;
} else {
i = 0;
}
setTimeout("slideS()", 1500);
}
slideS(img)
You could do something like this, using an object oriented approach:
function SlideShow(el, imagesArray, msDelay) {
this.el = el;
this.images = imagesArray;
this.delay = (msDelay) ? msDelay : 1000;
this.timer = null;
this.Run = function () {
var self = this;
var index = 0;
this.timer = setInterval(function(){
self.el.src = self.images[index++ % self.images.length];
}, this.delay);
}
this.Stop = function() {
this.timer = null;
}
}
var img = document.getElementById("asd");
var imgArr = ["1.jpg", "3.png", "3.png"];
var delay = 1500;
var ss = new SlideShow(img, imgArr, delay);
ss.Run();
...
ss.Stop();
Would that work for you? Then you are using pure functions and an object that can be used to start, stop, and manage any slide show.
I think you want like:
Remove setTimeout. And use setInterval:
setInterval(function(){
slideS(img)
},1500)
You could use a closure over the element and the array and use setInterval instead of setTimeout.
function slide(id, array) {
function swap() {
image.src = array[i];
i++;
i %= array.length;
}
var image = document.getElementById(id),
i = 0;
setInterval(swap, 1500);
}
slide('image1', ['http://lorempixel.com/400/200/', 'http://lorempixel.com/400/200/', 'http://lorempixel.com/400/200/']);
<image id="image1"></image>
I assume it works when the function doesn't take a parameter?
Then, the reason it would work with no parameter, but stop working with a parameter, is that the setTimeout tries to recursively call the function but doesn't pass a parameter. So you'd change that to
setTimeout(() => {slideS(a);}, 1500);
But then when you try to run multiple instances of this concurrently, you'll get into trouble because your'e using global variables. You'll need to use something more local (perhaps closures?) for your lcv, for example.
try this... you are making mistake at some places
var img = document.getElementById("asd");
var imgArr = ["1.jpg", "3.png", "3.png"];
var i = 0;
function slideS(a) {
a.src = imgArr[i];
if (i < imgArr.length - 1) {
i++;
} else {
i = 0;
}
setTimeout(() => slideS(a), 1500);
/* you need to pass function to setTimeout and pass refrence of image that's 'a' */
// or use function instead of arrow function
setTimeout(function() { slides(a) }, 1500);
}
slideS(img)
hope this helps..
You have to use setInterval instead of setTimeout
var img = document.getElementById("asd");
var imgArr = ["https://i.stack.imgur.com/lgt0W.png", "https://i.stack.imgur.com/X0fKm.png", "https://i.stack.imgur.com/YfPSD.png"];
var i = 0;
function slideS(a) {
a.src = imgArr[i];
if (i < imgArr.length - 1) {
i++;
} else {
i = 0;
}
}
slideS(img); //initial call to start it without having to wait for 1500 ms to pass
setInterval(function() {
slideS(img);
}, 1500);
<img id="asd">

pausing function on hover

I have a function written in javascript that allows me to scroll through an array of images iterated at a certain interval, now I would like to add some more functionality to it by pausing the rotation when I hover over any of the images in the array.
Javascript
(function() {
var rotator = document.getElementById('bigImage');
var imageDir = '../images/headers/';
var delayInSeconds = 5;
var images = ['ImageOne.png', 'ImageTwo.png', 'ImageThree.png', 'ImageFour.png',
'ImageFive.png',
'ImageSix.png'];
var num = 0;
var changeImage = function() {
var len = images.length;
bigImage.src = imageDir + images[num++];
if (num == len) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 1000);
})();​
You could store the id returned from setInterval, and pass it to clearInterval when the image is hovered over.
So, on mouse over, you clear, and on mouse out you set it going again.
Hope that helps!
Use jQuery:
var rotationRunning = true;
var changeImage = function() {
if (rotationRunning) {
var len = images.length;
rotator.src = imageDir + images[num++];
if (num == len)
num = 0;
}
}
};
$(rotator).hover(
function() { rotationRunning = false; },
function() { rotationRunning = true; }
);

How to fade in divs in sequence with Javascript (jQuery)?

What i want is to fade in my sidebar boxes after each other on page load by adding a class.
I have tried the following:
var a = $(".sidebar-box"), delayTime = 2000;
for(var i = 0; i < a.length; i++) {
setTimeout(function(
var ai = $(a[i]);
ai.addClass("fade in");
console.log(ai);
), delayTime);
console.log(delayTime);
delayTime += 2000;
}
The problem is, by the time the class gets added the first time, i already is 4, so the class only gets added to the last box, when actually it should be added to the first one.
You need to create a separate function so that variable i is copied each time:
var a = $(".sidebar-box"), delayTime = 2000;
var func = function(i)
{
setTimeout(function() {
var ai = $(a[i]);
ai.addClass("fade in");
}, delayTime);
}
for(var i = 0; i < a.length; i++) {
func(i);
delayTime += 2000;
}
Instead of adding a class and animating via CSS, if you are okay with using jQuery's fadeIn() method, you can have it like:
var a = $(".sidebar-box"), delayTime = 2000, i = 0;
function animateSideBar() {
if(i >= a.length) return;
// call fadeIn, and pass this function itself as the completion callback
$(a[i]).fadeIn(delayTime, animateSideBar);
i++;
}
animateSideBar(); // start it

Categories

Resources