javascript: How do I properly loop this function? - javascript

I am new to coding with js, and have tried many different ways to loop this code, as well as asking a friend of mine who is a bit more proficient than I am, and he was incorrect as well. I looked up how to use loops in js as well, and I seem to be stumped, so if you could also give me a basic explanation as to how loops in js work, that'd be great!
ORIGINAL CODE
function partA() {
var classes1 = document.getElementsByClassName('_jvpff _k2yal _csba8 _i46jh _nv5lf'); // finds follow button
var Rate1 = classes1[0];Rate1.click(); // clicks button1
}
setTimeout(partB, 20000); // begins func. B about 17 seconds after func a has been completed
function partB() {
var classes2 = document.getElementsByClassName('_de018 coreSpriteRightPaginationArrow'); // finds “next” arrow
var Rate2 = classes2[0];Rate2.click(); // clicks next arrow
}
partA(); // runs functions
The original code itself works fine, but it never seems to work with any loops I use.
Most Recent Loop Attempt
- Note: failed, obviously
function partA() {
var classes1 = document.getElementsByClassName('_jvpff _k2yal _csba8 _i46jh _nv5lf'); // finds follow button
var Rate1 = classes1[0];Rate1.click(); // clicks button1
}
setTimeout(partB, 20000); // begins func. B about 17 seconds after func a has been completed
function partB() {
var classes2 = document.getElementsByClassName('_de018 coreSpriteRightPaginationArrow'); // finds “next” arrow
var Rate2 = classes2[0];Rate2.click(); // clicks next arrow
}
partA(); // runs functions
for (i = 0; i < 30; i++) {
text += “The number is ” + i + “<br>”;
}
Thank you in advance!
- Michael
Any tips to just generally improve the code would also be appreciated.

Still can't work out exactly what you're after (looks like: trying to automate some repetitive task in some page for which you don't control the source)
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<title>JS Loop Example?</title>
<script>
function foo() {
var div = $("#x")[0];
div.innerHTML = "foo was clicked";
for (i = 0; i < 5; i++) {
div.innerHTML += "<br />!";
}
setTimeout(function(){ $('.barButton').click() }, 3000)
}
function bar() {
var div = $("#x")[0];
while (div.firstChild) {
div.removeChild(div.firstChild);
}
var wibble = document.createTextNode('bar was clicked');
div.appendChild(wibble);
for (i = 0; i < 5; i++) {
div.appendChild(document.createElement('br'));
wibble = document.createTextNode('?');
div.appendChild(wibble);
}
setTimeout(function(){ $('.fooButton').click() }, 3000)
}
</script>
</head>
<body onload='setTimeout(foo, 3000)'>
<script>
// Up until the close of the body, I can just write into the document.
document.write('<div id="x" class="stuffGoesHere">');
document.write('some random text<br />');
for (i = 0; i < 5; i++) {
document.write('#<br />');
}
document.write('</div>');
document.write('<input type="button" class="fooButton" value="foo" onClick="foo()" />');
document.write('<input type="button" class="barButton" value="bar" onClick="bar()" />');
</script>
</body>
</html>

Related

Creation of web page to show numbers with intervals

does anyone know how to make a WEB PAGE that shows numbers from, for example, 1 to 100 and that when it reaches 100 it resets to 1 again? and that you can change the time between number and number.
Using html, javascript or anything that was needed. Thx :)
Did you mean something like that?
let countArea = document.getElementById('count-area');
let speedInput = document.getElementById('speed');
let speed = Number(speedInput.value);
function setSpeed() {
speed = Number(speedInput.value)
}
function count() {
if (100 > Number(countArea.textContent)) {
countArea.textContent = Number(countArea.textContent) + 1;
} else {
countArea.textContent = 0;
};
setTimeout(count, speed)
}
count()
speedInput.addEventListener('change', setSpeed)
<!doctype html>
<html>
<head>
<title>Number counter</title>
</head>
<body>
<p id="count-area">0</p>
<input type="range" id="speed" min="50" max="1000">
</body>
</html>
I'm not sure I understand what you mean.
If you mean just a script that writes numbers from 1 to 100 multiple times this can work:
<div id='somediv'></div>
<script>
var times = 4;
for (var n=1;n<times;n++){
for (var i=1;i<101;i++){
somediv.innerHTML+='<br>'+i
}
}
</script>
To set delay between them can add timeout like here:
https://www.w3schools.com/jsref/met_win_settimeout.asp
Depending in what way you want that delay, the rest will be different.
To change how many times it will write 1-100 change the value of 'times', currently it will write it 1 time less then the number(so 3 times), can change that as well.
Edit: Aha!Ok so this can do something similar:
<div id='somediv'></div>
<script>
setInterval(displayCounter, 1000);
var i=0;
function displayCounter() {
document.getElementById("somediv").innerHTML = i;
i=i+1;
if (i==100){i=1};
}
</script>
It will cycle from 0 to 100, then start from 0 again. Currently its 1 second apart(1000 miliseconds). You can make it more or less by changing the 1000 to something else(3000 will be 3 seconds).
Edit 2:
{<br>
"number":"<span id='somediv'></span>"<br>
}
<script>
setInterval(displayCounter, 100);
var i=0;
function displayCounter() {
document.getElementById("somediv").innerHTML = i;
i=i+1;
if (i==100){i=1};
}
</script>
If you want it to start from 1 change:
var i=0;
to
var i=1;
If you want it to be to more or less then 100 change:
if (i==100)...
to 50 for example would be:
if (i==50)...
And can't think of anything more. For style can use css on #somediv.
Edit 3:
{<br>
"number":"<span id='somediv'></span>"<br>
}
<script>
setInterval(displayCounter, 1000);
var i = new Date().getSeconds();
function displayCounter() {
document.getElementById("somediv").innerHTML = i;
i=i+1;
if (i==100){i=1};
}
</script>
This will start the counter(1-100) from the current seconds of the clock. I'm not sure it will be the same for everyone, though, browser may load slower in some places or other factors.
Edit 4:
{<br>
"number":"<span id='somediv'></span>"<br>
}
<script>
setInterval(displayCounter, 1000);
var i = new Date().getSeconds();
if (i>0){somediv.innerHTML = i-1 ;} else if (i==0){somediv.innerHTML = 100}
function displayCounter() {
document.getElementById("somediv").innerHTML = i;
i=i+1;
if (i==100){i=1};
}
</script>

Javascript Slideshow using an array with img URLs

I'm a beginner in JS, and I can't figure out what's wrong with my attempted slideshow. I understand this may seem like a repeat, and I've found a different, working way, to display a slideshow in JS, but I am simply confused about what is wrong with my code. Every single version of slideshow code I've seen sets all of the image urls in HTML and then hides them and only displays one of them using JS, but why wouldn't mine, with image urls simply set in an array, work?
<img id="sideimg" src="images/image1.jpg" alt="penguin" />
<script>
next();
var next=function(){
for(var i=0;i<3;i++){
var slide=document.getElementById("sideimg");
var slides=["images/image1.jpg","images/image2.jpg","images/image3.jpg"]
slide.src=slides[i];
timeOut();
if(i>=3){
i=0;
};
};
var timeOut=function(){
setTimeout(next,1000);
}
};
</script>
Order of functions is not right in your sample
You also need i to be defined outside the function and there is no need for the for loop
The following works for me in chrome
<img id="sideimg" src="images/image1.jpg" alt="penguin" />
<script>
var i = 0
var timeOut=function(){
setTimeout(next,1000);
}
var next=function(){
var slide=document.getElementById("sideimg");
var slides=["images/image1.jpg","images/image2.jpg","images/image3.jpg"]
slide.src=slides[i];
timeOut();
i++;
if(i>=3){
i=0;
};
};
next();
</script>
We could also define i within next as follows using IIFE (immediately invoked function expression). It is also better to declare slides and slide outside the function that is invoked every interval.
<img id="sideimg" src="images/image1.jpg" alt="penguin" />
<script>
var timeOut=function(){
setTimeout(next,1000);
}
var next=function(){
var i = 0;
var slides=["images/image1.jpg","images/image2.jpg","images/image3.jpg"];
var slide=document.getElementById("sideimg");
return function() {
slide.src=slides[i];
timeOut();
i++;
if(i>=3){
i=0;
};
};
}();
next();
</script>
Try moving the array OUTSIDE of the loop:
var next=function(slides){
var slide=document.getElementById("sideimg");
var slides=["images/image1.jpg","images/image2.jpg","images/image3.jpg"]
for(var i=0;i<3;i++){
slide.src=slides[i];
...
};
Here is another possibility (WARNING: I haven't actually tried it):
How do I add a delay in a JavaScript loop?
<img id="sideimg" src="images/image1.jpg" alt="penguin" />
<script type="text/javascript">
var slides=["images/image1.jpg","images/image2.jpg","images/image3.jpg"]
var slide=document.getElementById("sideimg");
var i = 0;
var loop = function () {
sideimg.src=slides[i]; // Display current image
i++;
if (i >= slides.length)
i = 0;
setTimeout(function () { // call setTimeout when the loop is called
loop(); // .. again which will trigger another
}, 1000)
};
};
</script>
};

JavaScript Countdown with argument passing in

You are given an integer called start_num. Write a code that will countdown from start_num to 1, and when the countdown is finished, will print out "Liftoff!".
I am unsure how to do this and keep getting stuck.
This is the code I am provided with at the beginning of the problem:
function liftoff_countdown(start_num) {
// My code goes here!
}
And then they want me to pass in a value such as the 5:
liftoff_countdown(5);
And then this will be my output:
6
5
4
3
2
1
"Liftoff!"
Thanks!
Look at this maybe help you to create your own code
make two file in a same folder (script.js and index.html)
index.html
<!doctype html>
<head>
<title>Countdown</title>
</head>
<body>
<div id="container">
<div id="inputArea">
</div>
<h1 id="time">0</h1>
</div>
<script src="script.js"></script>
</body>
</html>
script.js
var valueRemaining;
var intervalHandle;
function resetPage() {
document.getElementById("inputArea").style.display = "block";
}
function tick() {
var valueDisplay = document.getElementById("time");
valueDisplay.innerHTML = valueRemaining;
if (valueRemaining === 0) {
valueDisplay.innerHTML = "Liftoff!";
clearInterval(intervalHandle);
resetPage();
}
valueRemaining--;
}
function startCountdown() {
var count = document.getElementById("count").value;
if (isNaN(count)) {
alert("Please enter a number!");
return;
}
valueRemaining = count;
intervalHandle = setInterval(tick, 1000);
document.getElementById("inputArea").style.display = "none";
}
// as soon as the page is loaded...
window.onload = function () {
var inputValue = document.createElement("input");
inputValue.setAttribute("id", "count");
inputValue.setAttribute("type", "text");
// create a button
var startButton = document.createElement("input");
startButton.setAttribute("type", "button");
startButton.setAttribute("value", "Start Countdown");
startButton.onclick = function () {
startCountdown();
};
// add to the DOM, to the div called "inputArea"
document.getElementById("inputArea").appendChild(inputValue);
document.getElementById("inputArea").appendChild(startButton);
};
in this example you have many things to understand how javascript works behind scenes.
How about this...
function liftoff_countdown()
{
var span=document.getElementById('num');
var i=document.getElementById('num').innerText;
i=i-1;
span.innerText=i;
if (i==0){
span.innerText='Liftoff!';
clearInterval(count_down)
}
}
var count_down=setInterval(liftoff_countdown,1000);
<span id="num">5</span>
You can achieve this with a simple recursive function and the use of setTimeout to recursively call the function after a time lapse of 1 second.
function lift_off(seconds) {
if(seconds == 0) {
console.log('liftoff');
} else {
console.log(seconds--);
setTimeout(function(){lift_off(seconds);},1000);
}
}
lift_off(10);
Here is a working JSFiddle
Preface
A lot of these answers seem to be focused on doing things with timers and recursion. I do not believe that is your intent. If your only goal is to print those values to the console, you could simply do the following (see the comments for an explanation).
The Answer
function liftoff_countdown(start_num) {
// Loops through all values between 0 and start_num
for(int i = 0; i < start_num; i++) {
// Prints the appropriate value by subtracting from start_num
console.log( start_num - i );
}
// Upon exiting the loop, prints "Liftoff!"
console.log("Liftoff!");
}
Additional Thoughts
You could just as easily loop backwards through the numbers instead of forward like so:
for(int i = start_num; i > 0; i--){
console.log( i );
}
I tend to lean towards iterating forwards just because it's more common, and it's often easy to confuse readers of your code if they gloss over the loop initialization.
Additionally, I am working with the assumption that when you say "print" you mean "console.log()". If this is untrue, you could of course use any other function in its place (e.g. alert( "Liftoff!" );).

can't add a remove/edit feature to my program

I making a web app that can be used to store contacts. I am having trouble with a feature in which I use a button to either remove or edit a contact. I have tried something like this.
<doctype html>
<html>
<head></head>
<body>
<table>
<thead></thead>
<tbody id='add-to'></tbody>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
// holds all the buttons Id's so I can keep track of which button I pressed
var id_hold = []
$(document).ready(function() {
for (var i = 0; i < id_hold; i++) {
// should add print something to the console if any button is clicked
$('#' + id_hold[i]).click(function() {
console.log('clicked button ' + i);
});
}
addIds();
});
function addIds() {
// allows me to add things to the table I made above
var add_to_dom = $('#add-to');
for (var i = 0; i < 10; i++) {
add_to_dom.append('<button id =' + i + '></button>');
}
}
}
</script>
</body>
</html>
My question is how do make Add a feature like this that works? I don't know how to.
thanks
As #user3743222 said you should do a bit of research before asking a question and need to be specific on what you want to achieve. Your posted code doesn't even run because of extra }. Anyway assuming you want to get this working I made some minimal changes to get that working.
<doctype html>
<html>
<head></head>
<body>
<table>
<thead></thead>
<div id='add-to'></div>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
// holds all the buttons Id's so I can keep track of which button I pressed
var id_hold = []
$(document).ready(function () {
addIds();
for (var i = 0; i < 10; i++) {
// should add print something to the console if any button is clicked
(function (j) {
$('#' + id_hold[j]).click(function () {
console.log('clicked button ' + j);
});
})(i)
}
});
function addIds() {
// allows me to add things to the table I made above
var add_to_dom = $('#add-to');
for (var i = 0; i < 10; i++) {
add_to_dom.append('<button id =' + i + '>' + i + ' </button>');
id_hold[i] = i;
}
}
</script>
</body>
</html>
Please note that you need to wrap click binding function inside for loop in a self invoking scope to avoid the case where you get the same i value for all the click handlers.

How to display one image in loop?

I'm trying to display one image in loop. Knowing the path and image-name are okay is this example, how to display one image in loop, and when the image haven't been found, the browser displays the last right image-name until the image-name is found?
#{int j=1;}
<img src="" />
<script>
(function () {
for (var i = 1; true; i++) {
#{ string file = "/MonitoringN/../bitmaps/" + j + ".png"; bool a = System.IO.File.Exists(file) == true; }
var str = "/MonitoringN/../bitmaps/" + i + ".png";
var b = "#a";
if (b)
{
setInterval(function () { $('img').prop('src', str); }, 1000);
} else {
i--;
#{j--;}
}
#{j++;}
}
});
</script>
Because when I execute this code, I get a blank image, and then I can't see the page is loading.
Thanks a lot!
I think I know what you are trying to do ...
If I understand the question correctly, you have a list of images and you want to try to open them until one of them is found. If an image is NOT found, you want to skip to the next one.
First -- I'd simply for your question by separating the Razor stuff and the Javascript off into very separate pieces. In fact, I'm going to skip Razor entirely.
<html>
<head>
<title>A test</title>
</head>
<body>
<img src="http://x.invalid" id="myImage">
<script>
var imgs = [
"http://x1.invalid/none",
"https://www.google.com/images/srpr/logo11w.png",
"http://thedailywtf.com/Resources/Images/Primary/logo.gif"
];
var imageIndex = 0;
function tryNextImage() {
var img = document.getElementById("myImage");
img.onerror = function() {
imageIndex++;
tryNextImage();
}
img.src = imgs[imageIndex];
}
// start the ball rolling
tryNextImage();
</script>
</body>
</html>

Categories

Resources