I have the following simple code from an exercise in Modern Javascript used to calculate a sphere's volume, it contains a part which checks to make sure that a value has been entered for radius.
I put in a negative number to test the function, and it works, but I was interested in what would be displayed in the console, so I checked. I end up seeing an error flash in the log and then disappear - too quick to read.
Is this just what occurs when an if statement evaluates to false? Why is this error displaying and then being cleared almost immediately? I'm aware I could use another way to debug this (a.k.a. using console.log or logging the problem by some other means), I'm just interested as to why this error disappears.
HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Volume of a Sphere Calculator</title>
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<!-- sphere.html -->
<form action="" method="post" id="theForm">
<fieldset>
<p>Use this form to calculate the volume of a sphere.</p>
<div>
<label for="radius">Radius</label>
<input type="text" name="radius" id="radius" required></div>
<div>
<label for="volume">Volume</label>
<input type="text" name="volume" id="volume"></div>
<div>
<input type="submit" value="Calculate" id="submit"></div>
</fieldset>
</form>
<script src="js/sphere.js"></script>
</body>
</html>
JS:
function calculate() {
'use strict';
var volume;
var radius = document.getElementById('radius');
if (radius && (radius.value > 0)){
volume = (4/3) * Math.PI * Math.pow(radius.value, 3);
}
volume = volume.toFixed(4);
document.getElementById('volume').value = volume;
return false;
}
function init() {
'use strict';
var theForm = document.getElementById('theForm');
theForm.onsubmit = calculate;
}
window.onload = init;
Because this is the top Google match for my problem of console.log output appearing and quickly disappearing, this happened to me because I either had an empty set of label tags out of place or a form with no action. Deleting those tags caused JavaScript and console.log() to work like it was supposed to.
Adding another solution as a Google search for "javascript log disappearing" brought me here.
Page refreshing/navigation was the problem.
Selecting "Preserve log" in the console settings as per mateuszb's comment solved the issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With