This draft deletes the entire topic.
Examples
-
Nearly all web browsers and JavaScript environments support writing messages to a console using a suite of logging methods. The most common of these is the
console.log()
method.Open up the JavaScript Console in your browser, type the following, and press Enter:
console.log("Hello, World!");
In this example the
console.log()
function printsHello, World!
to the console, along with a new line, and returnsundefined
(which is also shown above in the console output window), because it has no explicit return value.The
console.log()
function is also commonly used for debugging purposes. See the Console topic for more instructions on using the console.Note: It is also important to note that
console.log()
can also be used to log variables, and not only strings. This is especially useful when logging objects. For example:var foo = "bar"; console.log(foo); // Prints "bar" to the console, returns undefined as in the example above.
Logging an object and all of its properties and methods (this is useful, for example, to log JSON responses received from an API call):
For more information on how to use the console, see the Console topic.
-
DOM stands for Document Object Model and it is an object-oriented approximation from structured documents like XML and HTML.
Setting the
textContent
property of anElement
is one way to output text on a web page.
Associated HTML:document.getElementById("paragraph").textContent = "Hello, World";
<p id="paragraph"></p>
This will set the text content of the element that has the id
paragraph
to "Hello, World".Or, if you haven't yet defined the HTML element in your HTML page, you can create a new HTML element programmatically. In this example we are creating a new
<p></p>
:const element = document.createElement('p'); element.textContent = "Hello, World"; document.body.appendChild(element); //add the newly created element to the DOM
If you're trying to manipulate elements (the DOM) using JavaScript, the JavaScript code must be run after the relevant element has been created in the document. This often means putting the JavaScript
<script>
tags after all of your other<body>
content, or using event such asonload
or jQuery's$(document).ready()
to delay your code until after the page has loaded to execute the code once the document is ready. -
-
The
alert
method displays a visual alert box on screen. The alert method parameter is displayed to the user in plain text:alert('hello, world!');
In Chrome, you would get a pop-up like this:
Note: The
alert
method is technically a property ofwindow
object, but since allwindow
properties are automatically global variables, we can usealert
as a global variable instead of as a property ofwindow
- meaning you can natively usealert()
instead ofwindow.alert()
.Unlike using
console.log
,alert
acts as a modal prompt meaning that no other JavaScript code will execute until the alert is dismissed:alert('Pause!'); console.log('Alert was dismissed');
More information about usage of the
alert
method can be found in the modals prompts topic.The use of alerts is usually discouraged in favour of other methods that do not block users from interacting with the page - in order to create a better user experience. Nevertheless, it can be useful for debugging.
-
Using canvas elements
HTML provides the canvas element for building raster-based images.
First build a canvas for holding image pixel information.
var canvas = document.createElement('canvas'); canvas.width = 500; canvas.height = 250;
Then select a context for the canvas, in this case two-dimensional:
var ctx = canvas.getContext('2d');
Then set properties related to the text:
ctx.font = '30px Cursive'; ctx.fillText("Hello world!", 50, 50);
Then insert the
canvas
element into the page to take effect:document.body.appendChild(canvas);
Using SVG
SVG is for building scalable vector-based graphics and can be used within HTML.
First create an SVG element container with dimensions:
var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); svg.width = 500; svg.height = 50;
Then build a
text
element with the desired positioning and font characteristics:var text = document.createElementNS('http://www.w3.org/2000/svg', 'text'); text.setAttribute('x', '0'); text.setAttribute('y', '50'); text.style.fontFamily = 'Times New Roman'; text.style.fontSize = '50';
Then add the actual text to display to the
text
element:text.textContent = 'Hello world!';
Finally add the
text
element to oursvg
container and add thesvg
container element to the HTML document:svg.appendChild(text); document.body.appendChild(svg);
Image file
If you already have an image file containing the desired text and have it placed on a server, you can add the URL of the image and then add the image to the document as follows:
var img = new Image(); img.src = 'https://i.ytimg.com/vi/zecueq-mo4M/maxresdefault.jpg'; document.body.appendChild(img);
-
An easy way to get an input from a user is by using the
prompt()
method.var age = prompt("How old are you?") console.log(age); // Prints the value inserted by the user
If the user clicks "OK" button, the input value is returned. Otherwise, the method returns null.
Parameters:
prompt(text, [default])
- text: The text displayed in the prompt box [Required]
- default: A default value for the input field [Optional]
Note: While the prompt box is displayed, the user is prevented from accessing other parts of the page.
Remarks
JavaScript (not to be confused with Java) is a dynamic, weakly-typed language used for client-side as well as server-side scripting.
JavaScript is a case-sensitive language. It means the language considers capital letters as different from their lowercase counterparts. Keywords in JavaScript are all lowercase.
JavaScript is a commonly referenced implementation of ECMAScript standard.
Topics in this tag often refer to the use of JavaScript within the browser, unless otherwise stated. JavaScript files alone can't be run directly by the browser; it's necessary to embed them in an HTML document. If you have some JavaScript code you'd like to try, you can embed it in some placeholder content like this, and save the result as example.html
:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Test page</title>
</head>
<body>
Inline script (option 1):
<script>
// YOUR CODE HERE
</script>
External script (option 2):
<script src="your-code-file.js"></script>
</body>
</html>
Topic Outline
- Using console.log()
- Using the DOM API
- Using window.alert()
- Using the DOM API (with graphical text: Canvas, SVG, or image file)
- The prompt() method
Versions
Sign up or log in
Save edit as a guest
Join Stack Overflow
Using Google
Using Facebook
Using Email and Password
We recognize you from another Stack Exchange Network site!
Join and Save Draft