three small absolutely positioned divs in my homepage - javascript

I have three small absolutely positioned divs in my homepage. i want only one div to appear at a time, so that the page should start with only the first div and after 3 seconds, the second div and after 3 seconds the third div and this process should continue infinitely. this is the for-loop I've come up with for doing this 10 times. how can i make the same happen infinitely?
// this for not making infinite loop
var nb_loop=0;
var max_loop=10;
var j=0;
for (var i=2; i<=3 ; i++){
nb_loop++;
j++;
console.log("i="+i+", j="+j); // or alert if you want
if (j>=3)
j=0;
if (i>=3)
i=0;
if (nb_loop>max_loop)
break;
}

JS:
var counter = 1;
function showDiv(){
$('.display').hide();
$('#div'+counter).show();
(counter == 4 ? counter = 1 : counter++)
}
showDiv();
var timer = setInterval(showDiv, 3000);
HTML:
<div id='container'>
<div id='div1' class='display' style="background-color: red;">
div1
</div>
<div id='div2' class='display' style="background-color: green;">
div2
</div>
<div id='div3' class='display' style="background-color: blue;">
div3
</div>
<div id='div4' class='display' style="background-color: yellow;">
div4
</div>
</div>
CSS:
.display { display: none; }
Use Jquery setInterval function use for infinite time

use JQUERY SETTIMEOUT() function
like this
jQuery(document).ready(function () {
//hide a div after 3 seconds
setTimeout(function(){ jQuery("#div").hide(); }, 3000);
});

Related

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));
});

Select next div with jquery?

//$(document).ready(function(){
$('.next').click(function(){
$('.box').fadeOut();
$('.box').next().fadeIn();
});
//});
.box{
border:solid 1px #ccc;
padding: 20px;
width:10%;
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="next" style="cursor:pointer;">next</a> <br><br>
<div class="box" style="display:block;">
1
</div>
<div class="box">
2
</div>
<div class="box">
3
</div>
<div class="box">
4
</div>
I have a div .box, and the next button. I need to select the next div if i click the next button but only the first div not all. For example if i click next button while it shown box 1 then the next box that should be appear is 2 and so on. But now it shown 2 3 4. How to do this ?
you can get the first visible div using $(.box:visible) and then fadeIn next div to it. you can also add a check for last element, in which case you can fadeIn the first element. something like this:
//$(document).ready(function(){
$('.next').click(function(){
var visibleBox = $('.box:visible');
$(visibleBox).fadeOut();
if(!$(visibleBox).next('div').length)
$('.box').first().fadeIn();
else
$(visibleBox).next().fadeIn();
});
//});
.box{
border:solid 1px #ccc;
padding: 20px;
width:10%;
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="next" style="cursor:pointer;">next</a> <br><br>
<div class="box" style="display:block;">
1
</div>
<div class="box">
2
</div>
<div class="box">
3
</div>
<div class="box">
4
</div>
It's showing 2 3 4 because you ares selecting ALL .box elements, i.e. 1 2 3 4
.next() of 1 = 2
.next() of 2 = 3
.next() of 3 = 4
.next() of 4 = nothing
You should find the box that is currently being shown, and then find it's next sibling.
// Filter by CSS rule
var $showing = $('.box').filter(function() {
return $(this).css('display') === 'block';
}).fadeOut();
// or using :visible
$showing = $('.box:visible').fadeOut();
$showing.next().fadeIn();
you can use another class to labeled, which div is on the display. for example, you add a class display. then you put that class, on the first box. when you click next, you can remove the class display from the current one, and move it into the next one.
HTML
<a class="next" style="cursor:pointer;">next</a> <br><br>
<div class="box display">
1
</div>
<div class="box">
2
</div>
<div class="box">
3
</div>
<div class="box">
4
</div>
CSS
.box{
border:solid 1px #ccc;
padding: 20px;
width:10%;
display:none;
}
.display{
display:block
}
JQuery
$('.next').click(function(){
var current = $('.box.display');
current.fadeOut().removeClass('display').next().fadeIn().addClass('display');
});
Demo : https://jsfiddle.net/dfaLnsmo/
If I understand your requirement this will work
$(document).ready(function(){
var i = 1;
$('.next').click(function(){
$('.box').fadeOut();
$('.box:nth-child(i)').fadeIn();
if(i >= $('.box').length)
i++;
else
i=1;
});
});
Try the following Jquery
var curr = 1;
$('.next').click(function(){
if(curr < $( ".box" ).length) {
$('.box').hide();
$( ".box" )[curr].style.display= "block";
curr += 1;
}
});
Here is the working jsfiddel : https://jsfiddle.net/Lv7yr820/1/

Moving class names from div to div

I am trying to move class names on div's after a short delay (possible 10 seconds or so).
I want the 3 classes below to move through the div's and loop once it reaches the last one.
For example:
<div class="wrapper">
<div></div>
<div></div>
<div class="previous-one"></div>
<div class="in-focus"></div>
<div class="next-one"></div>
<div></div>
<div></div>
</div>
would turn to:
<div class="wrapper">
<div></div>
<div></div>
<div></div>
<div class="previous-one"></div>
<div class="in-focus"></div>
<div class="next-one"></div>
<div></div>
</div>
I hope this makes sense, It is my first post on here so nothing like starting off with a complicated one.
Appreciate any responses.
You should try this jquery solution:
var colors = ['blue', 'green', 'red'],
timer = 1000;
setInterval(function() {
for(var c in colors) {
var $current = $('.' + colors[c]),
$next = $current.next('li');
if($next.length == 0) {
$next = $('ul li:first-child');
}
$current.removeClass(colors[c]);
$next.addClass(colors[c]);
}
}, timer);
.red {
color: red;
}
.blue {
color: blue;
}
.green {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>lorem</li>
<li class="blue">ipsum</li>
<li class="green">dolor</li>
<li class="red">hello</li>
<li>world</li>
<li>again</li>
</ul>
Think of it step by step.
Find the list of all divs within the wrapper.
Remove "previous-one" class from the corresponding element.
Replace "in-focus" with "previous-one".
Replace "next-one" with "in-focus".
Check if there's an element after in-focus.
If there is, make it "next-one".
Else, make the first div of the list "next-one".
Rinse and repeat.
http://jsfiddle.net/thePivottt/9m63rouu/
function scrollFocus() {
var elements = $(".wrapper div");
var nextOne = elements.filter(".next-one");
var inFocus = elements.filter(".in-focus");
elements.filter(".previous-one").removeClass("previous-one");
inFocus.removeClass("in-focus");
inFocus.addClass("previous-one");
nextOne.removeClass("next-one");
nextOne.addClass("in-focus");
var newNext = nextOne.next("div");
if (newNext.length == 0) newNext = elements.first();
newNext.addClass("next-one");
}
setInterval(scrollFocus, 1000);
Here is my solution. Advance each div by changing the class of the next div then removing the class of the current one. If it is the last div in the wrapper, then move that class to the first div. Here is the fiddle https://jsfiddle.net/cyjm5toa/
Not the most elegant code, but works well.
setInterval(function(){
if($('.wrapper div').last()[0]==$('.next-one')[0]){
$('.next-one').removeClass('next-one');
$('.wrapper div').first().addClass('next-one');
}
else{
$('.next-one').removeClass('next-one').next().addClass('next-one');
}
if($('.wrapper div').last()[0]==$('.previous-one')[0]){
$('.previous-one').removeClass('previous-one');
$('.wrapper div').first().addClass('previous-one');
}
else{
$('.previous-one').removeClass('previous-one').next().addClass('previous-one');
}
if($('.wrapper div').last()[0]==$('.in-focus')[0]){
$('.in-focus').removeClass('in-focus');
$('.wrapper div').first().addClass('in-focus');
}
else{
$('.in-focus').removeClass('in-focus').next().addClass('in-focus');
}
},1000);

auto change div jquery

I am trying to make a div auto hide and show other div like changer. It does not work when I use multi div inside the main div:
<div id="div1">
What actually happens is that it hides all content of the inside div(s)
Is there any way to keep my div(s) for save my style and make an auto changer for my div(s)?
html code
<div id='container'>
<div id='div1' class='display' style="background-color: red;">
<div id="mydiv" style=" left:200; width:100; background-color:#F605C6;">
<div id="main_adv" class="a" style="position:absolute;text-align:left;width:673px;height:256px">
<div id="Layer3" class="a" style="position:absolute;text-align:left;left:176px;top:56px;width:490px;height:171px" title=""></div>
<div id="img_adv" class="a" style="position:absolute;text-align:left;left:4px;top:55px;width:169px;height:172px;" title="">
<img id="ri" class="a" src="thumbs/img1.png" />
</div>
<div id="title_adv" class="a" style="position:absolute;text-align:right;left:4px;top:6px;width:662px;height:40px;" title="">
<div style="position:absolute;text-align:right;right:6px;top:4px;">
<span style="color:#000000;font-family:Arial;font-size:29px;right:5px">some text</span>
</div>
</div>
</div>
</div>
</div>
</div>
<div id='div2' class='display' style="background-color: green;">
div2
</div>
<div id='div3' class='display' style="background-color: blue;">
div3
</div>
</div>
</body>
Javascript code
$('html').addClass('js');
$(function() {
var timer = setInterval( showDiv, 400);
var counter = 0;
function showDiv() {
if (counter == 0) { counter++; return; }
$('div','#container')
.stop()
.hide()
.filter( function() { return this.id.match('div' + counter); })
.show('fast');
counter == 16? counter = 0 : counter++;
}
});
I wrote some basic code that changes divs continiously like you asked :
jsfiddle.net/5jhuK/
HTML
<div id='container'>
<div id='div1' class='display' style="background-color: red;">div1</div>
<div id='div2' class='display' style="background-color: green;">div2</div>
<div id='div3' class='display' style="background-color: blue;">div3</div>
</div>
CSS
.display {
display: none;
}
JS (jQuery)
$(document).ready(function () {
var activeDiv = 1;
showDiv(activeDiv); // show first one because all are hidden by default
var timer = setInterval(changeDiv, 2000);
function changeDiv() {
activeDiv++;
if (activeDiv == 4) {
activeDiv = 1;
}
showDiv(activeDiv);
}
function showDiv(num) {
$('div.display').hide(); // hide all
$('#div' + num).fadeIn(); // show active
}
});
It's really not complicated, next time when you ask something try to be concise and remove unnecessary code (like #mydiv)
a few things:
1. html ids are unique, so you can just do something like below:
2. your code was missing a # in the find (e.g. "#div"+counter)
3. you can use the child selector ">" to just target divs one level down
var counter=1;
function showDiv() {
$('#container > div').hide()
$("#div"+counter).show();
counter == 3? counter = 1 : counter++;
}

Javascript - Using Events and Functions on elements within a div

Having difficulty with changing elements inside divs with events not understanding if i should use an for loop to go through div and make changes or put Events inside of divs and call them individually.
Also curious where i could use "this"
<html><head>
<script type='text/javascript'>
function changeBorder(){ //change all pics to red border
document.images.style.border="2px solid red";
}
function changeSize(){ //change pics in div1 to 100 onmouseover
pics = document.getElementById('div1');
for(i = 0; i < pics.length; i++)
{
pics[i].onmouseover.width = 100;
pics[i].onmouseover.height = 100;
}
}
function turnBlue(){ //paragraphs turn blue on doubleclick
alert("double click turn blue");
var paraBlue = document.getElementById.indexOf('p');
paraBlue.style.background="blue";
}
function yellowBack(){ //background on <p> to yellow onmouseover
var paraYell = document.getElementById.indexOf('p');
paraYell.style.background="yellow";
}
}
</script></head>
<body>
<div id="div1" onmouseover="changeSize()">
<img src="cat.jpg" id='im1' name='im1'/>
<img src="dog.jpg" id='im2' name='im2'/>
<img src="fish.jpg" id='im3' name='im3'/>
</div>
<div id="div2" ondblclick="turnBlue()">
<p id="p1">This is a paragraph</p>
<p id="p2">This is a paragraph</p>
<p id="p2">This is a paragraph</p>
</div>
<div id="div3" onmouseover="yellowBack()">
<p id="p4">This is a paragraph</p>
<p id="p5">This is a paragraph</p>
<img src="bird.jpg" id='im4' name='im4'/>
<img src="turtle.jpg" id='im5' name='im5'/>
</div>
</body>
</html>
too many problems to fix.
just one hint
function changeSize(){
var pics = document.querySelectorAll("#div1 img");
for(var i = 0; i < pics.length; i++){
pics[i].style.width = "100px";
pics[i].style.height = "100px";
}
}

Categories