Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
How would I go about replacing the old 'box' with a white/no background?
var counter = 11;
var check = 0;
var boxes = ["box_1","box_2","box_3","box_4"];
clock = setInterval(function() {
counter--;
if(counter==0) {
clearInterval(clock);
document.getElementById("counter").innerHTML="Time Left: 0 seconds.";
} else {
var box = boxes[Math.floor(Math.random()*boxes.length)];
document.getElementById("counter").innerHTML="Time Left: " + counter.toString() + " seconds.";
document.getElementById(box).style.backgroundColor="#000";
}
}, 1000);
I attempted to store the box as old_box -> old_box = box which didn't work.
It seems people are misunderstanding.
I want to store the box value so I can call it back on the next loop and set it to white, while the new box can be set to black.
You need to remember the box:
var counter = 11;
var check = 0;
var boxes = ["box_1","box_2","box_3","box_4"];
var lastbox = false;
clock = setInterval(function() {
counter--;
if(counter==0) {
clearInterval(clock);
document.getElementById("counter").innerHTML="Time Left: 0 seconds.";
} else {
if (lastbox) {
document.getElementById(lastbox).style.backgroundColor = "#FFF";
}
lastbox = boxes[Math.floor(Math.random()*boxes.length)];
document.getElementById("counter").innerHTML="Time Left: " + counter.toString() + " seconds.";
document.getElementById(lastbox).style.backgroundColor="#000";
}
}, 1000);
jsBin DEMO
Simply set the background to #000 to the element
which index-matches the random number (r==i)
function $id(_) { return document.getElementById(_); }
function $el(_) { return document.querySelectorAll(_); }
function game() {
if (!c) clearInterval( clock );
$cou.innerHTML = "Time Left: "+ (c--) +" seconds.";
var r = ~~(Math.random()*n);
for(var i=0; i<n; i++) $box[i].style.backgroundColor = i==r?"#000":"#fff";
}
var $box = $el("[id^=box_]"),
$cou = $id("counter"),
n = $box.length,
c = 10,
clock = setInterval(game, 1000);
As you can see I've also used some nice reusable functions so further in your project you don't need to loose your fingers writing all over the place document.getElementById but simply:
$id("elementID")
or if you want to get more elements using a wide spectrum of selectors: (slower)
$el(".elements") // [] array collection
$el("[id^=prefix]") // [] array collection
$el("input") // [] array collection
Related
I'm trying to update multiple progress bars at once on a Django template, but what I find is that it only updates that last one. I'm not sure why the for loop here isn't working. Can anyone provide any guidance. Thank you in advance.
I pull in the values that I need from the HTML into objects. From there I use a for loop to adjust the width of the progress bar dynamically, but it's only responding to the last div to go through the for loop.
var a = 0;
var counts = []
// Nestling relevant values in objects for for loop
var five = {
bar: document.getElementById("fivesBar"),
quantity: $("#fivesGiven").text()
}
var four = {
bar: document.getElementById("foursBar"),
quantity: $("#foursGiven").text()
}
var three = {
bar: document.getElementById("threesBar"),
quantity: $("#threesGiven").text()
}
var two = {
bar: document.getElementById("twosBar"),
quantity: $("#twosGiven").text()
}
var one = {
bar: document.getElementById("onesBar"),
quantity: $("#onesGiven").text()
}
counts.push(one, two, three, four, five);
console.log("Checking the list for counts:", counts);
// Grabbing percent complete to dynamically complete the progress bar
$(document).ready(function () {
for (b = 0; b < counts.length; b++) {
quantity = counts[b].quantity;
console.log(quantity);
quantity = parseInt(quantity)
bar = counts[b].bar;
if (a === 0) {
var width = 0;
var run = setInterval(fillratings, 5);
function fillratings() {
if (width === quantity) {
clearInterval(run);
a = 0;
} else {
width++;
bar.style.width = width + "%";
console.log(width);
}
}
}
}
});
I'm working on trying to create a random image generator that will show a random image in Javascript. I've been able to make it show a random image via the Javascript math and using random variables. But sadly I'm still yet to be eligible to make my code repeat itself.
I know its probably very simplistic but as you know, we all start from somewhere. I've tried my best to compact my code and I have looked at other stackoverflow recourses but im still in no luck.
A quick overview of what happens, you are meant to be able to press a button and then, a selected random image is replaced by the current one.
What I want: to be able to press a button and then it will proceed to cycle through the random images 'x' times.
My code:
function imgRandom() {
var myImages1 = new Array();
myImages1[1] = "images/Random/Icon1.png";
myImages1[2] = "images/Random/Icon2.png";
myImages1[3] = "images/Random/Icon3.png";
myImages1[4] = "images/Random/Icon4.png";
myImages1[5] = "images/Random/Icon5.png";
myImages1[6] = "images/Random/Icon6.png";
myImages1[7] = "images/Random/Icon7.png";
myImages1[8] = "images/Random/Icon8.png";
myImages1[9] = "images/Random/Icon9.png";
myImages1[10] = "images/Random/Icon10.png";
myImages1[11] = "images/Random/Icon11.png";
myImages1[12] = "images/Random/Icon12.png";
myImages1[13] = "images/Random/Icon13.png";
myImages1[14] = "images/Random/Icon14.png";
myImages1[15] = "images/Random/Icon15.png";
myImages1[16] = "images/Random/Icon16.png";
myImages1[17] = "images/Random/Icon17.png";
myImages1[18] = "images/Random/Icon18.png";
myImages1[19] = "images/Random/Icon19.png";
myImages1[20] = "images/Random/Icon20.png";
myImages1[21] = "images/Random/Icon21.png";
myImages1[22] = "images/Random/Icon22.png";
myImages1[23] = "images/Random/Icon23.png";
var rnd = Math.floor(Math.random() * myImages1.length);
if (rnd == 0) {
rnd = 1;
}
document.getElementById("gen-img").src = myImages1[rnd];
}
<center>
<p>
<img id="gen-img" class="character-image" src="images/QuestionMark.png" style="width:180px;height:310px;">
</p>
<p>
<input type="button" class="button" value="Choose" onclick="setTimeout(imgRandom, 3000);" />
</p>
</center>
I hope this isn't too confusing, i'll be active for a long time if you're able to help! Thanks,
David.
I refactored your code a bit with an possible approach Here's the fiddle: https://jsfiddle.net/mrlew/d2py2jvb/
I commented with some explanations.
/* some flags you can set */
var timesTocycle = 10;
var totalImagesToCreate = 23;
var timeBetweenCycle = 3000;
/* global variables */
var allMyImages = [];
var timesCycled = 0;
/*
function to create your images path.
Called once when you load your page.
*/
function createMyImages(total) {
for (var i=0; i<total;i++) {
var imageNumber = i+1;
var path = getImagePath(imageNumber);
allMyImages.push(path);
}
}
/* separated your path getter */
function getImagePath(imageNumber) {
return "images/Random/Icon" + imageNumber + ".png";
}
/* this is the function called when you press the button and when one cycle ends */
function triggerRandomImage() {
if (timesCycled >= timesTocycle) return;
setTimeout(displayRandomImage, timeBetweenCycle);
}
/* random integer javascript function */
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
/* function called on setTimeout */
function displayRandomImage() {
var rnd = getRandomInt(0,allMyImages.length-1);
var imageToDisplayPath = allMyImages[rnd];
document.getElementById("gen-img").src = imageToDisplayPath;
timesCycled++;
triggerRandomImage();
/* debug info */
document.getElementById('info').innerText = "(showing: " + imageToDisplayPath + ", cycle: " + timesCycled + ", max: " + timesTocycle + ")";
}
/* call this function to populate the allMyImages array */
createMyImages(totalImagesToCreate);
I believe what you want is for loop. Let me demonstrate with your code:
var count = 10; //number of times to run the for loop
for (i = 0; i < count; i++){
var rnd = Math.floor(Math.random() * myImages1.length);
if (rnd == 0) {
rnd = 1;
}
document.getElementById("gen-img").src = myImages1[rnd];
}
The above code would run the randomizing bit 10 times (= 10 images). Now, I have not tested it yet, but I believe that the images would flash by really quickly. Also, unrelated to the question you may want to read about Javascript arrays.
I have a slideshow on my website with left and right buttons.
Like this (http://i.prntscr.com/863ad10cfd4e4f1ea9b90721cc6582e8.png).
I am using angular to change the image on left and right.
As you can see in the function I increase the value
/*SlideShow Pictures*/
$scope.picture_1 = "./images/photos/watch.jpg";
$scope.picture_2 = "./images/photos/watch.jpg";
$scope.picture_3 = "./images/photos/watch.jpg";
$scope.picture_4 = "./images/photos/watch.jpg";
$scope.picture = $scope.picture_1;
$scope.picture_value = 1;
$scope.image_change_right = function () {
if ($scope.picture_value < 4)
{
$scope.picture_value = $scope.picture_value + 1;
$scope.picture = ('$scope.picture_' + $scope.picture_value);
console.log($scope.picture_value);
}
else{
$scope.picture_value = 1;
$scope.picture = ('$scope.picture_' + $scope.picture_value);
console.log($scope.picture_value);
}
}
Above is the function called for button right press.
The function increases the variable by 1 and adds it to the string to call the new variable. In the console log it looks great! However I think it is only showing as a string --- it is not actually setting the value of scope.picture to the variable.
How can I set this to not be a string but as a valid variable?
Thanks everyone!
A better way would be like this:
The Controller:
// The array of picture links.
$scope.pictures = [
"./images/photos/watch.jpg",
"./images/photos/watch.jpg",
"./images/photos/watch.jpg",
"./images/photos/watch.jpg"
];
$scope.current = 0; // Initialize the current pictures place in the array.
$scope.picture = $scope.pictures[$scope.current]; // Set the current picture.
// The direction is either 1 or -1;
$scope.changePicture = function (direction) {
$scope.current += direction; // add or remove one depending on direction.
$scope.current %= $scope.pictures.length; // Normalize the number based on the length of the pictures array.
console.log($scope.picture);
}
The Html:
<img src="{{picture}}">
<button ng-click="changePicture(1)">Next</button>
<button ng-click="changePicture(-1)">Previous</button>
Why don't you use an array with image links like this?
/*SlideShow Pictures*/
$scope.pictures = ["./images/photos/watch.jpg", "./images/photos/watch.jpg", "./images/photos/watch.jpg", "./images/photos/watch.jpg"];
$scope.picture = $scope.pictures[0];
$scope.picture_value = 0;
$scope.image_change_right = function () {
if ($scope.picture_value < 4)
{
$scope.picture_value = $scope.picture_value + 1;
$scope.picture = $scope.pictures[$scope.picture_value];
console.log($scope.picture_value);
}
else{
$scope.picture_value = 0;
$scope.picture = $scope.pictures[$scope.picture_value];
console.log($scope.picture_value);
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
With my code, the "lights" turn on one at a time and then turn off one at a time but I want there to only be one light on at a time. I want the previously turned on light to turn off before the next one comes on.
http://jsfiddle.net/JoshKerr98/hrpasw0p/
$(document).ready(function() {
var colourInfo = [
{ id: 'square2id', color: ['#FFFF00','#000000'] },
{ id: 'square3id', color: ['#00FF00','#000000'] },
{ id: 'square4id', color: ['#0000FF','#000000'] },
{ id: 'square1id', color: ['#FFFFFF','#000000'] },
{ id: 'square5id', color: ['#FFA500','#000000'] },
];
var changeIndex = 0, colorIndex = 0;
var changeNextBoxColor = function() {
if (!colourInfo[changeIndex]) {
changeIndex = 0;
colorIndex += 1;
}
var info = colourInfo[changeIndex],
color = info.color[colorIndex%info.color.length];
$('#' + info.id).css('background-color', color);
changeIndex += 1;
setTimeout(changeNextBoxColor, 2000);
};
setTimeout(changeNextBoxColor, 2000);
});
Please read through the comments as well.
JSFiddle
$(document).ready(function() {
var colourInfo = [
{ id: 'square2id', color: ['#FFFF00','#000000'] },
{ id: 'square3id', color: ['#00FF00','#000000'] },
{ id: 'square4id', color: ['#0000FF','#000000'] },
{ id: 'square1id', color: ['#FFFFFF','#000000'] },
{ id: 'square5id', color: ['#FFA500','#000000'] }
];
var colorIndex = 0;
// This function sets the color of a box with a certain id
var setColor = function(squareId, color) {
$('#' + squareId).css('background-color', color);
};
// This will make the colorIndex's box black, then increment the index
// and highlight the next box
var changeNextBoxColor = function() {
// Need to make sure to mod (%) by the length of colourInfo
// so that the index doesn't go out of bounds.
var revertSquare = colourInfo[colorIndex % colourInfo.length];
setColor(revertSquare.id, revertSquare.color[1]);
// By using ++colorIndex, you increment colorIndex and the left hand value is
// the incremented value so that changeSquare corresponds to the next element
// in colourInfo
var changeSquare = colourInfo[(++colorIndex) % colourInfo.length];
setColor(changeSquare.id, changeSquare.color[0]);
};
// This repeats the function every 2 seconds (so you don't need to call setTimeout
// inside of changeNextBoxColor).
setInterval(changeNextBoxColor, 2000);
});
I just recently startet with Javascript and had the following Idea:
I would like to have short text (maybe just a headline) on my website which single chars will have a rainbow-color that travells from left to right.
So I wrote this short script.
var Count = 6;
setInterval(function RainbowColorFunction()
{
var Rainbow_Colors = ["#FFFF00","#FF7F00","#FF0000","#9400D3","#4B0082","#0000FF","#00FF00"];
var Color_Element = document.getElementById("RainbowColorText");
var Color_String = Color_Element.textContent;
var Letter = "";
var NewText = "";
var RainbowCount = Count;
var Stringlenght = Color_String.length;
Color_String = reverse(Color_String);
for (var i = Stringlenght, min = 0; i > min; i--)
{
Letter = Color_String.charAt(i -1);
if(Letter == " ")
{
NewText += Letter;
continue;
}
NewText += Letter.fontcolor(Rainbow_Colors[RainbowCount]);
RainbowCount--;
if(RainbowCount < 0){RainbowCount = 6;}
}
Count--;
if(Count < 0){Count = 6;}
Color_Element.innerHTML=NewText;
}, 60);
function reverse(s) {
return (s === '') ? '' : reverse(s.substr(1)) + s.charAt(0);
}
My Issue is now that the text changes colour from right to left. But I want it the other way around. Without the reverse Function my text is a big mess, but I am quite sure thats the point where I have to change things.
Short answer: just increment instead of decrement Count:
Count++;
if(Count>6 ){Count = 0;}
Other observations:
it's "length" not "lenght"
try to use singlequotes in Javascript and doublequotes for html
attributes. You will see that writing html in javascript and the
reverse become simple.
also the naming conventions for Javascript usually use lowercase
Camel variables, uppercase is reserved for class names, public
members maybe, etc. Whatever you use, be consistent after you choose.
you can move a lot of the function outside the interval, like the
part that gets the element.
you don't need to name the function that you give setInterval as an
attribute. Alternately you can name it then use
setInterval(functionName,500) on a separate line.
If I would do it, I would try to encapsulate it better. Here is my 5 minute effort:
function RainbowColor(elem)
{
this.Colors=["#FFFF00","#FF7F00","#FF0000","#9400D3","#4B0082","#0000FF","#00FF00"];
this.Speed=16.66;
this.Direction=1;
this._offset=0;
this._elem=elem;
this._originalContent=elem.innerHTML;
}
RainbowColor.prototype={
Colorize:function() {
var self=this;
function mod(v,l) {
var result=v%l;
return result<0?result+l:result;
}
function rainbowColorFunction() {
var text=self._elem.textContent;
var result='';
var k=self._offset;
for (var i=0; i<text.length; i++) {
var letter=text.charAt(i);
if (!letter) continue;
result+=letter.fontcolor(self.Colors[mod(k,self.Colors.length)]);
k-=self.Direction;
}
self._elem.innerHTML=result;
self._offset++;
}
this._interval=setInterval(rainbowColorFunction,1000/self.Speed);
},
Stop:function() {
if (this._interval) clearInterval(this._interval);
},
Restore:function() {
this._elem.innerHTML=this._originalContent;
}
}
var colorizer=new RainbowColor(document.getElementById('RainbowColorText'));
colorizer.Colorize();
setTimeout(function() { colorizer.Direction=-1; },5000);
setTimeout(function() { colorizer.Colors=['lightgray','gray','black'] },10000);
setTimeout(function() { colorizer.Speed=10; },15000);
setTimeout(function() { colorizer.Stop(); },20000);
setTimeout(function() { colorizer.Restore(); },23000);
I also looked into using CSS to create a text gradient, but I couldn't find any cross-browser solution (More details : How do I use a gradient as a font color in CSS?)
Speaking of cross-browser, perhaps you should use jQuery to get and set HTML content in order for this to work everywhere correctly.