I am trying to create a kind of box which suppose to display random divs. For example with fun facts about animals. I found some code, wrote some on my own and it works this way:
1. random div is loaded when page is loading
2. next random divs are loaded everytime user click the button: "Random fun facts"
In the code below the button "Rundom fun facts" works only once. How can I make it to work continousely? I mean the way that I can click on it 100 times and it will display 100 various divs. And here is my second question: When using for example 100 divs (there are many fun facts about animals) the code below would be very long, is there a simpler way with some kind of creating a loop?
There are tons of sliders but I couldn't find anything like I need. Any help would be appreciated.
<div id="box">
<div id="funfact1">
<p>
Squirrels plant thousands of new trees each year simply by forgetting where they put their acorns. </p>
</div><!-- end funfact1 -->
<div id="funfact2">
<p>Macaques in Japan use coins to buy vending machine snacks. </p>
</div><!-- end funfact2 -->
<div id="funfact3">
<p>Japanese Macaques make snowballs for fun. </p>
</div><!-- end funfact3 -->
<div id="funfact4">
<p>Dogs’ nose prints are as unique as human fingerprints and can be used to identify them. </p>
</div><!--end funfact4 -->
<div id="buttonDiv">
<button id="buttonShuffle">Random fun fact</button>
</div><!-- end buttonDiv -->
</div><!-- end div box -->
<script type="text/javascript">
randomNumber = Math.floor(Math.random()*4+1);
window.onload = function() {
if (randomNumber == 1) {
document.getElementById("funfact1").style.display = "inline";
document.getElementById("funfact2").style.display = "none";
document.getElementById("funfact3").style.display = "none";
document.getElementById("funfact4").style.display = "none";
}
if (randomNumber == 2) {
document.getElementById("funfact1").style.display = "none";
document.getElementById("funfact2").style.display = "inline";
document.getElementById("funfact3").style.display = "none";
document.getElementById("funfact4").style.display = "none";
}
if (randomNumber == 3) {
document.getElementById("funfact1").style.display = "none";
document.getElementById("funfact2").style.display = "none";
document.getElementById("funfact3").style.display = "inline";
document.getElementById("funfact4").style.display = "none";
}
if (randomNumber == 4) {
document.getElementById("funfact1").style.display = "none";
document.getElementById("funfact2").style.display = "none";
document.getElementById("funfact3").style.display = "none";
document.getElementById("funfact4").style.display = "inline";
}
}
randomNumber1 = Math.floor(Math.random()*4+1);
document.getElementById("buttonShuffle").onclick=function() {
if (randomNumber1 == 1) {
document.getElementById("funfact1").style.display = "inline";
document.getElementById("funfact2").style.display = "none";
document.getElementById("funfact3").style.display = "none";
document.getElementById("funfact4").style.display = "none";
}
if (randomNumber1 == 2) {
document.getElementById("funfact1").style.display = "none";
document.getElementById("funfact2").style.display = "inline";
document.getElementById("funfact3").style.display = "none";
document.getElementById("funfact4").style.display = "none";
}
if (randomNumber1 == 3) {
document.getElementById("funfact1").style.display = "none";
document.getElementById("funfact2").style.display = "none";
document.getElementById("funfact3").style.display = "inline";
document.getElementById("funfact4").style.display = "none";
}
if (randomNumber1 == 4) {
document.getElementById("funfact1").style.display = "none";
document.getElementById("funfact2").style.display = "none";
document.getElementById("funfact3").style.display = "none";
document.getElementById("funfact4").style.display = "inline";
}
}
</script>
Fiddle
If you want to keep all your div and write a less repetitive code, you can try this. In general, when you write code, try to identify repetitions and export their in functions.
window.onload = function() {
// show random fact on load
randomFact()
// show random fact on button click
document.getElementById("buttonShuffle").addEventListener('click', randomFact)
}
function randomFact () {
// generate random
var random = Math.floor(Math.random() * 4)
// get all facts
var funfacts = document.getElementsByClassName('funfact')
// hide all facts
for (var i = 0; i < funfacts.length; i++) {
funfacts[i].style.display = 'none'
}
// show one
funfacts[random].style.display = 'inline'
}
https://jsfiddle.net/kxv7y6x9/
Try this :
<div id="box">
<p id="funFacts"></p>
</div><!-- end div box -->
<script type="text/javascript">
var funFacts = [
'Squirrels plant thousands of new trees each year simply by forgetting where they put their acorns. ',
'Macaques in Japan use coins to buy vending machine snacks. ' ,
'Japanese Macaques make snowballs for fun. ' ];
var randomNumber = Math.floor(Math.random() * (funFacts.length-1));
window.onload = function() {
document.getElementById('funFact').innerHTML = funFacts[randomNumber];
};
document.getElementById("buttonShuffle").onclick=function() {
var randomNumber1 = Math.floor(Math.random() * (funFacts.length-1));
document.getElementById('funFact').innerHTML = funFacts[randomNumber1];
}
</script>
What problem you are facing is that you are generating randomNumber1 outside the function which is running only once and not on each call of buttonShuffle.
Next problem you had was to not write some many divs which you can see that I have solved using an array of funfacts.
This will fix your problem,
And if you want to dynamic the posts count you can do something like this,
HTML,
<div id="box">
<div class="text">
<p>Squirrels plant thousands of new trees each year simply by forgetting where they put their acorns</p>
</div><!-- end funfact1 -->
<div class="text">
<p>Macaques in Japan use coins to buy vending machine snacks.</p>
</div><!-- end funfact2 -->
<div class="text">
<p>Japanese Macaques make snowballs for fun.</p>
</div><!-- end funfact3 -->
<div class="text">
<p>Dogs’ nose prints are as unique as human fingerprints and can be used to identify them. </p>
</div><!--end funfact4 -->
<div id="buttonDiv">
<button id="buttonShuffle">Random fun fact</button>
</div><!-- end buttonDiv -->
</div><!-- end div box -->
Javascript,
var texts = document.getElementsByClassName('text'),
randomNumber;
function updateNumber(){
randomNumber = (Math.floor((Math.random() * texts.length) + 1)) - 1;
}
function updateText(){
updateNumber();
for (i = 0; i < texts.length; i++) {
texts[i].style.display = "none";
}
texts[randomNumber].style.display = "block";
}
window.onload = function(){
updateText();
}
document.getElementById('buttonShuffle').onclick = function(){
updateText();
}
CSS,
#box {
width: 350px;
height: 250px;
border: solid thin blue;
padding: 10px;
position: relative;
}
#buttonDiv {
position: absolute;
bottom: 10px;
left: 120px;
}
See the example: https://jsfiddle.net/xbouf1o2/21/
In the code below the button "Random fun facts" works only once. How can I make >it to work continuously?
The reason this happens is because your randomNumber1 variable is calculated once. You need to calculate your random number within the onclick event. This way, every time you click the button, a random number is generated, and the associated fun fact is displayed.
When using for example 100 divs (there are many fun facts about animals) the >code below would be very long, is there a simpler way with some kind of >creating a loop?
First, you need to remove the ID from each fun fact, and add a class instead. Now you can use JS to grab all fun facts using document.getElementsByClassName(class). This will return a nodelist that we can loop through.
Second, create a function which will do the shuffling for you.
function shuffleRandomFunfact(event) {
// Generate a random number.
var randomNumber = Math.floor(Math.random() * 4);
// Loop through the nodelist.
for (var i = 0; i < funfacts.length; i++) {
// If the index of the current funfact is the same
// as the random number.
if (i === randomNumber)
funfacts[i].style.display = 'inline';
// Otherwise ...
funfacts[i].style.display = 'none';
}
}
Now, you just need to attach the above function to your event listeners.
Fiddle
Related
I want to use a button to display a text with the styles and to revert to the original text when I click the button again. I have done the first part which is to display the text but I cant revert back to the original text. This is what I have so far:
function myFunction() {
document.getElementById("second").innerHTML = "Hello Javascript";
document.getElementById("second").style.fontSize = "25px";
document.getElementById("second").style.color = "red";
}
<button type="button" onclick="myFunction()">Click here</button>
<p id="second">This is me</p>
Declaring a a variable let count = 1; outside the function which will help me to check the state i am in currently in.so first i assigned the value of 1 to it.
in my function i am saying is count is equal to 1 change it to Hello Javascript with other properties and change count to zero.so when you click the next time count is now zero and the first if gets rejected instead it goes to the second if else
condition and makes it this is me and changes count to 1 this time.
basically changing the text with count as a statemanagement.
let count = 1;
function myFunction() {
if (count == 1) {
document.getElementById("second").innerHTML = "Hello Javascript";
document.getElementById("second").style.fontSize = "25px";
document.getElementById("second").style.color = "red";
count = 0;
} else if (count == 0) {
document.getElementById("second").innerHTML = "This is me";
document.getElementById("second").style.fontSize = "16px";
document.getElementById("second").style.color = "black";
count = 1;
}
}
<button type="button" onclick="myFunction()">Click here</button>
<p id="second">This is me</p>
perhaps using sequence style 😉
const sequence = [
['This is me', '20px', 'blue'],
['Hello Javascript', '25px', 'red'],
['stackoverflow', '50px', 'green'],
];
let index = 0;
function myFunction() {
const element = document.getElementById("second");
element.innerText = sequence[index][0];
element.style.fontSize = sequence[index][1];
element.style.color = sequence[index][2];
// increment the index then wrap index to the start when needed
index = (index + 1) % sequence.length;
}
// intialize
myFunction();
One way to do so would be to toggle your styles on the element. The code to do so is given below.
function myFunction() {
document.getElementById("second").classList.toggle("mystyle");
}
.mystyle {
font-size: 25px;
color: red;
}
<button type="button" onclick="myFunction()">Click here</button>
<p id="second">This is me</p>
<!DOCTYPE html>
<html>
<script>
var count = 0;
function myFunction() {
count += 1;
if (count % 2 > 0) {
document.getElementById("second").style.fontSize = "25px";
document.getElementById("second").style.color = "red";
document.getElementById("second").innerText = "Hello Javascript";
} else if (count % 2 == 0) {
document.getElementById("second").style.fontSize = "15px";
document.getElementById("second").style.color = "black";
document.getElementById("second").innerText = "This is me";
}
}
</script>
<body>
<button type="button" onclick="myFunction()">Click here</button>
<p id="second">This is me</p>
</body>
</html>
You should store the button style somewhere, and you should store your element reference, interrogating the DOM is performance consuming.
You can get compute styles with window.getComputedStyle(element)
Something like
const buttonRef = document.getElementById("second")
const buttonDefaultStyle = window.getComputedStyle(buttonRef)
const isDefaultStyle = true
let buttonInnerHTML = "text"
function myFunction() {
if (isDefaultStyle) {
buttonRef.innerHTML = "Hello Javascript";
buttonRef.style.fontSize = "25px";
buttonRef.style.color = "red";
isDefaultStyle = false;
} else {
buttonRef.innerHTML = buttonInnerHTML;
buttonRef.style.fontSize = buttonDefaultStyle.fontSize;
buttonRef.style.color = buttonDefaultStyle.color;
isDefaultStyle = true;
}
}
You have to pardon me, as I'm still learning JS, but I thought i'd give it a try as an exercise. There are probably simpler ways to do this, but this is what I came up with.
For a faux 'boolean', if you will, you can go through even and odd numbers with a counter increasing each time you press the button. If left to its own devices, a counter will go to infinity, so adding an if clause (or a case switch, could be either), for the counter if it goes above a certain number will keep it reasonable.
Rather than adding font styles, I think it would be easier to toggle between classes, that way you can just edit the CSS instead of having to go change JS every time you want to change the output style of one of the states.
Using an event listener instead of an onclick assigned to the html Button tag will allow the function to count up the clicks, because essentially the function is continually running instead of just firing once every time the button is clicked.
let counter = 0; //establishing the counter
button.addEventListener("click", function() { //using an event listener instead of an onclick event allows the function to continually run instead of firing once each time the button is clicked
let button = document.querySelector("#button");
let print1 = 'Goodbye Foo'; //making the change state the first state assigned by the click means that the content will in fact change the first time you click the button, which took me a hot second to figure out
let print2 = 'Hello World';
let printer = document.getElementById('second');
if (counter % 2 == 0) { //if the counter, when divided by two has a remainder of 0
printer.innerHTML = print1; //then print "print1" as the inner html
printer.classList.replace('print2', 'print1'); //and toggle the classes
} else { //else, if the remainder of the counter divided by 2 is not zero
printer.innerHTML = print2; //print the other state
printer.classList.replace('print1', 'print2'); //and replace the css
}
if (counter >= 9) { //if the counter ever gets to 9 (an odd number)
counter = 0; //then restart the counter at zero (which gives a remainder of 0, making it "even" in this case
} else {
counter++; //otherwise count up one each time the button is pressed
}
});
.print1 {
color: red;
font-size: 24px;
}
.print2 {
color: blue;
font-size: 12px;
}
<button id="button" type="submit">
Click me
</button>
<p id="second" class="print2">
Hello World
</p>
here it is in jsfiddle:
https://jsfiddle.net/slingtruchoice/wkt3pz9v/
you can switch from a class to another using toogle to change the style like this :
document.getElementById("second").classList.toggle("mystyle");
and you keep inner-html to change the text like this:
if (document.getElementById("second").innerHTML === "Click here")
{
document.getElementById("second").innerHTML = "Hello Javascript";
} else {
document.getElementById("second").innerHTML = "Click here";
}
I eventually used this and it worked perfectly fine for me. it also changed the text on the button as well.
let count = 1;
function mySecond() {
if (count == 1) {
document.getElementById("button3").innerHTML = "Hello Javascript";
document.getElementById("button3").classList.toggle("myStyle");
document.getElementById("button2").innerHTML = "Back";
count = 0;
} else if (count == 0) {
document.getElementById("button3").innerHTML = "This is the best";
document.getElementById("button3").classList.toggle("myStyle");
document.getElementById("button2").innerHTML = "Start";
count = 1;
}
}
<button id="button2" onclick="mySecond()">Start</button>
<p id="button3">This is the best</p>
.myStyle {
color: brown;
}
EDIT
I meant to say, how could I add a third else if statement that would fire on the third click.
basically it opens and hide a different element on the first, second and third click.
so I want to add one more function to make a total of 3 functions to this onclick event that changes depending on how many times you click on the button. I am just not sure how to add a third function.
<div class="base" id="base">
<img src="img/base.svg">
</div>
<div class="base one" id="one">
<img src="img/one.svg">
</div>
<div class="base two" id="two">
<img src="img/two.svg">
</div>
<div class="base three" id="three">
<img src="img/three.svg">
</div>
<button class="test" id="test">btn</button>
var action = 1;
test.onclick = function viewSomething() {
if (action == 1) {
base.style.display = "none";
one.style.display = "block";
action = 2;
console.log(tets)
} else {
one.style.display = "none";
two.style.display = "block";
action = 1;
}
}
You already have the basic setup, you just need to extend it:
var action = 1;
test.onclick = function viewSomething() {
if (action == 1) {
base.style.display = "none";
one.style.display = "block";
action = 2;
console.log(tets)
} else if (action === 2) {
// ...
action = 3;
} else if (action === 3) {
one.style.display = "none";
two.style.display = "block";
action = 1;
}
Having said that, if you always go sequentially from one "action" to the other, you could consider moving each "action" into a separate function, storing all those functions into an array and have the click handler simply advance the index:
const actions = [
function(event) {
base.style.display = "none";
one.style.display = "block";
},
function(event) {
one.style.display = "none";
two.style.display = "block";
},
function(event) {
// ...
},
];
let actionIndex = 0;
test.onclick = function viewSomething(event) {
actions[actionIndex](event);
actionIndex = (actionIndex + 1) % actions.length;
};
The advantage of the solution is that you are decoupling the action "control" from the actions themselves and that you can more easily add and rearrange additional actions.
I'm not sure what you mean by a third function since I can only see viewSomething, but you can add an if else block to your if statement:
if (action == 1) {
base.style.display = "none";
one.style.display = "block";
action = 2;
console.log(tets)
} else if (this == that) {
// your logic here
} else {
one.style.display = "none";
two.style.display = "block";
action = 1;
}
If you really want three different functions (you currently have one function and two if statements), you need to use addEventListener:
function clickOne() {
console.log("first!");
}
function clickTwo() {
console.log("second!");
}
function clickThree() {
console.log("third!");
}
var test = document.querySelector("#test");
test.addEventListener("click", clickOne);
setTimeout(() => {
test.addEventListener("click", clickTwo);
}, 2000);
setTimeout(() => {
test.addEventListener("click", clickThree);
}, 5000);
<button class="test" id="test">Click</button>
This code should stop after the length of the array scores reaches the length of five. Or so I thought. It doesn't and I cant't figure out what to do.
I also altered the code so that scores.length < rounds.length but that didn't work either.
Any help would be greatly appreciated.
JS
var scores = [];
var rounds = [1, 2, 3, 4, 5];
var startTime, clickTime, resultTime;
var button = document.querySelector('.button');
var box = document.querySelector('.box');
function game() {
if (scores.length < 5) {
box.style.display = 'none';
button.onclick = function() {
box.style.display = 'block';
startTime = Date.now();
}
box.onclick = function() {
clickTime = Date.now();
resultTime = (clickTime - startTime) / 1000;
box.style.display = 'none';
scores.push(resultTime);
}
console.log(scores);
}
else {
box.style.display = 'none';
button.style.display = 'none';
}
}
game();
CSS
.box {
width:150px;
height:150px;
background-color:red;
}
.wrapper {
display: flex !important;
align-items: center !important;
justify-content: center !important;
flex-flow:column;
}
.button {
width: 150px;
height: 20px;
background-color:blue;
}
HTML
<html>
<head>
<link type="text/css" rel="stylesheet" href="reaction.css">
</head>
<body>
<div class="wrapper">
<div class="button"></div>
<div class="box">
<div class="text">
</div>
</div>
</div>
<script src="reaction-timer.js"></script>
</body>
</html>
The problem lies around your if statement, which is evaluated only once at the beginning of the code execution, in the beginning of the execution of game().
You want this condition to be checked before it enters the displaying part, and each time it does so. And moreover you want it to happen several times, until the condition fails. So in this case, you would need a while here.
It would do something like this:
var scores = []
while (scores.length < 5) {
// The actions you want to repeat 5 times here
scores.push('pushSomething');
}
But it's not actually what you want, I think you want to check if the click on the button can trigger on new push into scores. So you need a check there, not at the beginning of game().
So by better splitting your code it will be easy:
var scores = []
var rounds = [1, 2, 3, 4, 5];
var startTime, clickTime, resultTime;
var button = document.querySelector('.button');
var box = document.querySelector('.box');
function handleBoxClicked () {
if (scores.length >= 5) {
box.onclick = null; // to disable trigger of this function
return false
}
clickTime = Date.now();
resultTime = (clickTime - startTime) / 1000;
box.style.display = 'none';
console.log(scores);
scores.push(resultTime);
}
function game() {
box.style.display = 'none';
button.onclick = function() {
box.style.display = 'block';
startTime = Date.now();
}
box.onclick = handleBoxClicked;
}
game();
Ok i'll try very hard to explain exactly what I'm trying to accomplish.
I know that if I want a div to stay at the bottom of a page I can simply do this..
<div id="foo" style="position: fixed; bottom: 0: width: 100%">
blah text
</div>
But I don't want this to always be at the bottom of the page..
I have code like this..
<html>
<head>
<script type="text/javascript">
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';"
else
e.style.display = 'block';
}
</script>
</head>
<body>
<div id="firstDiv" style="display: block;">
......
</div>
<div id="secondDiv" style="display: none;">
......
</div>
<div id="thirdDiv" style="display: none;">
......
</div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
..repeated 20 times or w/e..
</body>
</html>
I want to do something like http://www.snyderplace.com/demos/collapsible.html
BUT i really don't want to use someone elses library if at all possible... I'm open to using jQuery etc, just don't want to use someone elses library if all possible unless its very bare bones and not a FULL library.
I only know how to hide and show the current ones HTML. I know i would prolly have to do something like..
if (e.id = "firstDiv") {
secondDiv.style.display = 'none';
thirdDiv.style.display = 'none';
} elseif { ....
....
}
Ok so what I want to be able to do is if i have a TON of data inside the [firstDiv] and its so much data that the page has a scroll bar and the [secondDiv] and [thirdDiv] would normally pushed all the way down the page... I want [secondDiv] and [thirdDiv] to stack ontop of eachother and always at the bottom of the page...
But then if I click on [secondDiv] then the [firstDiv] contents will obviously disappear, but I want [firstDiv] to stay at top of page no matter what, then [secondDiv] to be right under neath it which will then show its HTML while [thirdDiv] will still stay static at the bottom of the page....
Then if I was to click on [thirdDiv] then it would just then be [firstDiv] [secondDiv] and [thirdDiv] stacked in order at the very top while now of course showing the HTML of the [thirdDiv]...
LOOOONG explaination later i'm wanting to do a Collapseable system that hides the other divs content while keeping them in order HOWEVER the twist is that the divs below the [firstDiv] always still show up at the bottom of the page no matter what.
Hopefully this makes sense!
I ended up solving and having to do this myself. My answer is TERRIBLY UGLY, but it does work... I would love if anyone could help re-write it so its not so ugly I would greatly appreciate it...
I ended up having to create a Header to act as the (Accordion Header) then a div below it that acted as the div that held the results of the HTML/Content..
Then each Accordion Header I just set onclick="toggle_visibility('firstDivHeader');" or whatever the header that was clicked and then it did the following..
http://jsfiddle.net/t8Le7qqv/ - I wanted to add finished result incase anyone wanted to know how to do this.
<script type="text/javascript">
function toggle_visibility(id) {
if (id == 'firstDivHeader')
{
document.getElementById('firstDivResults').style.display = 'block';
document.getElementById('firstDivHeader').style.top = '0';
document.getElementById('firstDivHeader').style.position = 'fixed';
document.getElementById('secondDivResults').style.display = 'none';
document.getElementById('secondDivHeader').style.top = '';
document.getElementById('secondDivHeader').style.bottom = '82px';
document.getElementById('secondDivHeader').style.position = 'fixed';
document.getElementById('thirdDivResults').style.display = 'none';
document.getElementById('thirdDivHeader').style.top = '';
document.getElementById('thirdDivHeader').style.bottom = '41px';
document.getElementById('thirdDivHeader').style.position = 'fixed';
document.getElementById('forthDivResults').style.display = 'none';
document.getElementById('forthDivHeader').style.top = '';
document.getElementById('forthDivHeader').style.bottom = '0px';
document.getElementById('forthDivHeader').style.position = 'fixed';
} else if (id == 'secondDivHeader')
{
document.getElementById('firstDivResults').style.display = 'none';
document.getElementById('firstDivHeader').style.top = '0';
document.getElementById('firstDivHeader').style.position = 'fixed';
document.getElementById('secondDivResults').style.display = 'block';
document.getElementById('secondDivHeader').style.top = '41px';
document.getElementById('secondDivHeader').style.bottom = '';
document.getElementById('secondDivHeader').style.position = 'fixed';
document.getElementById('thirdDivResults').style.display = 'none';
document.getElementById('thirdDivHeader').style.top = '';
document.getElementById('thirdDivHeader').style.bottom = '41px';
document.getElementById('thirdDivHeader').style.position = 'fixed';
document.getElementById('forthDivResults').style.display = 'none';
document.getElementById('forthDivHeader').style.top = '';
document.getElementById('forthDivHeader').style.bottom = '0px';
document.getElementById('forthDivHeader').style.position = 'fixed';
} else if (id == 'thirdDivHeader')
{
document.getElementById('firstDivResults').style.display = 'none';
document.getElementById('firstDivHeader').style.bottom = '0';
document.getElementById('firstDivHeader').style.position = 'fixed';
document.getElementById('secondDivResults').style.display = 'none';
document.getElementById('secondDivHeader').style.top = '41px';
document.getElementById('secondDivHeader').style.bottom = '';
document.getElementById('secondDivHeader').style.position = 'fixed';
document.getElementById('thirdDivResults').style.display = 'block';
document.getElementById('thirdDivHeader').style.top = '82px';
document.getElementById('thirdDivHeader').style.bottom = '0';
document.getElementById('thirdDivHeader').style.position = 'fixed';
document.getElementById('forthDivResults').style.display = 'none';
document.getElementById('forthDivHeader').style.top = '';
document.getElementById('forthDivHeader').style.bottom = '0px';
document.getElementById('forthDivHeader').style.position = 'fixed';
} else if (id == 'forthDivHeader')
{
document.getElementById('firstDivResults').style.display = 'none';
document.getElementById('firstDivHeader').style.top = '0';
document.getElementById('firstDivHeader').style.bottom = '';
document.getElementById('firstDivHeader').style.position = 'fixed';
document.getElementById('secondDivResults').style.display = 'none';
document.getElementById('secondDivHeader').style.top = '41px';
document.getElementById('secondDivHeader').style.bottom = '';
document.getElementById('secondDivHeader').style.position = 'fixed';
document.getElementById('thirdDivResults').style.display = 'none';
document.getElementById('thirdDivHeader').style.top = '82px';
document.getElementById('thirdDivHeader').style.bottom = '';
document.getElementById('thirdDivHeader').style.position = 'fixed';
document.getElementById('forthDivResults').style.display = 'block';
document.getElementById('forthDivHeader').style.top = '123px';
document.getElementById('forthDivHeader').style.bottom = '';
document.getElementById('forthDivHeader').style.position = 'fixed';
}
}
</script>
Thanks for the design pattern. It really helped me when I was looking to build something similar to what you had done. Here's my version as per your re-write request :) Things to note: I'm using jQuery selectors rather the the javascript ones you used, my divs are named differently and my row height is different, but you'll get the idea.
function toggle_visibility(id) {
// Setup the accordion divs
var sectionHeaderIds = ["#sectionOneHeader", "#sectionTwoHeader", "#sectionThreeHeader",
"#sectionFourHeader", "#sectionFiveHeader", "#sectionSixHeader"];
var sectionDetails = ["#sectionOneDetail", "#sectionTwoDetail", "#sectionThreeDetail",
"#sectionFourDetail", "#sectionFiveDetail", "#sectionSixDetail"];
var rowHeight = 30;
var chosenSectionId = 0;
var numSections = sectionHeaderIds.length;
// Get the index of the selected section
for (var i = 0; i < numSections; i++) {
if (sectionDetails[i] == id) {
chosenSectionId = i;
}
}
// Loop through the divs
for (var i = 0; i < numSections; i++) {
var sectionHeader = $(sectionHeaderIds[i]);
var sectionDetail = $(sectionDetails[i]);
sectionHeader.css('position','fixed');
if (sectionDetails[i] == id) {
sectionDetail.css('display', 'block');
} else {
sectionDetail.css('display', 'none');
}
sectionHeader.css('top',(i <= chosenSectionId) ? i * rowHeight : '');
sectionHeader.css('bottom',(i > chosenSectionId) ? (numSections - i - 1) * rowHeight : '');
}
}
I want to display two images which should change every 50 seconds. Each image should be displayed for 120 seconds.
window.onload = function() {
var dir = "0";
setInterval(function () {
var element = document.getElementById("maincontainer");
if(element.style.display == "none") {
if(dir == "1") {
dir = "0";
} else {
dir = "1";
}
loadNewImages(dir);
element.style.display = "block";
} else {
element.style.display = "none";
}
}, 50000);
Some simple HTML code with a div container:
<div id="maincontainer">
<img src="myimage.png" />
</div>
I try to play around with:
setTimeout(function() {
element.style.display = "none";
}
),
120000)
But this did not work.
I need a solution in plain JavaScript. With jQuery I can simply use delay or other magic.
Can someone give me a hint how to achieve my requirement?
I recommend using a cycle pattern. Here's a demo (using 1.2 seconds to save you 1.98 minutes).
var images = document.getElementsByTagName("img");
We wrap this in a closure so we can control our i variable.
(function(){
var i = 0;
The first thing we do in our interval is to hide the current image, which is images[i].
setInterval(function(){
images[i].style.display = "none";
The we check and see if i+1 would be a valid image. You could also write this as images[i+1] != null. If we can increment it, we do. Otherwise we start back at 0. With two images this toggles between 0 and 1. With 5 images it cycles 0, 1, 2, 3, 4, 0, 1, 2, ...
if (i+1 < images.length) {
i++;
}
else {
i = 0;
}
Our new image is displayed. This will be image[i] when the timer runs again, so it will be hidden.
images[i].style.display = "inline-block";
}, 120000);
})();