Reputation: 89
In my javascript program I have created object and 5 instances. I have created array. After that I am getting current minutes by date object and array length. Now I want to do following: 1). Determine the index to retrieve the object by getting the modulo of minutes with the length of the array. 2). Display the link to the URL. 3). Set the timer to run every minute that means We should be able to see a different link every minute.
To determine index I calculated length of array and modulo of minute. So still I am confused retrieving object by getting the modulo of minutes with the length of the array.
I have also set time interval which should change link every minutes. but it doesn't seem to work. Can anyone help me ?
code:
<!DOCTYPE html>
<html>
<head>
<style>
div p {
text-align: center;
font-family: monospace;
font-size: 30px;
}
a{
text-align: center;
text-decoration: none;
color: #3bb570;
}
a:hover{
color:#efa5db
}
</style>
<title>lab15</title>
</head>
<body background="lab15_images/pink.jpg">
<div class="myDiv" id="div">
<p> Click on the link to see a website. </p>
<!-- <p><b><a href="#" id="link"> </a></b></p> -->
<p id="link"> </p>
</div>
<script>
function web(url, name) {
this.url = url;
this.name = name;
}
var myWeb = new site("http://www.cnn.com/", "CNN");
var myWeb2 = new site("http://www.bbc.com/news", "BBC");
var array = new Array(myWeb, myWeb2);
setInterval(changeLink, 60000);
function changeLink() {
var n = new Date().getMinutes();
var site = instances[index]
var counter = 0;
var ele = document.getElementbyId("link");
ele.innerHTML = instances[counter];
counter++;
if(counter >= instances.length) {
counter = 0;
}
var a = document.createElement('a');
var myDiv = document.getElementbyId("div");
a.href = site.the_url;
myDiv.appendChild(a);
document.body.appendChild(myDiv);
}
</script>
</body>
</html>
Upvotes: 0
Views: 85
Reputation: 92440
The modulus of a number m
m % n
will never be larger than n - 1
. So you have minutes from 0 - 60 and you want to convert that into array index 0 - 4, you just need minutes % array.length
. In other words to get a particular site given a minute you only need:
var n = new Date().getMinutes();
var index = n % instances.length
var site = instances[index]
You actually don't need var mod = n % 60;
because d.getMinutes()
will always return a number between 0 and 59 already.
I would put those calculations inside your changeLink()
function:
function changeLink() {
var n = new Date().getMinutes();
var index = n % instances.length
var site = instances[index]
var a = document.createElement('a');
var myDiv = document.getElementById("div");
myDiv.appendChild(a);
a.title = site.website_name;
a.href = site.the_url;
document.body.appendChild(myDiv);
}
This leaves you with another problem: what happens when you have displayed all your sites? Do you just keep repeating and append the same sites? Do you stop?
Upvotes: 2