Displaying a javascript var in html body
Esme,
Your document.write(o) snippet is executed right after page load. And that time 'o' variable is not defined. After click on the button, you make your div visible but don't update the result. Here is a possible suggestion to your problem:
<html>
<head>
<title>HTML Calculator</title>
<script type="text/javascript">
function calc() {
var i = document.getElementById("input").value;
var p = document.getElementById("percent").value;
return (i/100) * p;
}
function GetTotal() {
document.getElementById('answer').style.display = "block";
document.getElementById('answer_value').innerText = calc();
}
</script>
</head>
<body>
<form>
Input: <input type="text" id="input"/><br />
Percent: <input type="text" id="percent" value="10"/>%<br />
<input type="button" style="color:#000;" name="Get Total" value="Get Total" onclick="GetTotal()" />
<div id="answer" style="display:none;"> Total: <span id="answer_value"></span> </div>
</form>
</body>
</html>
How to display the value of a javascript variable in html?
You would just set the .textContent
of the element that it will be shown in to the variable. No hiding/showing of the element is needed because the element's .textContent
will be empty at first (so it will initially not show anything anyway).
<html><head> <title>Using form data in the page</title></head><body> <div> <input type="text" id="input"> <button onclick="go()">Click</button> </div>
<div id="show"></div>
<script> function go() { let value = document.getElementById('input').value; document.getElementById('show').textContent = value; } </script></body></html>
How to display JavaScript variables in a HTML page without document.write
Element.innerHTML
is pretty much the way to go. Here are a few ways to use it:
HTML
<div class="results"></div>
JavaScript
// 'Modern' browsers (IE8+, use CSS-style selectors)
document.querySelector('.results').innerHTML = 'Hello World!';
// Using the jQuery library
$('.results').html('Hello World!');
If you just want to update a portion of a <div>
I usually just add an empty element with a class like value
or one I want to replace the contents of to the main <div>
. e.g.
<div class="content">Hello <span class='value'></span></div>
Then I'd use some code like this:
// 'Modern' browsers (IE8+, use CSS-style selectors)
document.querySelector('.content .value').innerHTML = 'World!';
// Using the jQuery library
$(".content .value").html("World!");
Then the HTML/DOM would now contain:
<div class="content">Hello <span class='value'>World!</span></div>
Full example. Click run snippet to try it out.
// Plain Javascript Examplevar $jsName = document.querySelector('.name');var $jsValue = document.querySelector('.jsValue');
$jsName.addEventListener('input', function(event){ $jsValue.innerHTML = $jsName.value;}, false);
// JQuery examplevar $jqName = $('.name');var $jqValue = $('.jqValue');
$jqName.on('input', function(event){ $jqValue.html($jqName.val());});
html { font-family: sans-serif; font-size: 16px;}
h1 { margin: 1em 0 0.25em 0;}
input[type=text] { padding: 0.5em;}
.jsValue, .jqValue { color: red;}
<!DOCTYPE html><html><head><script src="https://code.jquery.com/jquery-1.11.3.js"></script> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>Setting HTML content example</title></head><body> <!-- This <input> field is where I'm getting the name from --> <label>Enter your name: <input class="name" type="text" value="World"/></label> <!-- Plain Javascript Example --> <h1>Plain Javascript Example</h1>Hello <span class="jsValue">World</span> <!-- jQuery Example --> <h1>jQuery Example</h1>Hello <span class="jqValue">World</span></body></html>
How do I use this JavaScript variable in HTML?
You don't "use" JavaScript variables in HTML. HTML is not a programming language, it's a markup language, it just "describes" what the page should look like.
If you want to display a variable on the screen, this is done with JavaScript.
First, you need somewhere for it to write to:
<body>
<p id="output"></p>
</body>
Then you need to update your JavaScript code to write to that <p>
tag. Make sure you do so after the page is ready.
<script>
window.onload = function(){
var name = prompt("What's your name?");
var lengthOfName = name.length
document.getElementById('output').innerHTML = lengthOfName;
};
</script>
window.onload = function() { var name = prompt("What's your name?"); var lengthOfName = name.length
document.getElementById('output').innerHTML = lengthOfName;};
<p id="output"></p>
Display javaScript variable value on HTML page?
Call the score
function whenever, the Score
variable gets updated. In your html
there is not element with id
Points
, however class
is present. Instead of document.getElementById("Points").innerHTML = Score;
use document.querySelector(".Points").textContent = Score;
. No need to use innerHTML
, as Score is a number and not an html
content.
var notes = [];var gameStarted = false;var Score = 0;
// ==== CLASS FOR ARROWS ==== //
// 1. Direction of arrows// 2. jQuery img that links to direction bottom// 3. Destroy when it arrow gets to the // 4. Explode when arrow gets to the bottom
// Class Arrowfunction Arrow(direction) { // CSS spacings for the arrows // var xPos = null;
switch (direction) { case "left": xPos = "350px"; break; case "up": xPos = "420px"; break; case "down": xPos = "490px"; break; case "right": xPos = "560px"; break; }
this.direction = direction; this.image = $("<img src='./arrows/" + direction + ".gif'/>"); this.image.css({ position: "absolute", top: "0px", left: xPos }); $('.stage').append(this.image);
} // ends CLASS Arrow
// To enable animating the arrowsArrow.prototype.step = function() { // Controls the speed of the arrows this.image.css("top", "+=4px");};
// Deletes arrows when they get to bottom of pageArrow.prototype.destroy = function() { // removes the image of the DOM this.image.remove(); // Removes the note/arrow from memory/array notes.splice(0, 1);};
// Explodes arrow when hitArrow.prototype.explode = function() { this.image.remove();};
// For random arrowsvar randNum = 0;
// Frame increasingvar frame = 0;
// Determines the speed of notesvar arrowSpawnRate = 40;
// Random generator for arrowsfunction randomGen() { // Randomizes between 1 and 4 randNum = Math.floor(Math.random() * 4) + 1; if (randNum === 1) { notes.push(new Arrow("left")); } if (randNum === 2) { notes.push(new Arrow("right")); } if (randNum === 3) { notes.push(new Arrow("up")); } if (randNum === 4) { notes.push(new Arrow("down")); }} // ends randomGen()
// Render function //function render() { if (frame++ % arrowSpawnRate === 0) { randomGen(); }
// Animate arrows showering down // for (var i = notes.length - 1; i >= 0; i--) { notes[i].step(); // Check for cleanup if (notes[i].image.position().top > 615) { notes[i].destroy(); } }} // ends render()
// jQuery to animate arrows //$(document).ready(function() { // shim layer with setTimeout fallback window.requestAnimFrame = (function() { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) { window.setTimeout(callback, 40 / 75); }; })();
/* place the rAF *before* the render() to assure as close to 60fps with the setTimeout fallback. */
// Infinte loop for game play (function animloop() { if (gameStarted) { requestAnimFrame(animloop); render(); } else { window.setTimeout(animloop, 1000); // check the state per second } })(); // ends (function animloop() )}); // ends $(doc).ready
// Listening for when the key is pressed$(document).keydown(function(event) { for (var i = 0; i < notes.length; i++) { if (event.keyCode == 37 && notes[i].direction == "left") { if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) { console.log("LEFT! " + notes[i].explode()); Score++; score(); } } if (event.keyCode == 38 && notes[i].direction == "up") { if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) { console.log("UP! " + notes[i].explode()); Score++; score(); } } if (event.keyCode == 40 && notes[i].direction == "down") { if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) { console.log("DOWN! " + notes[i].explode()); Score++; score(); } } if (event.keyCode == 39 && notes[i].direction == "right") { if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) { console.log("RIGHT! " + notes[i].explode()); Score++; score(); } } } // ends loop}); // ends $(doc).keyup
function score() { document.querySelector(".Points").textContent = Score;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div id="BackgroundScene"> <div id="DanceScoreboard"> <div id="GameStopped"><button id="StartBtn" class="btnStyle" onclick="gameStarted=true;">Begin Game</button> <br><br><br> <div class="Status">Click Begin Game to start</div> </div> <div id="GameRunning"><button id="StopBtn" class="btnStyle" onclick="gameStarted=false;">Stop Game</button> <div id="Status" class="Status"></div> </div> <div id="dancePoints" class="Points">Points Earned: <div class="OutputText" id="CorrectCount">0</div> </div> </div> <div class="stage"></div> <!-- ENDS .STAGE --> <div id="controls"> <img id="left" src="./arrows/staticLeft.png"> <img id="up" src="./arrows/staticUp.png"> <img id="down" src="./arrows/staticDown.png"> <img id="right" src="./arrows/staticRight.png"> </div> <!-- ENDS #CONTROLS -->
Add JavaScript variable to HTML
You could create a <span>
element and then use jQuery selector to set the html of that element.
Here is an example:
<div class = "box"><span class="span"></span>user</div>
<script type="text\javascript">
$(".box .span").html("Hello ");
</script>
Related Topics
How to Call a Rest Web Service API from JavaScript
Cross-Origin Data in Html5 Canvas
How to Write in File (User Directory) Using JavaScript
How to Open a Link in New Tab (And Not New Window)
Stop an Input Field in a Form from Being Submitted
How to Show Popup Message Like in Stack Overflow
Restart Animation in Css3: Any Better Way Than Removing the Element
How to Disable Scroll Without Hiding It
How to Get the Cursor Position in a Textarea
Convert Svg to Png With Applied Images as Background to Svg Elements
Using Execcommand (JavaScript) to Copy Hidden Text to Clipboard
How to Get the Position of Text Within an Element
Prevent Typing Non-Numeric in Input Type Number
Find All CSS Rules That Apply to an Element
How to Set Background Color of HTML Element Using CSS Properties in JavaScript