Preint one specific array element, when I click stop button - javascript

I am repeatedly looping through an array, my aim is to stop the loop and printout a specific element in the array and display it through span id="fruit". please see code below :
var title = ['233249864597', '233209425159', '233201112221', '233546056136', '233266549303', '233209409846', '233501345825', '233248446422', '233546112136', '233541006033', '233502089334', '233552476293', '233268222280', '233202240898'];
var i = 0; // the index of the current item to show
var animate = setInterval(function() {
// setInterval makes it run repeatedly
document
.getElementById('fruit')
.innerHTML = title[i++];
// get the item and increment
if (i == title.length) i = 0;
// reset to first element if you've reached the end
}, 15);
function stop() {
clearInterval(animate);
}
<h1>THE WINNER IS : </h1>
<h1><span id="fruit"></span></h1>
<center><button onclick="stop()">STOP</button></center>

You mean
const title = ['233249864597', '233209425159', '233201112221', '233546056136', '233266549303', '233209409846', '233501345825', '233248446422', '233546112136', '233541006033', '233502089334', '233552476293', '233268222280', '233202240898'];
const winner = title[3]; // for example
var i = 0; // the index of the current item to show
var animate = setInterval(function() {
// setInterval makes it run repeatedly
document
.getElementById('fruit')
.innerHTML = title[i++];
// get the item and increment
if (i == title.length) i = 0;
// reset to first element if you've reached the end
}, 15);
function stop() {
clearInterval(animate);
document
.getElementById('fruit')
.innerHTML = winner;
}
<h1>THE WINNER IS : </h1>
<h1><span id="fruit"></span></h1>
<center><button onclick="stop()">STOP</button></center>

var title = ['233249864597', '233209425159', '233201112221', '233546056136', '233266549303', '233209409846', '233501345825', '233248446422', '233546112136', '233541006033', '233502089334', '233552476293', '233268222280', '233202240898'];
var i = 0; // the index of the current item to show
var animate = setInterval(function() {
// setInterval makes it run repeatedly
//document.getElementById('fruit').innerHTML = title[i++];
// get the item and increment
if (i == title.length) i = 0;
// reset to first element if you've reached the end
}, 15);
function stop() {
clearInterval(animate);
document.getElementById('fruit').innerHTML = title[i++];
}
<h1>THE WINNER IS : </h1>
<h1><span id="fruit"></span></h1>
<center><button onclick="stop()">STOP</button></center>

How about this?
I changed the numbers to fruits because.. well... I just wanted to write out some fruits.
But they can be changed back to numbers ofc.
var fruits = ['Apple', 'Banana', 'Pineapple', 'Orange', 'Kiwi', 'Watermelon'];
var i = 0; // the index of the current item to show
var animate = setInterval(function() {
i++
document
.getElementById('fruit')
// use modulus operator to stay inside array
.innerHTML = fruits[i % fruits.length];
}, 15);
function stop() {
clearInterval(animate);
}
<h1>THE WINNER IS : </h1>
<h1><span id="fruit"></span></h1>
<center><button onclick="stop()">STOP</button></center>

Related

Using a button to display different texts using javascript

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;
}

Disable the click and reset it (Javascript Vanilla)

I have a problem. I created the following code! when you click on a button, a timer that lasts 3 seconds starts, the problem is that if I double click the button, the seconds go crazy, I would like to make sure that the click is reset as soon as the timer reaches 0! so that clicking again the timer always starts from 3 seconds!
document.getElementById("titolo").style.display="block"
count = 3 ;
setInterval(function(){
count--;
if(count>=0){
id = document.getElementById("titolo");
id.innerHTML = count;
}
if(count === 0){
document.getElementById("titolo").style.display="none" ;
}
},1000);
setInterval returns an ID that you can pass to clearInterval to cancel it. When the user clicks, cancel the existing ID and call setInterval again to reset it.
Capture the return value of setInterval so that later you can use it to call clearInterval.
You should disable (or hide) the button (or other element) that the user can click to start the count down.
Make sure to always declare your variables with var, let or const.
Don't use innerHTML when you only want to assign text (not HTML entities). For text (like the string representation of a counter) use textContent.
Here is how it could work:
let start = document.getElementById("start");
let id = document.getElementById("titolo");
start.addEventListener("click", function () {
start.disabled = true;
id.style.display = "block";
id.textContent = "3";
let count = 3;
let timer = setInterval(function(){
count--;
id.textContent = count;
if (count === 0) {
id.style.display = "none" ;
clearInterval(timer);
start.disabled = false;
}
}, 1000);
});
<button id="start">Start</button>
<div id="titolo"></div>
The function setInterval returns the unique id representing the interval. You can call the function clearInterval to delete that interval.
Example:
var intervalID = setInterval(function () { }, 0);
clearInterval(intervalID);
Example combined with your code:
var intervalID, count, dom = document.querySelector("#titolo");
document.querySelector("#button").addEventListener("click", onClick);
function onClick() {
clearInterval(intervalID);
dom.style.display = "block";
dom.textContent = 3;
count = 3;
intervalID = setInterval(function() {
count -= 1;
if (count >= 0) dom.textContent = count;
else {
dom.style.display = "none";
clearInterval(intervalID);
}
}, 1000);
}
<div id="titolo"></div>
<button id="button">Button</button>

jquery animate background images in an infinite loop

What would be the best way to have an array of background images and loop through them using js/jquery in an infinite loop?
this is what I have so far:
//ANIMATE JUMBOTRON BACKGROUND IMAGE
$(document).ready(function() {
var backgroundImage = [
'url(/static/images/slideshow/slide0.jpg)',
'url(/static/images/slideshow/slide1.jpg)',
'url(/static/images/slideshow/slide2.jpg)',
'url(/static/images/slideshow/slide3.jpg)',
'url(/static/images/slideshow/slide4.jpg)'
];
$('.jumbotron').css('background-image', backgroundImage[0]);
})
this is obviously just the array and simple css, but I am a bit lost on how to loop through the array?
A counter variable and a window.setInterval should do you. Increment the counter every time the interval'd function runs - once you hit the length of the background image array reset it back down to 0.
var backgroundImages = [
'url(/static/images/slideshow/slide0.jpg)',
'url(/static/images/slideshow/slide1.jpg)',
'url(/static/images/slideshow/slide2.jpg)',
'url(/static/images/slideshow/slide3.jpg)',
'url(/static/images/slideshow/slide4.jpg)'
],
backgroundImageCounter = 0,
jumbotron = $('.jumbotron');
window.setInterval(function() {
jumbotron.css('background-image', backgroundImages[backgroundImageCounter]);
backgroundImageCounter++;
if(backgroundImageCounter >= backgroundImages.length) {
backgroundImageCounter = 0;
}
}, 5000);
There is this thing called setInterval.
var count = 0;
var div = document.getElementById('a');
var btn = document.getElementById('b');
var interval = setInterval(function(){
div.innerText = count;
count++;
}, 1000);
btn.addEventListener('click', function(){
clearInterval(interval);
});
<div id="a">0</div>
<button id="b">Stop</button>

Show elements of array one by one - Jquery

So I have a button on which I want to display each element of my array for a few seconds. This is my html code:
<button class="btn" id="random">Start</button>
I have made an array with jQuery that I want to use to change the buttons text:
$(document).ready(function() {
$("#random").on("click", loop);
});
var array = ["el1","el2","el3"];
function loop() {
for (i = 0; i < array.length; i++) {
$("#random").html(array[i]);
}
var random = Math.floor(Math.random() * array.length) + 1;
$("#random").html(array[random]);
}
The for loop is supposed to do what I want but I can't find a way to delay the speed, it always just shows the last line of code. When I try setTimeout or something it just looks like it skips the for loop.
My proposal is to use IIFE and delay:
var array = ["el1","el2","el3", "Start"];
function loop(){
for (i = 0; i < array.length; i++){
(function(i) {
$("#random").delay(1000).queue(function () {
$(this).html(array[i]);
$(this).dequeue();
});
})(i);
}
}
$(function () {
$("#random").on("click", loop);
});
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<button class="btn" id="random">Start</button>
Basically, a for loop will not help you. It runs with the max speed it can. And delaying it would do no good in js (you would just freeze the browser). Instead, you can just make a function that will execute itself with a delay. Kinda recursion, but not entirely. Below would make the trick.
https://jsfiddle.net/7dryshay/
$(document).ready(function() {
$("#random").on("click", function (event) {
// texts to cycle
var arr = ["el1","el2","el3"];
// get the button elem (we need it in this scope)
var $el = $(event.target);
// iteation function (kinda recursive)
var iter = function () {
// no more stuff to display
if (arr.length === 0) return;
// get top of the array and set it on button
$el.text(arr.shift());
// proceed to next iteration
setTimeout(iter, 500);
}
// start first iteration
iter();
});
});
Use setInterval() and clearInterval()
$(document).ready(
function() {
$("#random").on("click", loop);
}
);
var array = ["el1", "el2", "el3"];
var int;
function loop() {
var i = 0; // variable for array index
int && clearInterval(int); // clear any previous interval
int = setInterval(function() { //store interval reference for clearing
if (i == array.length) clearInterval(int); // clear interval if reached the last index
$("#random").text(i == array.length ? 'Start' : array[i++]); // update text with array element atlast set back to button text
}, 1000);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="btn" id="random">Start</button>
UPDATE : If you need to implement it using for loop and setTimeout() then do something like this
var array = ["el1", "el2", "el3", "Start"];
function loop() {
for (i = 0; i < array.length; i++) {
(function(i) {
setTimeout(function() {
$("#random").html(array[i]);
}, i * 1000);
})(i);
}
}
$(function() {
$("#random").on("click", loop);
});
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<button class="btn" id="random">Start</button>

Textarea disappears after setting value

Here's what I'm trying to do:
Type initials (e.g. MS,AK,LT) by clicking on "Enter Names". This saves a string, which I then turn into an array (nameArray) in order to get each set of initials. After reordering these randomly, I want to place some of the initials into the textareas, but that's where things go wrong.
Here's what's wrong:
the initials display for a moment, then disappear after the function executes. (ALSO, I'm trying to have a div (with text "randomizing...") that is otherwise hidden, show itself for 4 seconds (4000 ms) while the initials are being reordered to indicate as such. That's what the setTimeout is for...but that doesn't work either. The div disappears along with the text). Why are these only in coordination with the execution of the function?
Here's the JS code:
var nameArray;
window.onload = pageLoad;
function pageLoad() {
$("#randomizingNotification").hide();
$("#prev_arrow").click(prevUser);
$("#next_arrow").click(nextUser);
$("#enter_names").click(orderNames);
}
function orderNames() {
nameArray = getNames();
randomizeNames();
displayNames();
}
function getNames() {
var initialsString = prompt("Please enter initials, separated by a comma (e.g LK,AS,NM)");
nameArray = initialsString.split(",");
return nameArray;
}
function randomizeNames() {
$("#randomizingNotification").show();
var timer = setTimeout(function(){randomize(nameArray);},4000);
$("#randomizingNotification").hide();
clearTimeout(timer);
}
function randomize(array) {
for (var i = 0; i < array.length; i++ ) {
var randNum = Math.floor(array.length*Math.random()) //random number between 0 and length of array (rounded down
var temp = array[i];
array[i] = array[randNum];
array[randNum] = temp;
}
}
function displayNames() {
var curr, up, prev, current, upcoming, previous;
curr = 0;
up = 1;
prev = null
current = nameArray[curr];
upcoming = nameArray[up];
$("#upcoming_pick").val(upcoming);
$("#current_pick").val(current);
}
Here's the relevant HTML code:
<body>
<div id="header">
<div id="randomizeNotContDiv">
<div id="randomizingNotification">randomizing...</div>
</div>
<div id="page_title"><h1>Welcome to Classtech Shift Scheduler!</h1></div>
<div id="helper_functions_div">
<div id="enter_names_div">
Enter Names
</div>
</div>
<div id="main_content">
<div id="name_tracker">
<div><img src="Images/prev_arrow.png"/></div>
<textarea name="upcoming_pick" cols="10" rows="1" class="picker_names" id="upcoming_pick"></textarea>
<textarea name="current_pick" cols="10" rows="1" class="picker_names" id="current_pick"></textarea>
<textarea name="previous_pick" cols="10" rows="1" class="picker_names" id="previous_pick"></textarea>
<div><img src="Images/next_arrow.png"/></div>
</div>
You've got at least few issues, but the main problem is the structure of your setTimeout. A setTimeout is like an AJAX call in that it's non-blocking. Anything inside the function you pass to it will only execute when the timer is done, while code that comes after it will execute immediately.
I've reorganized the hiding of your randomization message and the displayNames function to go inside of the setTimeout function and things work fine.
Here it is in a fiddle: http://jsfiddle.net/nate/LB6dz/
And here's the code:
var nameArray;
window.onload = pageLoad;
function pageLoad() {
$("#randomizingNotification").hide();
$("#enter_names").click(orderNames);
}
function orderNames(event) {
// Prevent the link's default action
event.preventDefault();
nameArray = getNames();
randomizeNames();
}
function getNames() {
var initialsString = prompt("Please enter initials, separated by a comma (e.g LK,AS,NM)");
nameArray = initialsString.split(",");
return nameArray;
}
function randomizeNames() {
$("#randomizingNotification").show();
var timer = setTimeout(function (){
randomize(nameArray);
// These items need to be inside the timeout, so they only run once it's done
$("#randomizingNotification").hide();
displayNames();
}, 4000);
// No need to clearTimeouts after they're done... they only run once
// clearTimeout(timer);
}
function randomize(array) {
for (var i = 0; i < array.length; i++ ) {
var randNum = Math.floor(array.length*Math.random()) //random number between 0 and length of array (rounded down
var temp = array[i];
array[i] = array[randNum];
array[randNum] = temp;
}
}
function displayNames() {
var curr, up, prev, current, upcoming, previous;
curr = 0;
up = 1;
prev = null
current = nameArray[curr];
upcoming = nameArray[up];
$("#upcoming_pick").val(upcoming);
$("#current_pick").val(current);
}

Categories