I display a random DIV every time my webpage is reloaded using a simple function. This produces too many repeats because I only have seven divs.
<script type="text/javascript">
randomNumber = Math.floor(Math.random()*7+1);
window.onload = function() {
if (randomNumber == 1) {
document.getElementById("n1").style.display = "inline";
}
if (randomNumber == 2) {
document.getElementById("n2").style.display = "inline";
}
...[ETC. through 7]
}
}
</script>
I would like to solve this by replacing the "random number" with a predictable "progressing number". Can I advance a variable with every reload or onclick and execute the function to display each DIV in sequence? 1,2,3... displaying all seven divs before repeating.
I worry I would need cookies to do this with each individual visitor. Because the traffic is very low (likely one visitor at a time), perhaps I could use code from a page counter to achieve this.
I searched for any examples of this in action but found none. I would be very appreciative of any and all suggestions. Thanks for your time.
First of all, the random number you are generating, generates 3 everytime so no wonder you are getting all the repeats of third div.. change your random number generation code with this one:
var randomNumber = Math.floor(Math.random() * (7)) + 1;
This will generate a random number between 1 and 7 randomly. Then to display that particular div, instead of so many if or switch statements, you can simply do it in one line considering your div ids are n1, n2, n3 and so on..
document.getElementById("n"+randomNumber).style.display = "inline";
Put these two lines inside window.onload function so everytime window loads, a new random number gets generated and that div gets displayed.
This will work perfectly for many visitors as each visitor will get it's unique random number and that particular div will be displayed. No need to go into cookies or stuff like that.
See the Working snippet below, everytime you run it, a random div will be displayed:
var randomNumber = Math.floor(Math.random() * (7)) + 1;
document.getElementById("n"+randomNumber).style.display = "inline";
<div id="n1" style="display:none">DIV1</div>
<div id="n2" style="display:none">DIV2</div>
<div id="n3" style="display:none">DIV3</div>
<div id="n4" style="display:none">DIV4</div>
<div id="n5" style="display:none">DIV5</div>
<div id="n6" style="display:none">DIV6</div>
<div id="n7" style="display:none">DIV7</div>
EDIT: After understanding your question better (hopefully) and doing some research, i came up with a solution where you can retain the value of current div between page reloads, make a new html file on your computer, copy paste the following code and keep refreshing the page to see each div being displayed incrementally..
<!DOCTYPE HMTL>
<html>
<body>
<div id="n1" style="display:none">DIV1</div>
<div id="n2" style="display:none">DIV2</div>
<div id="n3" style="display:none">DIV3</div>
<div id="n4" style="display:none">DIV4</div>
<div id="n5" style="display:none">DIV5</div>
<div id="n6" style="display:none">DIV6</div>
<div id="n7" style="display:none">DIV7</div>
<script>
window.onload = function(){
if(window.name === "" || parseInt(window.name, 10) === 8) //this condition will be true when the page loads for the first time or the div values (window.name) exceeds 7 (Number of divs)
window.name = 1;
document.getElementById("n"+window.name).style.display = "inline";
window.name = parseInt(window.name,10) + 1; //incrementing the div number..
}
</script>
</body>
</html>
NOTE: Although the question has an accepted answer, I thought this was a closer to the question solution, so I posted it after reading the lines in the OP Can I advance a variable with every reload or onclick and execute the function to display each DIV in sequence? 1,2,3... displaying all seven divs before repeating. which meant that the OP author did not want to show them randomly through the divs.
You could use localStorage to make this happen. This will rotate through the 7 divs sequentially and display one at each page load and it's going to be user specific. That means, every user is assured to see all the divs sequentially.
if (typeof(Storage) != 'undefined') { // Check if localStorage is available in the browser
prevDiv = localStorage.getItem("myShowDiv"); // Fetch the previous that was shown to this browser
if (!isNaN(prevDiv)) prevDiv = parseInt(prevDiv); // If not first time
else prevDiv = parseInt('0'); // If it's first time
nowDiv = prevDiv + 1; // This div will be shown
if (nowDiv > 7) nowDiv = 1; // When all divs have been shown start from 1
localStorage.setItem("myShowDiv",nowDiv); // Save this div id for next page load
document.getElementById("div"+nowDiv).style.display = "inline"; // Show the div
}
Here's a fiddle
Related
I don't know how to display my divs in another page after created them. When the divs are created with their function, after clicking a button, they will be displayed in a div in the main page, right after that, there has to be a redirection to the second page, passing the divs created.
example how the main page works: Jsfiddle
I don't know how to send and display the divs just created, in a second page.
I think that the action should be set with php but I don't know...
IMPORTANT
You don't have to understand the Js code. You only have to know that the divs that I want to copy to the second page, at the beginning, don't exist. So the "copy-to-the-new-page" action has to be done after the creation of the divs.
Main Page:
<html lang="it">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css"/>
</head>
<body>
<div id="faketxt" contenteditable>Write Here</div>
<button id='btn'>OK</button> <br>
<div id='boxes'>
</div>
<script type="text/javascript">
$('#btn').click(function() {
var primo = document.getElementById('faketxt');
var wordLimit = 145;
var words = primo.textContent.replace(/(<([^>]+)>)/ig,"").split(/\s/);
if (words.length) {
var count = 0;
var div = createDiv();
words.forEach(function(word) {
if (++count > wordLimit) {
count = 1;
div = createDiv();
}
if (div.innerHTML) {
div.append(' ');
}
div.append(word);
});
}
});
function createDiv() {
div = document.createElement('div');
div.className = 'fakes';
document.getElementById('boxes').append(div);
return div;
}
</script>
</body>
</html>
You shouldn't have to send the entire div just the amount of data that's required for the next page to recreate it.
i.e. you could use a cookie and have the user remember:
document.cookie = "divinfo=The text field of the div's;\
path=/";
have a hidden input field that contained the relevant information.
<input name="divinfo" hidden value="The info required for the creation of the div"/>
If you use the cookie the javascript could recreate the data on the other side if you use the hidden input you should have the php recreate it.
well, you have at least 3 ways to do it, and it all comes down to how to pass enough information between 2 pages:
1) you may get HTML of those divs when they are just created, store it in session storage, and re-create divs from the stored html. That way you dont have to know much about the divs on the 2nd page, but there is a limit on how much you can store. Also, may pose some security/privacy risks if information is sensitive, so you may have to do some extra coding to mitigate it.
2) you may re-create those divs on the 2nd page based on the same set of information you used to create those on the first page. JS code could be shared between the two.
3) use server side to generate div's content. That way you can generate both 1st and 2nd page content.
Or is there something I miss about the problem?
Create a hidden text input in the submit form
Add the new div value to that hidden input
Submitting the form will send the value to the next page through php
Now pick that value in javascript using php like
var xyz = '';
Now you can use this value whatever you want
I don't know why the values with php tag is not showing here :(
I suggest a few changes. First all all, use a proper form - kind of like you had in the first revision of your question.
<form action="download.php">
<input id="faketxt" type="text" value="Write Here" />
<button id='btn'>OK</button>
</form>
<div id='boxes'></div>
Now, on the second page, you have all the information you need in your form field "faketxt" and just can create the divs there. Depending on which method you are using (POST/GET) you have access to the data like following:
<?php echo $_POST["faketxt"]; ?>
Secondly I suggest, you change you code slightly, to make it a bit more readable.
$('#btn').click(function() {
var primo = document.getElementById('faketxt');
var wordLimit = 5;
var words = primo.value.replace(/(<([^>]+)>)/ig,"").split(/\s/);
while (words.length > 0){
let div = createDiv();
div.append(words.splice(0,wordLimit).join(" "));
}
});
See your modified fiddle.
I am learning to code in JavaScript and my assignment was to find out what each line of this code means. I've tried to figure out some of the code but the part which confuses me most is the functions,'div classes',document.createElement('something') and the append.Child('something').I have researched on the internet but it is vaguely explained. Please can someone explain each line of the code;here is the code:
<!DOCTYPE html>
<html>
<head>
<title>Traffic lights</title>
</head>
<script>
var images = ['redlight.jpg', 'Red -yellow light.jpg', 'Green Light.jpg', 'Amber Light.jpg'];
var index = 0;
function buildImage() {
var img = document.createElement('img')
img.src = images[index];
document.getElementById('content').appendChild(img);
}
function changeImage() {
var img = document.getElementById('content').getElementsByTagName('img')[0]
index++;
index = index % 4;
img.src = images[index];
}
</script>
<body onload="buildImage();">
<div class="contents" id="content"></div>
<button onclick="setInterval(changeImage, 3000)">NextImage</button>
</body>
Thanks in advance
First Part:
function buildImage() {
var img = document.createElement('img')
img.src = images[index];
document.getElementById('content').appendChild(img);
}
This function
first create dynamic html tag of image
Assign Image src/path that contained in the var images =
['redlight.jpg', 'Red -yellow light.jpg', 'Green Light.jpg', 'Amber
Light.jpg'];
first get html tag that has id name content then append it means
to hold the previous and next images
Second Part:
function changeImage() {
var img = document.getElementById('content').getElementsByTagName('img')[0]
index++;
index = index % 4;
img.src = images[index];
}
This function
first initialize the img variable with the content/image that hold
in content div by access through an array index Increment to
access other image
using Modulus logic to get images that are on 4 index
Relace srcwith existing
This code displays an image when the page is loaded, then changes the image every 3 seconds after the user clicked the button once. Here is how it works:
buildImage is a function that creates an <img /> element (document.createElement) and set the source (img.src) attribute to one of the sources listed in the array images. Which one exactly depends on the index variable. It then adds the element to the html page, under the div with the id content (getElementById('content').appendChild(img)). So you end up with:
<div class="contents" id="content">
<img src="redlight.jpg" />
</div>
The function is called only once, when the page is loaded (see the onload attribute).
changeImage changes the image source (img.src). the code
document.getElementById('content').getElementsByTagName('img')[0]
means "get the div with id = content, then find all the html tags "img" and return the first one".
the code
index++; index = index % 4;
increments the index variable, but ensure it is never more than 4 (the size of your array, see the modulo operator).
Finally, the setInterval is a function which takes a function name and a duration in milliseconds. Once called, it will run the function every X ms.
!!
In this code, the setInterval function is called on every click. It might be problematic. I would change it if I were you.
document.createElement('img') creates a new <img /> tag. img.src = images[index] takes the path of the first element inside images (because index is set to 0 at the beginning) and sets the source (='redlight.jpg'). With document.getElementById('content').appendChild(img) you add the created <img src='redlight.jpg' /> tag inside your <div> with id = 'content'.
div class='contents' defines that your div is using the css class 'contents'. This css class handles the styling of your div element.
There are really good explanation for this all at http://www.w3schools.com/. You should study that page.
For the parts that you are insecure about.
Function
Functions is a big subject itself. It's a huge part of about every programming language. It's a way to in an effective way do something that you might want to do more than one time. Lets say you want to make a function that subtracts two values, but you want to use it for any value. Then you can create a function that takes two parameters and do the calculation...
function sub(x, y)
{
return x-y;
} // Very basic example
In that way you can send any values.
document.createElement('img')
Will simply just create an HTML-tag. In this case an 'img' tag. In your case they want to create one in order to place it inside another element.
Div classes(?) No idea what this is. Any examples?
document.getElementById("something").append.Child('something2')
What this will do is simply take an element by it's id. It can be a DIV or List etc. Then you simply put your element "something2" inside that element. So if something2 is an img, and something is a div. The result would be like:
<div>
<img>
</div>
Onload i.e when the page has being loaded it calls buildImage() function of javascript.This function creates a img tag and appends to the div which is of class 'contents'(Since index is 0 it loads a first image i.e img.src = images[index]).
And once you click on button every 3000 milliseconds its changes the image source to different image based on the index
I am creating an image which, when you click on it, sends you to one of four links. I have managed to code this, but the problem I am having is that it is completely random (only part of the point). What I would like to be able to do is to randomise the first click through, and then if the user goes back to the image, only leave them with the remaining three destinations, and then obviously two and one at the end. This is to stop them theoretically ending up at the same link every single time and not being able to access the other three.
Does anybody know how I might be able to do this? The code I have currently is:
<img src="IMAGE" onclick="randomLink();">
<script type="text/javascript">
var randomLink = function () {
var links = ["LINK 1","LINK 2","LINK 3","LINK 4",];
var max = (links.length)
var randomNumber = Math.floor(Math.random()*max);
var link = links[randomNumber];
window.location = "http://" + link;
}
</script>
You can simply remove the selected entry from the links array (i.e. using Array.splice). Next time the user clicks the link, you would generate a random number between 0 and 2 only and so on.
Hello again my JS saviors! I have another dilema:: I have a div titled "homebanner" that contains text and a background image. My client decided that he wanted the #homebanner to change on reload with 4 images/slides.
So, I did this to change the background::
JS CODE
jQuery(function($){
$('#homebanner').css({backgroundColor: "#fff"});
var totalCount = 4;
var num = Math.ceil( Math.random() * totalCount );
function setBGImage() {
var bgimage = 'http://bwpcommunications.com/TESTING/images/homepage/'+num+'.jpg';
$('#homebanner').css(
{
backgroundImage:"url("+bgimage+")",
});
}
setBGImage();
});
And it works great! So I'm stoked about that. But I can't figure out a way to have specific headline text to correspond with each image. Is this possible? Also, here's a link to the test site http://www.bwpcommunications.com/TESTING/. As you can see, when you refresh the page the image changes but the text does not.
Any help would be awesome!
Thanks,
Shadna
put whatever headline text options you want into an array
var hText = ["blue jeans", "red jeans", "ripped jeans", "plaid"];
then right after setting the background image, you can use the num variable to pick the corresponding text from the array (or if you want it random you can just do the random number generation again). Then it's just a matter of setting the text on the page.
$('#htxt').html(hText[num]);
or in plain javascript:
document.getElementById('htxt').innerHTML = hText[num];
depending how the images are numbered, you might need to do num - 1 since the array is 0 indexed.
I am trying to figure out how I can get just this code to refresh without the whole page refreshing.
Here is how it works.
Page is opened.
User is prompted to pick blue, green, or red.
Code looks at date, and then determines the hour.
Code is used to pick an image that represents the first digit of the hour. It also chooses the correct color of the image.
I'd like this code to refresh and display a new image as the time changes rather that having to reload the page to get the most current time.
If I make the entire page refresh to keep the clock updating every second, then I am prompted everytime to pick a color. I do want that to happen when the page is refreshed though, so I am looking to just refresh the portion of the page that the clock portion runs in.
I have abbreviated the code so that only the first image shows. There are minutes and seconds as well, but they all do pretty much the same thing as far as how they are determined and are displayed.
I have altered the code here to use images from a URL instead of the local folder that the file is kept in so that you can copy/paste it into your preffered HTML editor if you wish. I used TinyURL to shorten the URL in the interest of space.
<html>
<head>
<script type="text/javascript">
/*The following two variables are used to determine the hour.*/
var d = new Date();
var h = d.getHours();
/*The following variable is used to pick either 1 or "blank" for
the first hour digit and display the corresponding image*/
var h1
if(h>=1&&h<=9)
{
h1=new Array();
h1[0]=document.createElement('img');
h1[0].src= "http://tinyurl.com/3qqsggj ";
h1[1]=document.createElement('img');
h1[1].src= "http://tinyurl.com/3n75atp ";
h1[2]=document.createElement('img');
h1[2].src= "http://tinyurl.com/3tcha7o ";
}
else if(h>=13&&h<=21)
{
h1=new Array();
h1[0]=document.createElement('img');
h1[0].src= "http://tinyurl.com/3qqsggj ";
h1[1]=document.createElement('img');
h1[1].src= "http://tinyurl.com/3n75atp ";
h1[2]=document.createElement('img');
h1[2].src= "http://tinyurl.com/3tcha7o ";
}
else
{
h1=new Array();
h1[0]=document.createElement('img');
h1[0].src= "http://tinyurl.com/3s8wt8q ";
h1[1]=document.createElement('img');
h1[1].src= "http://tinyurl.com/3rz42gw ";
h1[2]=document.createElement('img');
h1[2].src= "http://tinyurl.com/3egvtho ";
}
/*The following function is used to take variable h1 and place
the image that corresponds to it into the table in the body*/
function timewrite()
{
document.getElementById("hour1").appendChild(h1[colnum]);
}
</script>
</head>
<!--Body runs function timewrite() upon loading-->
<body onload="timewrite()">
<table border="5" bordercolor="black">
<tr>
<td>
<span id="hour1"> <!--Here is where the h1 image goes--> </span>
</td>
</tr>
</table>
<script type="text/javascript">
/*The following variable is used to determine whether the image
for blue, green, or red should be shown.*/
var col=prompt("Please enter blue, green, or red.");
col=col.toLowerCase()
/*The following variable converts variable col into a number
so that it can easily be used to pick the correct h1 array
portion in the timewrite() function*/
var colnum
if(col=="blue")
colnum=0;
else if(col=="green")
colnum=1;
else if(col=="red")
colnum=2;
else
colnum=1;
</script>
</body>
</html>
Thanks in advance for your help.
I would wonder if setTimeout and/or setInterval would not be effective beause the variables are keeping their values? As in, are the"d" and "h" variables looing at the time once, taking on those values, and then not changing them unless the page is refreshed? Do I need to put the variables in a function or something like that, so that they can be refreshed, or will they automatically update as the time changes?
I am relatively new to JavaScript by the way, in case you were wondering.
Here is a link to the entire code if that will help. I do realize that it is not the most efficient way to accomplish what I am doing, but I am new to JavaScript, and also, this is a project that needs to contain several different programming concepts. I have it commented pretty well.
http://cid-7cc3864d98261b77.office.live.com/browse.aspx/Shared%20Files?uc=1
What you need to do is just put your method into a timeout so it updates at a later time (you seem to have already extracted the info to a method called timewrite:
setInterval(function()
{
timewrite();
}, 3000);
Effectively, this sets up a recurring call to timewrite every 3 seconds.
Use setTimeout() or setInterval() to re-run your code as necessary.