How to display ONE div randomly

Below is the code written by another user here to show / hide the div with a random delay between 4-8 seconds

<script> function showCity() { $('#city-middle').show(); window.setTimeout( hideCity, 10 ); } function hideCity() { $('#city-middle').fadeOut(200); window.setTimeout( showCity, 3000 + (Math.random() * 5000) ); } hideCity(); </script> 

So the DIV # city-middle (appears and disappears) has a child div named # bolt-container, which explicitly appears and disappears with this div. Inside this bolt container there are 4 daughter divisions with bolts-1 to bolt-4. Each of these divs is located in different places.

 <div id="city-middle"> <div id="bolt-container"> <div class="bolt-1"> </div> <div class="bolt-2"> </div> <div class="bolt-3"> </div> <div class="bolt-4"> </div> </div> </div> 

I need divs-bolt-1 - # bolt-4 to be displayed randomly ONE AT TIME without animation.

So far I have been looking for this and have found only one jsfiddle that could help - http://jsfiddle.net/tricinel/FgXDC/

I tried to implement, as shown below, with no luck.

  function showCity() { $('#city-middle').show(); window.setTimeout( hideCity, 10 ); } function hideCity() { $('#city-middle').fadeOut(200); window.setTimeout( showCity, 3000 + (Math.random() * 5000) ); } hideCity(); var divs = $('#bolt-container').find('.div'), len = divs.length, randomDiv, speed = 1000; var interval = setInterval( function() { randomDiv = Math.floor(Math.random()*len); divs.removeClass('show'); divs.eq(randomDiv).addClass('show'); } , speed); 

I know that something is wrong with how I put it, but as a beginner, I have no idea where to even look! Maybe I am not closing the first jQuery thing right? Or do not set any function for the second?

+4
source share
3 answers

To adapt the script that you sent, all you had to do was use:

 var divs = $('#bolt-container').find('div'), //fetch all the divs 

Note that var divs = $('#bolt-container').find('.div') retrieves all elements with a class div (!) That were descendants of the element with id #bolt-container . In your example, you do not want this, you want to get all the <div> under such an element. This is what the above code does.

And don't forget the CSS (will also apply to all <div> below #bolt-container ):

 #bolt-container div { display:none; } 

Check if it works here .

+3
source

I would fulfill the suggestions already given (by @acdcjunior):

 var divs = $('#bolt-container').find('div'); 

and

 #bolt-container div { display:none; } 

but I would also put all the code (excluding function definitions) between:

 $(document).ready(function() { // Put your code here. }); 

To make sure your document is loaded before working with its objects.

+3
source
 var divs = $('#bolt-container').find('.div'), 

it should be:

 var divs = $('#bolt-container').find('div'), 

or simply:

 var divs = $('#bolt-container div'), 
+2
source

Source: https://habr.com/ru/post/1492404/


All Articles