I'm pretty new to any form of coding so please forgive my ignorance, but when I use a var for my interval for a second function, it will not work correctly, I've tried my best to not have to ask, but my search is fruitless. Please help!
function click_01() {
var elem = document.getElementById('trash_02');
setInterval(frame, 10);
var width = 0
function frame(){
if (width >= 100){
clearInterval("frame");
width = 0;
} else {
width = width + 1;
elem.style.width = width + '%';
}
}
}
click_01();
Pass a function instead of a string
Just remove quote and parenthesis from function frame. If you pass with quotes it will become string and your code wont work properly.
So here goes your answer
function click_01() {
var intr=setInterval(frame, 100);//here you passed "frame()" which is string
function frame(){
let elem=document.getElementById('cls');
elem.style.width=(parseInt(elem.style.width)+1)+'px';
elem.innerHTML=parseInt(elem.style.width)+"%";
if(parseInt(elem.style.width)>=100){
elem.style.width=0;
clearInterval(intr);
elem.innerHTML='Loading complete';
}
}
}
<div id="cls" style="background-color:red;width:0px">
</div>
<div><button onclick="click_01()"> click to launch loader</botton> </div>
Related
I made a progressbar using JavaScript and I later added a intersection observer API to let it automatically run.
I now want to have multiple of these progressbars in my website and my teachers at school told me I could better just copy the code multiple times and change the ID (which I disagree with but I do not know how to make multiple prgressbars run by 1 script).
I copied my html 2 times with a other ID-name and changed the ID-name in my JavaScript file and I even put it in a different <script> section but only one progressbar works (the 1st one) the second one does not work.
Why doesn't it work? I am currently learning JavaScript so please tell me what I am doing wrong or if there is room for improvement besides my whole script not working for more then once...
my html =
div class="progressbars">
<div class="progress_status">
<div id="progressbar">
<p>5%</p>
</div>
</div>
</div>
<div class="progressbars">
<div class="progress_status">
<div id="progressbar2">
<p>5%</p>
</div>
</div>
the CSS for it ( don't think you will need it but just to be sure)
#progressbar /*,#progressbar2 ,#progressbar3 ,#progressbar4*/{
width: 5%;
height: 35px;
background-color: #D8135A;
text-align: center;
line-height: 32px;
color: white;
}
the JavaScript (the first one works, the second one does nothing to my second progressbar)
<script>
const progress = document.getElementById('progressbar')
const options = {
threshold : 1
};
let observer = new IntersectionObserver(update, options);
observer.observe(progress);
function update() {
var element = document.getElementById("progressbar");
var width = 5;
var identity = setInterval(scene, 30);
function scene() {
if (width >= 40) {
clearInterval(identity);
} else {
width++;
element.style.width = width + '%';
element.innerHTML = width * 1 + '%';
}
}
}
</script>
this is the script that I'd like to function on (on my div #progressbar2)
<script>
// start js deel 2
const progress = document.getElementById('progressbar2')
//try this for multiple progressbars
const options = {
threshold : 1
};
let observer = new IntersectionObserver(update, options);
observer.observe(progress);
function update() {
var element = document.getElementById("progressbar2");
var width = 5;
var identity = setInterval(scene, 30);
function scene() {
if (width >= 40) {
clearInterval(identity);
} else {
width++;
element.style.width = width + '%';
element.innerHTML = width * 1 + '%';
}
}
}
</script>
once again I do not know why this doesn't work, I am new to JavaScript.
I tried a lot of different things like getdocumentbyclassname but I couldn't get it to work..
please tell my if this is possible in one script or how I could make it work with more scripts.
https://snapr.pw/i/2cedbe3345.png
<script>
//when user clicks start button this function ensures all fields //are set to 0 and it
//sets the timer for the game (90seconds) and the second timer to //call showWord() every four seconds to display a new word
function startGame() {
numBadWordsField.innerHTML = '';
numGoodWordsField.innerHTML = '';
numWordsRight = 0;
numWordsWrong = 0;
correctWords = [];
showWord();
gameTimer = setInterval(gameTime, 1000);
timedWordDisplay = setInterval(showWord, 4000);
}
//this function is set to repeat every four seconds unless the user //types the word
//correctly in which case code in the checkWord() function resets setInterval then and a new word appears
function showWord() {
let randomNum = Math.floor(Math.random()*wordsLevelOne.length);
currentWord = wordsLevelOne[randomNum];
//i put all correctly typed words in an array to avoid them being repeated
//if the random word has been typed correctly and is in the array then i tell the
//program to repeat the function until a new word is found.
if (correctWords.includes(currentWord)) {
showWord();
} else {
wordDisplayBox.innerHTML = currentWord;
setInterval(changeBar, 500);
answerBox.focus();
}
}
//this function is called oninput as user types in the word. it works perfectly (i think it does anyways)
//however i cannot figure out how to give instructions in the event the user does not type the
//word correctly before the four seconds are up and the setInterval repeats. I would like to
//in that case increment the words wrong score and reset the fields to be ready for the next
//word to be displayed
function checkWord() {
let currentWordLen = answerBox.value.length;
if (wordDisplayBox.innerHTML === answerBox.value) {
clearInterval(timedWordDisplay);
numWordsRight++;
correctWords.push(currentWord);
numGoodWordsField.innerHTML = numWordsRight;
answerBox.value = '';
answerBox.focus();
wordDisplayBox.innerHTML = '';
showWord();
timedWordDisplay = setInterval(showWord, 4000);
} else if (answerBox.value === currentWord.substring(0, currentWordLen)) {
answerBox.style.borderColor = 'green';
} else {
answerBox.style.borderColor = 'red';
}
}
//different topic than above but i also researched how to make my progress bar fill slowly over the course
//of the four seconds. i have written the following function identically to that on
//w3schools and other code yet it does not work.
//Any ideas?
function changeBar() {
let proBar = document.querySelector('#progressBar');
var width = 1;
var id = setInterval(frame, 10);
function frame() {
if (width >= 100) {
clearInterval(id);
} else {
width++;
proBar.style.width = width + '%';
}
}
}
</script>
This project Im working on is a beginner level speed typing game that displays a different word for the user to type in less than four seconds.I have a setInterval that displays a different word every four seconds unless the user types the word correctly at which point the timer starts over then. What I am stumped at is how can I make it so that if the correct answer is not typed in before the interval resets (at the end of four seconds) the program knows to increment the 'wrong answer' score and to reset the input boxes for the next word just like when it is typed correctly. i have attached the parts of my code i think may be relevant. If anyone has any suggestions let me know. I am eager to learn. **I am not familiar yet with JQuery. Please describe any suggestions using vanilla JS
This feature should be implemented in the showWord function.
showWord is executed after 4 seconds have passed, which is when the time is up. Executing this function means the user has failed to type the word in time.
I would do something like this :
function showWord() {
// At this point, the user has lost. We perform the according operations
numWordsWrong++;
answerBox.value = '';
// etc.
// What follows is the rest of the function you've already implemented
let randomNum = Math.floor(Math.random()*wordsLevelOne.length);
// etc.
}
To answer your question about the progress bar, you are setting an interval to run changeBar every 500 milliseconds, which would cause the progress bar to reset every half second. If you want a delay before starting the progress bar use setTimeout.
In addition, you are running your progress bar to move 1% every 10 milliseconds which would result in the bar completing in 1 second. If you want the bar to complete in 4 seconds, set the id interval to run every 40 milliseconds.
Without seeing your css and html, I have to assume you're using the correct id names in your code but if nothing is happening at all, that could also be the cause.
I have looked at the W3Shools code you reference and I tried to replicate what you were trying to do and got this to work:
<html>
<head>
<style>
#myProgress {
width: 100%;
background-color: #ddd;
}
#myBar {
width: 1%;
height: 30px;
background-color: #4CAF50;
}
</style>
</head>
<body>
<div id="myProgress">
<div id="myBar"></div>
</div>
</body>
<script>
function changeBar() {
let proBar = document.querySelector('#myBar');
var width = 1;
var id = setInterval(frame, 40);
function frame() {
if (width >= 100) {
clearInterval(id);
} else {
width++;
proBar.style.width = width + '%';
}
}
}
setTimeout(changeBar, 100);
</script>
</html>
One solution can be to create a new function (ex : showWordBecauseTimeout) and call it in your setInterval instead of showWord. And call that function in showWord fct instead of in startGame fct.
So the new code would be something like :
function showWord() {
clearInterval(timedWordDisplay);
timedWordDisplay = setInterval(showWordBecauseTimeout, 4000);
// you also need to move the cleaning of the input in the showWord fct
// ...
}
function showWordBecauseTimeout() {
numWordsWrong++;
showWord()
}
Hope that it helps you :).
Pretty new to jquery so bear with me. I’ve got two functions, one that is intended to be used on desktop and one that is used at the tablet breakpoint. They both check for the length of a particular DOM element and pass in the width as a parameter. I’ve got another function that currently calls only one of the functions but is there a way to somehow pass in one or the other based on if they are at the tablet or mobile breakpoint? You can see in the setWidth function it's using the calculateDesktop function. I could create two different functions to do this but that would seem redundant. Kind of a newb to jquery please include code samples as necessary.
function calculateDesktop(width) {
var desktop= $('.header-item').length;
return width * ($('.header-section').length - desktop);
}
function calculateTablet(width) {
var tablet = $('.header-item.tablet-none').length;
return width * ($('.header-section').length - tablet);
}
function setWidth() {
$('.expand .main-section').each(function() {
var headerClass = $(this).closest('.header-item')).filter(function(it){
return it.match(/^width-/); });
var width = headerClass ? headerClass[0].split('-')[1] : 75;
$(this).css("width", calculateDesktop(width) + "%");
});
}
SUDO CODE (doesn't work, but something I'm looking to achieve)
if ($(window).width() <= 768) {
setWidth(calculateTablet)
} else {
//desktop goes here
setWidth(calculateDesktop)
}
You can pass the function reference as you have done then invoke that function reference to get the width
function setWidth(fn) {
$('.expand .main-section').each(function () {
var headerClass = $(this).closest('.header-item').filter(function (it) {
return it.match(/^width-/);
});
var width = headerClass ? headerClass[0].split('-')[1] : 75;
$(this).css("width", fn(width) + "%");
});
}
if ($(window).width() <= 768) {
setWidth(calculateTablet)
} else {
//desktop goes here
setWidth(calculateDesktop)
}
I am writing code to increment the most basic progress bar ever...... it just isn't working.
These are the variable used:
map.progress_bar = // the progress div that grows inside a container div that is the width of the screen (100%);
progress = 0;
state.window_width = // the width of the window or otherwise $(window).width();
setTimeout(function incProgress(){
if ( map.progress_bar.width() < state.window_width ) {
progress += 10;
map.progress_bar.css({
width: String(progress + '%')
});
console.log('progress: ', map.progress_bar.width());
console.log('window: ', state.window_width);
setTimeout(incProgress(), 300);
}
}, 300);
Please do not ask me to do setInterval. Please explain to me why on earth this does not work, I feel very unhappy.
setTimeout(incProgress(), 300);
You are calling the function and passing its return value (undefined) to setTimeout.
You need to pass a function to setTimeout.
Remove the ().
I am new to Javascript and would like to know if the following function should create a transition scrolling down to a set scroll position and if not, what am I misunderstanding about the time out or scroll to methods..
function scrollDownToMovie() {
for (var scrollbit = 10; scrollbit < 900; scrollbit += 10) {
window.setTimeout(function({window.scrollTo(0,scrollbit);}
,scrollbit*100);
}
}
Thank you
Try this. It's not perfect but it should do what you want.
var scrollbit=10;
function scrollDownToMovie() {
var time=setTimeout(function(){scrollDownToMovie();},50); //fifty can be whatever increment you want.
window.scrollTo(0,scrollbit);scrollbit+=10;
if(scrollbit>890){clearTimeout(time);}
}