Activates javascript after 'x' seconds - javascript

Is it possible that the javascript automatically activates after 8 seconds when a user is not using the link, so that it continues every 8 seconds, from Q1 to Q2, Q3 etc
JAVASCRIPT:
function laatZien(divID) {
var tabs = ["Q1", "Q2", "Q3"];
for(var i in tabs)
{ if (tabs[i] != divID)
{
document.getElementById(tabs[i]).className = "verstopt"; b
} }
var item = document.getElementById(divID);
if(item.className=="verstopt") {
item.className = "zichtbaar"
} else {
item.className = "zichtbaar"
}
}
HTML:
<div id="Q1" class="zichtbaar">
Next (Q2)
</div>
<div id="Q2" class="verstopt">
Next (Q3)
</div>
<div id="Q3" class="verstopt">
Back
</div>
CSS:
#Q1.verstopt, #Q2.verstopt, #Q3.verstopt{
display: none;
}
#Q1.zichtbaar, #Q2.zichtbaar, #Q3.zichtbaar{
display: block;
}

simply use the setInterval function provided by javascript and call your method every 8000ms.
setInterval(function(){ laatZien(element) }, 8000);
The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds).
here is a little fiddle for you:
var i = 2;
setInterval(function(){
$('div').removeClass('is_active');
$('.q'+i).addClass('is_active');
if(i == 3) {i = 0;}
i++;
},8000);
.is_active {
display: block;
}
div {display: none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="q1 is_active">Test 1</div>
<div class="q2">Test 2</div>
<div class="q3">Test 3</div>

You can use this function:
var timerId = setInterval(function() {
alert("tick");
}, 2000);
setTimeout(function() {
clearInterval(timerId);
alert('tick');
}, 5000);

Related

Animation and transition property with setTimeout() function

I'm fairly new to JS, and I'm trying to make a simple text slide animation. However, when the animation event is activated the first time, the transition property doesn't apply. Every time after that it works fine.
So I'm struggling with the first execution of the slide animation.
Here is the code:
function slide_animation(direction){
// Init
let text = document.querySelector(".story .box .right-part .text");
let text_html = text.innerHTML;
let text_slide = [
"Text n°1",
'Text n°2',
'Text n°3'
];
let current_slide = 0;
// Looking for the current_slide
for(let i=0;i<text_slide.length;i++){
if (text_slide[i]==text_html){current_slide = i};
}
// Calculating the next slide position
if (direction=='right'){
if (current_slide >= text_slide.length-1){
current_slide = 0;
}
else {current_slide+=1;}
}
else {
if (current_slide <= 0){
current_slide = text_slide.length-1;
}
else {
current_slide = current_slide-=1;
}
}
// Animation
setTimeout(()=>{
text.style.transition = '0.5s';
text.style.opacity = 0;
text.style.left = '100px';
},250);
setTimeout(()=>{
text.innerHTML = text_slide[current_slide];
text.style.opacity = 1;
text.style.left = '0px';
},750)
}
.story .box .right-part .text-container .text {
line-height: 1.25;
position: relative;
}
<div class="box">
<div class="left-part">
<div class="text-container">
<p class="text">
<span class="text-padding fontsize-md">----</span>
</p>
</div>
<div class="buttons-container">
<button class="backward" onclick="slide_animation('left')"></button>
<button class="forward" onclick="slide_animation('right')"></button>
</div>
</div>
<div class="right-part">
<div class="text-container">
<p class="text fontsize-sm">Text n°1</p>
</div>
</div>
</div>
Anyway , it is fixed. I added another setTimeOut that did nothing really useful on the text , i placed it just before the others setTimeOut and it seems to work out properly.
Here is what is inserted :
setTimeout(()=>{
text.style.left=0;
},0)

multiple carousel maximum callstack exceeded on single page Jquery/Vanilla Javascript

So I'm trying to implement an infinite autoplay multiple carousel using Jquery.
I have created two different carousel blocks on same page
this is the body of the page
<div class="rotating_block">
<div class="block one"></div>
<div class="block two"></div>
<div class="block three"></div>
</div>
<br>
<div class="rotating_block">
<div class="block one"></div>
<div class="block two"></div>
<div class="block three"></div>
</div>
CSS for the same
.rotating_block {
display: flex;
}
.one {
background: red;
height: 100px;
width: 100px;
}
.two {
background: green;
height: 100px;
width: 100px;
}
.three {
background: blue;
height: 100px;
width: 100px;
}
In JS i've created slideIndex array and childrens (blocks) array for each carousel
slideIndex[n] stores current slide number to show while
childrens[n] stores array of blocks/childrens
For each parent div '.rotating_block' I'm storing its slideIndex and its children in those arrays and performing the carousel function.
At the end I'm calling for setTimeout so as to run the function once again every five seconds and change the slide to give carousel like effect the problem is I'm getting max call exceeded stack / console getting logged every second multiple times
var slideIndex = [];
var childrens = [];
$(".rotating_block").each(function (index) {
slideIndex[index] = 0;
childrens[index] = $(this).find(".block");
function carousel(children, slideIndex) {
console.log('hello world');
for (let i = 0; i < children.length; i++) {
$(children[i]).hide();
}
if (slideIndex > children.length) {
slideIndex = 1;
}
$(children[slideIndex - 1]).show();
setTimeout(carousel(children, slideIndex), 5000);
}
carousel(childrens[index], slideIndex[index]);
});
link to pen
The problem is that you are passing the function carousel with parameters which is actually calling the function.
setTimeout(carousel(children, slideIndex), 5000);
To solve this, pass an arrow function to setTimeout
setTimeout(() => carousel(children, slideIndex), 5000);
EDIT
Also, you forgot to increment the slideIndex value:
var slideIndex = [];
var childrens = [];
$(".rotating_block").each(function (index) {
slideIndex[index] = 0;
childrens[index] = $(this).find(".block");
function carousel(children, slideIndex) {
console.log(slideIndex);
for (let i = 0; i < children.length; i++) {
$(children[i]).hide();
}
//////////////////////
slideIndex++;
//////////////////////
if (slideIndex > children.length) {
slideIndex = 1;
}
$(children[slideIndex - 1]).show();
setTimeout(() => carousel(children, slideIndex), 5000);
}
carousel(childrens[index], slideIndex[index]);
});

Showing an element for 5 seconds, then hide and show next element

This is what I've tried so far, but it just shows all the elements at once:
i1 = document.getElementById('img_1');
i2 = document.getElementById('img_2');
i3 = document.getElementById('img_3');
i4 = document.getElementById('img_4');
i5 = document.getElementById('img_5');
myarr = [i1,i2,i3,i4,i5];
for (i=0; i<myarr.length;i++) {
$(myarr[i]).show().delay(5000).fadeOut();
}
I assume you are trying to achieve an endless loop.
I think you should use interval in that case, and do fadeOut/fadeIn of elements.
i1 = document.getElementById('img_1');
i2 = document.getElementById('img_2');
i3 = document.getElementById('img_3');
i4 = document.getElementById('img_4');
i5 = document.getElementById('img_5');
let myarr = [i1, i2, i3, i4, i5];
let active = 1;
setInterval(() => {
$(myarr[active - 1]).fadeOut(500)
if (active >= myarr.length) {
active = 0
}
setTimeout(() => {
$(myarr[active]).fadeIn(500);
active = active + 1;
}, 500)
}, 5000)
What this does, is updates elements every 5 sec to next element, if it reached the end, it resets it to zero.
Checkout this fiddle
You can use async and await.
Another this you can improve is that. You can add same class to all images you want to show in series. If you want to select all by id you can use Attribute Selectors.
const myarr = document.querySelectorAll('img[id^=img]');
I have used same class rather than id
const arr = [...document.querySelectorAll('.test')];
(async function(){
for (let i=0; i<arr.length;i++) {
await new Promise(res => {
setTimeout(() => {
$(arr[i]).show().fadeOut();
res();
},2000)
})
}
})()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="test">Test 1</div>
<div class="test">Test 2</div>
<div class="test">Test 3</div>
let count = 1;
setInterval(()=>{
document.querySelectorAll("*[id*='img_']").forEach((elem)=> elem.style.display="none");
document.getElementById(`img_${count}`).style.display="";
if(count<4) count++;
else count = 1;
},1000)
<div id="img_1">Image 1</div>
<div id="img_2" style="display:none">Image 2</div>
<div id="img_3" style="display:none">Image 3</div>
<div id="img_4" style="display:none">Image 4</div>
Vanilla Javascript solution!
You forgot to show your element after fadeOut. Here you can achieve it:
// show first element
$('img').eq(0).show();
$('img').each(function () {
// your delay
$('img').delay(5000).fadeOut();
// make sure next element is image
if ($(this).next()[0].tagName === 'IMG') {
// show next element
$(this).next().fadeIn();
}
});
img {
display: none;
position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://picsum.photos/id/5/50" />
<img src="https://picsum.photos/id/10/50" />
<img src="https://picsum.photos/id/30/50" />
<img src="https://picsum.photos/id/0/50" />
<img src="https://picsum.photos/id/150/50" />
<img src="https://picsum.photos/id/1000/50" />
var basicVal =0;
$(document).ready(function(){
$('.wrapper img').eq( basicVal ).show();
var setTime =setInterval(function(){
if( basicVal < $('.wrapper img').length - 1){
$('.wrapper img').eq(basicVal ).hide();
basicVal++;
$('.wrapper img').eq(basicVal).show();
}else{
clearTimeout(setTime);
}
console.log();
}, 5000);
});
.wrapper{
width: 100%;
float: left;
}
.wrapper img{
width: 50%;
height: 300px;
object-fit: cover;
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<img src="https://images.pexels.com/photos/34950/pexels-photo.jpg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="">
<img src="http://www.desktopwallpaperhd.net/wallpapers/0/4/landscapes-wallpaper-fengguangbizhi-fengjingbizhi-picture-image-1316.jpg" alt="">
<img src="http://trustbanksuriname.com/wp-content/uploads/2019/04/pony-picture-guide-to-native-pony-breeds-little-pony-cartoon-pictures.jpg" alt="">
<img src="https://www.bigfoto.com/stones-background.jpg" alt="">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQulscf1nNOpaI1tElZgKTTSAl_ZcL_i1VwLDojgKzqjSTMofsqPw" alt="">
</div>
check this out I use some little bit of jquery and setInterval function to change in every 5000ms
You may use setTimeout for achieving this effect.
<div id="container">
<div class="block" id="img_1"></div>
<div class="block" id="img_2"></div>
<div class="block" id="img_3"></div>
<div class="block" id="img_4"></div>
<div class="block" id="img_5"></div>
</div>
.block{
width:100px;
height:100px;
display: inline-block;
margin:10px;
background: lightblue;
visibility: hidden;
}
And then,
$('.block').each(function(index, value) {
setTimeout(function() {
$(value).css("visibility", "visible");
$(value).show().delay(1000).fadeOut();
}, 2000 * (index + 1));
});

jquery If statement based on a previous element

I want to hide an element if the previous element has a number less than 0.
https://jsfiddle.net/82bysjag/2/
$(document).on("click", function() {
$(".hide").each(function() {
var prevqty = $(".hide").prev().text();
if (prevqty < 0) {
$(this).hide();
} else {}
});
});
div {
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
-2
</div>
<div class="hide">
Hide
</div>
<div>
1
</div>
<div class="hide">
Hide
</div>
Is there an error with my var prevqty?
Use $(this) and parseInt to
$(".hide").each(function() {
var prevqty = parseInt($(this).prev().text(), 10);
if (prevqty < 0) {
$(this).hide();
} else {}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>-2</div>
<div class="hide">Hide</div>
The problem is from prevqty. JavaScript is seing it as a string. Convert it to number first as follows;
var prevqty = $(".hide").prev().text();
prevqty =Number(prevqty );
Then you can compare

how to change color of elements one by one using javascript(jquery) and then reset the result again one by one

how to change color of elements one by one using javascript(jquery) and then reset the result again one by one
.cub {
background: aqua;
width: 200px;
height: 200px;
display: inline-block;
}
You can add class and remove class using jQuery. First assign another class to these divs so no other divs will be affected.
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
var counter = 0;
var divs = $('.box'), div = null;
setInterval(function(){
div = $(divs[counter]);
if(div.hasClass('cub')){
div.removeClass('cub');
} else {
div.addClass('cub');
}
counter = (counter + 1) % 4;
}, 500);
Please try this code if it works. I was not able to check it but it should work.
<div class="cub"></div>
<div class="cub"></div>
<div class="cub"></div>
<div class="cub"></div>
.cub{ background-color: white; }
.cub.highlighted{ background-color: aqua; }
<script>
var highlighting = true;
$(document).ready(function(){
var highlightingInterval = setInterval(function(){
if( $(".cub.highlighted").length == 0 )
highlighting = true;
else if( $(".cub.highlighted").length == 4 )
highlighting = false;
if( highlighting )
{
$(".cub").not(".highlighted").eq(0).addClass("highlighted");
}
else
{
var targetIndex = $(".cub.highlighted").length - 1; $(".cub.highlighted").eq(targetIndex).removeClass("highlighted");
}
}, 2000 );//setInterval
});//document ready
</script>

Categories