Function is not defined even though it is - javascript

I am coding a taximeter which is calculating the drive-expenses through the elapsed time. By clicking a button the standing below function "startDrive" will normally executed, but when I am clicking on my button the browser or console respectively is showing an error which is including the message "Uncaught ReferenceError: startDrive is not defined
at HTMLButtonElement.onclick (time.html:15:62)". I checked whether I mentioned the wrong Function in the "onclick" part in HTML but this is not the case. What I am doing wrong?
//global variables
let y = 3.9;
let reversal = 20;
//Main-function in which the sub-functions are be executed
function startDrive() {
document.getElementById('output1').innerHTML = y.toFixed(2) + "€";
interval();
}
//Calculating drive-expenses
function calculate() {
if(y < reversal) {
y += 0.14375;
}
else if(y > reversal) {
y += 0.103125;
}
document.getElementById('output1').innerHTML = y.toFixed(2) + "€";
}
//Fixed time in which "calculate()" will be executed
function interval() {
timerId = setInterval(calculate, 5000);
}
//Stopping interval
function stop() {
clearInterval(timerId);
}
<button onclick = "startDrive()">start!</button>
<output id = "output1"></output>

here
<button onclick = "startDrive">start!</button>
use startDrive() instead of startDrive
you can watch a sample at here.

It says startDrive is not defined, so it seems your function definitions are never executed.
If you put your code in a plain script tag inside head it works just fine:
https://codesandbox.io/s/great-joana-ubttg5?file=/index.html

Related

JavaScript if statement not working except inside function. Anyone know how to fix it?

I have this function that alerts the user when their amount of "moonstone" is 10. However, for various reasons, I would like the if statement to be outside the function. When I do this though, the alert doesn't work. Could someone please explain and post a fix for it?
<!DOCTYPE html>
<html>
<img id="game-board" onclick="totalCount()" class="game-board" src="https://pics.clipartpng.com/thumbs/Mars_PNG_Clip_Art-3002.png"></img>
<h2 id="counts">Moonstone:</h2>
<script>
let stone = 0;
function totalCount() {
let newCounts = stone++;
document.getElementById('counts').innerHTML= "Moonstone:"+ newCounts;
}
if (newCounts == 10){
alert('10');
}
</script>
</html>
What does work, but that I don't want to use, is
<DOCTYPE html>
<html>
<img id="game-board" onclick="totalCount()" class="game-board" src="https://pics.clipartpng.com/thumbs/Mars_PNG_Clip_Art-3002.png"></img>
<h2 id="counts">Moonstone:</h2>
<script>
let stone = 0;
function totalCount() {
let newCounts = stone++;
document.getElementById('counts').innerHTML= "Moonstone:"+ newCounts;
if (newCounts == 10){
alert('10');
}
}
</script>
In your code you calling the totalcount() function on onclick event so whatever inside the totalcount() function will executed and code outside the totalcount() function will not execute
I'm not entirely clear why you wouldn't want the if test within the function. But, there is something that you could do:
const counter = {
value: 0,
addOne: function() {
this.value++;
if (this.value > 10) {
alert("Too many");
this.value--;
} else {
document.getElementById("counts").innerHTML = "Moonstones: " + this.value;
}
}
}
function updateCounter() {
counter.addOne();
}
<button onclick="updateCounter();">Add</button>
<div id="counts"></div>
This creates the counter as an object and includes an if test on a addOne function directly attached to that object. Whenever the updateCounter() function is called, the addOne function updates the counter value and checks to see if it has passed 10. If it has, the user gets and alert, otherwise the "counts" element gets updated.
But, as others have said, there is no real reason why an if test shouldn't be part of a function - perhaps you could explain your reasons for that requirement?

Using a return/stop function on click

Currently closee to finishing a slideshow using html and JavaScript. My last problem is creating stop button which needs to use a return function (I assume) Or some sort of exit function. It is an image slideshow that runs automatically, can be paused, skip image, go back an image and so on. I'd like the stop button to kill the autoRun function and set the image back to the first default image. I've set up a function which I'm guessing is totally wrong as it is not working.
The HTML
<td class="controls">
<button onClick="autoRun()">Start</button>
<button onClick="changeImage(-1); return false;">Previous Image</button>
<button onClick="pause();">pause</button>
<button onClick="changeImage(1); return false;">Next Image</button>
<button onClick="Exit();">Exit</button>
</td>
</tr>
All buttons are working besides the last one
JavaScript
var images = ["HGal0.jpg", "HGal1.jpg", "HGal2.jpg", "HGal3.jpg", "HGal4.jpg", "HGal5.jpg", "HGal6.jpg", "HGal7.jpg", "HGal8.jpg", "HGal9.jpg", "HGal10.jpg", "HGal11.jpg", "HGal12.jpg", "HGal13.jpg", "HGal14.jpg", "HGal15.jpg"];
var interval = setInterval("changeImage(1)", 2000);
var imageNumber = 0;
var imageLength = images.length - 1;
function changeImage(x) {
imageNumber += x;
// if array has reached end, starts over
if (imageNumber > imageLength) {
imageNumber = 0;
}
if (imageNumber < 0) {
imageNumber = imageLength;
}
document.getElementById("slideshow").src = images[imageNumber];
return false;
}
function autoRun() {
interval = setInterval("changeImage(1)", 2000);
}
function pause(){
clearInterval(interval);
interval = null;
}
function Exit(){
return;
}
I'm not fully understanding the return statement in the Exit function, as most examples I've looked at run the function when an 'if' statement is met, whereas I'd like mine to execute when the Stop button is clicked. Thanks
A return statement simply exits the function in which it appears, it doesn't cause other things to stop. So this:
function Exit(){
return;
}
...has the same effect as this:
function Exit() { }
That is, the function doesn't do anything at all.
I'd like the stop button to kill the autoRun function and set the image back to the first default image.
OK, so have your Exit() function call your other functions:
function Exit() {
pause(); // this will stop the slideshow
imageNumber = 0; // reset to the first image
changeImage(0); // change to that image
}

window.onload called after returning from a event handler method

This code is for learning purpose in javascript.I have declared a global variable called num and initialized it to 30. Now this is increased on click of a plus button and is decreased on click of minus button.But when I click plus button twice.It alerts 31 twice instead of showing 31 first then 32.
When I debugged it on chrome I found out that the breakpoint hits 'var num=30' again once it executes the increase method which is called onclick of plus button.
So why after the return from method the window is reloading?Can someone please explain?Thanks in advance.My code is as below :
window.onload =initialize;
var num=30;
function initialize()
{
if(!document.getElementById) return;
var increaseButton = document.getElementById('plus');
increaseButton.onclick = increase;
var decreaseButton = document.getElementById('minus');
decreaseButton.onclick = decrease;
}
function increase()
{
num++;
alert(num);
}
function decrease()
{
num++;
alert(num);
}
Seems to work for me if the HTML is:
<button type="button" id="plus">+</button>
<button type="button" id="minus">-</button>
You would also want your decrease function to be:
function decrease()
{
num--;
alert(num);
}
JSFiddle: https://jsfiddle.net/OzymandiasII/L9h1xbsr/

JQuery and Javascript fade not working

Jquery and Javascript do strange things. If you look to the code there is a "while" loop. It does 3 loops but only fades the last one (#c2).
Here is my code:
<div style="display:none" id="c0">Element 0</div>
<div style="display:none" id="c1">Element 1</div>
<div style="display:none" id="c2">Element 2</div>
<script>
var count = 0;
var exit = false;
var time = 300;
while(exit == false){
if(document.getElementById("c" + count)){
cual = "#c" + count;
$(document).ready(function(){
$(cual).fadeIn(time);
});
}
else
exit = true;
count++;
time += 100;
}
</script>
The reason you see this is because the cual variable will hold the value #c3 by the time the callbacks execute. Because cual is defined within a global scope, and not the callback scope, it is not bounded to the callback scoe.
There is a workaround for this, by adding an intermediary function, something like this:
function scheduleFade(count) {
var cual = "#c" + count;
$(document).ready(function(){
$(cual).fadeIn(time);
});
}
while(exit == false) {
if(document.getElementById("c" + count)) {
scheduleFade(count);
} else {
exit = true;
}
count++;
time += 100;
}
The script is loaded after the DOM is loaded on the page, so you don't need to use $(document).ready(). I have tested the following script:
var count = 0;
var exit = false;
var time = 300;
while(exit == false){
if(document.getElementById("c" + count)){
cual = "#c" + count;
$(cual).fadeIn(time);
}
else
exit = true;
count++;
time += 100;
}
and it works.
(Update based on comments)
The variable cual is overwritten on each loop, but the code inside the ondocumentready event listener is only executed after the DOM is fully loaded. At this point the variable cual is only set to the name of the third element.
You can create an own visibility scope for that variable to make it available inside the event listener callback:
var count = 0;
var exit = false;
var time = 300;
while(exit == false){
if(document.getElementById("c" + count)){
cual = "#c" + count;
$(document).ready((function() {
var elementToFadeIn = cual;
return function() {
$(elementToFadeIn).fadeIn(time);
}
})());
}
else
exit = true;
count++;
time += 100;
}
Here the variable elementToFadeIn is set inside an immediately-invoked-function, which also returns the event listener callback. That way, the locally defined elementToFadeIn will stay with name passed in on the current loop iteration.
–––––
On the other you are using jQuery, why do need the loop in the first place?
Just include this code at the end of the page (i.e. before the closing BODY tag) and you don't need the ondocumentready event, as all relevant parts of the DOM are loaded right before the closing BODY tag.
var time = 1000;
jQuery( '[id^="c"]' ).fadeIn( time );

Countdown function isn't actually counting down

I have a function in my .js file that is supposed to display a countdown from 10 - 0. Once it hits 0, it should open up a second page. I don't have the part where it opens the page written yet, but that isn't my current problem. My problem is that the countdown will display the number 1, and do nothing else. I'm not really sure why.
Here's the countdown function
function startCountdown() {
for (var i = 10; i >= 0; i--) {
document.getElementById("countdown").value = i;
}
}
Here is the function that calls it
function startAdPage() {
setInterval(changeAd(), 2000);
setInterval(startCountdown(), 1000);
}
Finally, here is the HTML code that it is sending to. Everything is started by the body tag calling the onload method. I know that part works, since I have it doing something else that is working properly.
<div id="counter">
<p>The Central Valley Realtors home page will display in
<input type="text" value="" class="countdown"/>
seconds</p>
</div>
The first argument to setInterval is a function. You're not passing the function, you're calling the function and passing whatever it returns, since you have () after the function name.
Also, you're not waiting between updates to the countdown field. Javascript is single-threaded, the page doesn't update until the script returns. You need this:
function startAdPage(){
var curCounter = 10;
function startCountdown() {
document.getElementById("countdown").value = curCounter;
curCounter--;
if (curCounter == 0) {
clearInterval(countdownInterval);
}
}
setInterval(changeAd, 2000);
var countdownInterval = setInterval(startCountdown, 1000);
}
Your loop inside of startCountdown is running all the way to the end of the loop, so the value ends up 0. Also, you are supposed to pass either an Anonymous function or an unexecuted function to setInterval and clearInterval without parameters. When you add () at the end of a function name you are executing the function. Change the the <input type='text' class='countdown' /> to <input type='text' id='countdown' />, then try the following:
function countdown(begin, end, interval, outputElement){
var repeat = setInterval(function(){
if(outputElement.innerHTML){
outputElement.innerHTML = begin--;
}
else{
outputElement.value = begin--;
}
if(begin === end)clearInterval(repeat);
}, interval);
}
countdown(10, 0, 1000, document.getElementById('countdown'));

Categories