HTML Tips
A clear method to display your data
Often we need a quick check on our data when testing a program. Most of the time you display just the values of your data in an alertbox or in the console. When checking large amounts of data this will get messy. Using JSON.stringify will display your data in a well-organised manner.
var temperature = 20;
var doorsensor = "closed";
var lamp = "off";
alert(JSON.stringify({temperature, doorsensor, lamp}));
document.write(JSON.stringify({temperature, doorsensor, lamp}));
console.log(JSON.stringify({temperature, doorrsensor, lamp}));
This will show an alertbox, on the webpage and in the console the information as follows:
{"temperature":20,"doorsensor":"closed","lamp":"off"}
Activate a link at a certain time
Suppose we are building a webpage where customers can order some stuff but only at at a certain time. We put a link on the page to the actual ordering page but that may only be activated at the determined time. We can achieve that as follows:
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Orders can be placed starting at 17.00 hour</title>
</head>
<body>
<a id="activelink" title="<<You are too early>>" target="_blank">
This link activates at 17.00 hour
</a>
<script>
const link = document.getElementById('activelink');
const actualtime = new Date().getHours();
if (actualtime === 17)
{
link.href = "http://lucstechblog.blogspot.com/";
link.innerHTML="Go to Luc's Blog";
link.title="Order now !!!";
}
</script>
</html>
The script starts with searching the activelink on the page. Then we set the current time in a variable and compare that with 17 (17.00 hour). If the time is 17.00 hour we activate the link, change the text on the page and change the mouse tip.
Add an element to the bottom of a page
Use document.body.appendChild(document.createElement('div')) to add a div to the end of a webpage. It does not need to be a div but can be any element like <p> or <a>. The next example shows how a div is added each time the button is pressed.
<html>
<body>
<button id="clickbut">Add a line</button>
<br><br>
<script>
var eventValue = function (event) {
document.body.appendChild(document.createElement('div'))
.textContent = "Another new line";
}
var pressed = document.querySelector("#clickbut");
pressed.addEventListener("click", eventValue);
</script>
</body>
</html>
Add an element to a list
The next snippet shows how to add an element to a list. The text is fetched from an input field and tested for not to be empty.
<!DOCTYPE html>
<html>
<body>
<a>What do you want to add :</a>
<input id ="newtext" type="text" value = "Javascript tips">
<button id = "newinlist">Voeg toe</button>
<br><br>Hier is de lijst<br>
<ul id="thelist">
<li>ESP 32 Simplified</li>
<li>Raspberry Pi Pico Simplified</li>
</ul>
<script>
document.getElementById("newinlist").addEventListener('click', voegtoe);
function voegtoe()
{
var newelement = document.getElementById("newtext").value;
if (newelement !="")
{
var newli = document.createElement('li');
newli.textContent = newelement;
document.getElementById("thelist").append(newli);
newelement.value = "";
}
}
</script>
</body>
</html>
Add an element to a list 2
Here is another method to add an item to a list.
<!DOCTYPE html>
<html>
<body>
<input id="newtext" type ="text" value = "Javascript tips">
<button id="newinlist">Add to list</button>
<ul id="thelist">
<li>ESP32 Simplified</li>
<li>Raspberry Pi Pico Simplified</li>
</ul>
<div id = "test"></div>
</body>
<script>
var el = document.getElementById("newinlist");
el.onclick = makelist;
function makelist()
{
var itemtoadd = document.getElementById('newtext').value;
var list = document.getElementById('thelist');
var addthis = "<li>"+ itemtoadd +"</li>";
list.insertAdjacentHTML('beforeend', addthis);
itemtoadd.value = '';
}
</script>
</html>
Add or remove an event listener to an element
Using addEventListener() and removeEventListener() we can add or remove eventlisteners to an element. The next example shows hot to add a click event to a <p> webelement.
This is the HTML code
<p id="test">
Click this text
</p>
Here is the Javascript:
document.getElementById("test").addEventListener('click',testclick);
function testclick()
{
alert("clicked")
}
Using removeEventListener() we can remove the eventlistener.
Using addEventListener() and removeEventListener() we can add or remove eventlisteners to an element. The next example shows hot to add a click event to a <p> webelement.
This is the HTML code
<p id="test">
Click this text
</p>
Here is the Javascript:
document.getElementById("test").addEventListener('click',testclick);
function testclick()
{
alert("clicked")
}
Using removeEventListener() we can remove the eventlistener.
Add or remove a class
Using <style> we can set an elements attributes like font-size, color etc. Using a script we can add, remove or toggle that style. The next example gives a web-page with a black text that changes in a larger font and in red when you press the button.
<!DOCTYPE html>
<html>
<head>
<style>
.red
{
font-size: 25px;
color: red
}
</style>
</head>
<body>
<p id="colortext">Change the style by altering the class</p>
<button class="alter">Click here</button>
<p>Click the button to change the class</p>
<script>
document.querySelector(".alter").addEventListener("click", changeclass);
function changeclass() {
var element = document.getElementById("colortext");
element.classList.add("red");
}
</script>
</body>
</html>
If you want to remove the class just use: element.classList.remove("red");
You can toggle the <style> or and off with toggle : element.classList.toggle("red");
Using <style> we can set an elements attributes like font-size, color etc. Using a script we can add, remove or toggle that style. The next example gives a web-page with a black text that changes in a larger font and in red when you press the button.
<!DOCTYPE html>
<html>
<head>
<style>
.red
{
font-size: 25px;
color: red
}
</style>
</head>
<body>
<p id="colortext">Change the style by altering the class</p>
<button class="alter">Click here</button>
<p>Click the button to change the class</p>
<script>
document.querySelector(".alter").addEventListener("click", changeclass);
function changeclass() {
var element = document.getElementById("colortext");
element.classList.add("red");
}
</script>
</body>
</html>
If you want to remove the class just use: element.classList.remove("red");
You can toggle the <style> or and off with toggle : element.classList.toggle("red");
Add text to an element
Generally we use innerHTML to put a text into a field on the webpage. This replaces the text that is already there. We can also choose to add text to that field. Here is an example that adds text to a <div>
<!DOCTYPE html>
<html>
<div id="textfield">Javascript</div>
<script>
document.getElementById("textfield").innerHTML += " tips and tricks";
</script>
</html>
Generally we use innerHTML to put a text into a field on the webpage. This replaces the text that is already there. We can also choose to add text to that field. Here is an example that adds text to a <div>
<!DOCTYPE html>
<html>
<div id="textfield">Javascript</div>
<script>
document.getElementById("textfield").innerHTML += " tips and tricks";
</script>
</html>
Alert the user when he uses page-back
<!DOCTYPE html>
<html>
<title>Don not use it</title>
<body>
<p>Do not press page-back</p>
<script>
window.onbeforeunload = function()
{
alert "Your data will be lost";
};
</script>
</body>
</html>
Allow just one click on a button
Sometimes you want to allow the user to click a button just once. The next snippet shows how to achive this.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title >Test wether the button was pressed</title>
</head>
<body>
<h1>Test wether the button was pressed</h1>
<button class="knop" >Click to test</button>
<script>
document.querySelector(".knop").addEventListener("click", pressed, { once: true });
function pressed()
{
alert ("You pressed the button");
}
</script>
</body>
</html>
</html>
If you click the button the alert wil show. If you click the button a second time nothing will happen.
You can use this on any element on a page.
Alter the onclick function
Javascript kan alter the onclick event of a buttom. Here is an example on how to do that.
<!DOCTYPE html>
<button id="test" onclick="function1()">
Click me
</button>
<script>
function function1()
{
alert("This is not going to fire")
}
var newfunction = document.getElementById('test');
newfunction.setAttribute('onclick', 'alert("This is the new alert");');
</script>
</html>
newfunction.setAttribute() overrules the in the button defined function call.
Javascript kan alter the onclick event of a buttom. Here is an example on how to do that.
<!DOCTYPE html>
<button id="test" onclick="function1()">
Click me
</button>
<script>
function function1()
{
alert("This is not going to fire")
}
var newfunction = document.getElementById('test');
newfunction.setAttribute('onclick', 'alert("This is the new alert");');
</script>
</html>
newfunction.setAttribute() overrules the in the button defined function call.
Automatically invoke the current year
Using new Date().getFullYear() gives us the current year. We can use this to automatically invoke the current year in (for example) a copyright message. The next example shows how a copyright message with the current year is invoked in a <div> at the end of a page using innerHTML.
<!DOCTYPE html>
<html>
<p>
This is a test page that puts<br>
automatically an updated copyright<br>
notice at the end of a page.<br>
<br>
<div id="autoyear"></div>
</p>
<script>
var text = ""
var text = "Copyright "
var text = text + new Date().getFullYear();
document.getElementById("autoyear").innerHTML=text;
</script>
</html>
Using new Date().getFullYear() gives us the current year. We can use this to automatically invoke the current year in (for example) a copyright message. The next example shows how a copyright message with the current year is invoked in a <div> at the end of a page using innerHTML.
<!DOCTYPE html>
<html>
<p>
This is a test page that puts<br>
automatically an updated copyright<br>
notice at the end of a page.<br>
<br>
<div id="autoyear"></div>
</p>
<script>
var text = ""
var text = "Copyright "
var text = text + new Date().getFullYear();
document.getElementById("autoyear").innerHTML=text;
</script>
</html>
Automatically jump to the previous page
By putting the next code into your script the web browser will automatically jump to the previous page after 5 seconds (determined by the value 5000).
<SCRIPT>
setTimeout("history.back();", 5000);
</script>
Be carefull with this code as it will be executed each time the user lands on the page.
Blocking an input field
You can check with onchange() if the text in an input field has changed. You can then block the input by setting the original value back and ignore the input.
The next example shows how to do this but accepts the input when a user tries to change it for the second time.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<INPUT id="inp" type="text" value= "do not change" onchange="testchange()">
<script>
tries = 1;
function testchange()
{
if (tries == 1)
{
alert("DON'T DO THAT");
document.getElementById("inp").value="do not change";
tries = tries + 1;
}
else
{
alert("You made it")
}
}
</script>
</body>
</html>
Change a texts attributes
HTML code allows to set a texts attributes. With Javascript we can change these attributes when the text is already displayed on the page. The next example changes part of a text in subscript.
<html>
<head>
</head>
<body>
<script>
var text = "example";
document.write("The following text in subscript: "+text.sub());
</script>
</body>
</html>
The same way we can change other attributes. If we want to change the text in the variable text Javascript offers the next possibilities:
document.write(text.small())
document.write(text.strike());
document.write(text.italics());
document.write(text.fontsize(10));
document.write(text.fontcolor( "blue" ));
document.write(text.bold());
document.write(text.big());
Change an elements id
If you need to changte an elements ID you can do that with the next snippet.
var element = document.getElementById("originalID");
element.id = "modifiedID";
If you need to changte an elements ID you can do that with the next snippet.
var element = document.getElementById("originalID");
element.id = "modifiedID";
Change an image into another
You can change an image on a webpage into another image by changing the source url. Here is an example.
<img id="butimg" src="https://i.postimg.cc/KzfwQZKS/butred2.png" alt="Buttonred" width="500" height="333">
The above html code places a red button on the webpage.
<script>
var imag = document.getElementById('butimg');
imag.src = "https://i.postimg.cc/d16KhRwY/butblack2.png"
</script>
The script searches the image by its ID and puts it's attributes into the variable imag. imag.src = "url" then changes the image into another image.
You can change an image on a webpage into another image by changing the source url. Here is an example.
<img id="butimg" src="https://i.postimg.cc/KzfwQZKS/butred2.png" alt="Buttonred" width="500" height="333">
The above html code places a red button on the webpage.
<script>
var imag = document.getElementById('butimg');
imag.src = "https://i.postimg.cc/d16KhRwY/butblack2.png"
</script>
The script searches the image by its ID and puts it's attributes into the variable imag. imag.src = "url" then changes the image into another image.
Change the attributes of a text on a page
To change the appearance of a text on a page in for example bold you can use CSS but Javascript can do it also for you.
<!DOCTYPE html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<p id="becomesbold">
This text should be bold
</p>
<button onclick="makebold()">Make it so</button>
<script>
function makebold()
{
becomesbold.innerHTML = "<h1>" + becomesbold.innerHTML + "</h1>";
}
</script>
</html>
Change the background color of a webpage
Actually this is not Javascript but I would not keep this from you.
Using onmouseover="document.bgColor=' it is possible to change the background color of a webpage when moving the mouse over an element on that page.
<!DOCTYPE html>
<html>
<title>Change the background color</title>
<head>
</head>
<body>
<a onmouseover="document.bgColor='springgreen'">Green</a>
<a onmouseover="document.bgColor='plum'">Purple</a>
<a onmouseover="document.bgColor='PowderBlue'">Blue</a>
<script>
</script>
</body>
</html>
Change the background color of a webpage 2
This is just HTML code and no Javascript but I did not want to keep it from you anyway. The following HTML code will present a drop-down menu from which you choose the background color for the page.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
</head>
<body>
<FORM>
<B>Choose a background color:</B>
<SELECT name="backcolor" onChange=(document.bgColor=backcolor.options[backcolor.selectedIndex].value)>
<OPTION value="C0C0C0" >Cool Grey
<OPTION value="0D09A3" >Dark Blue
<OPTION value="808040" >Avocado
<OPTION value="800080" >Purple
<OPTION value="444444" >Gray
<OPTION value="FF0400" >Red
<OPTION value="EFE800" >Yellow
<OPTION value="05EF00" >Green
<OPTION value="0206FF" >Blue
<OPTION value="AE08EF" >Violet
<OPTION value="FF8C8A" >Mauve
<OPTION value="FF80FF" >Pink
<OPTION value="FFCCCC" >Peach
<OPTION value="FFCC99" >Orange
<OPTION value="808080" >Dark Grey
<OPTION value="D5CCBB" >Tan
<OPTION value="DDDDDD" >LightGray
<OPTION value="FBFF73" >Light Yellow
<OPTION value="7CFF7D" >LightGreen
<OPTION value="A6BEFF" >Light Blue
<OPTION value="FFFFFF" >White
</SELECT></FORM>
<script>
</script>
</body>
</html>
Change the values to your own liking. To easily find the hex codes for your color use the tool on this page:
https://www.rapidtables.com/web/color/RGB_Color.html
Change the background color by clicking a button
Using document.body.style.backgroundColor = "blue"; changes the background of a webpage in blue. To achieve this by clicking a button use the next code.
<!DOCTYPE html>
<html>
<body>
<button onclick="backgnd()">Click for a color change</button>
<script>
function backgnd() {
document.body.style.backgroundColor = "blue";
}
</script>
</body>
</html>
Change the background color of an element
To make an element stand out you can change its background color after for example pressing a button. You can do this with element.style.backgroundColor = "color". The next snippet shows how to change the background color of the text of a <div> after pushing a button.
<html>
<body>
<div id="testdiv">
Text from which the background color will be changed
</div>
<button id="colchange" onclick="change()">change the color</button>
<script>
function change()
{
document.getElementById("testdiv").style.backgroundColor = "#ff0000";
}
</script>
</body>
</html>
Change the background color with a drop-down menu
Actually this does not belong here cause it is pure HTML code. Nevertheless I did not want to keep it from you. The next HTML code shows how to change the background of a webpage with a drop-down menu.
<HTML>
<FORM>
Choose a background color:
<SELECT name="backcolor" size="1" onChange=(document.bgColor=backcolor.options[backcolor.selectedIndex].value)>
<OPTION value="FFFFFF" >White
<OPTION value="FF0400" >Red
<OPTION value="800080" >Purple
<OPTION value="EFE800" >Yellow
<OPTION value="05EF00" >Green
<OPTION value="FF80FF" >Pink
<OPTION value="FFCCCC" >Peach
<OPTION value="FFCC99" >Orange
</SELECT>
</FORM>
</HTML>
Actually this does not belong here cause it is pure HTML code. Nevertheless I did not want to keep it from you. The next HTML code shows how to change the background of a webpage with a drop-down menu.
<HTML>
<FORM>
Choose a background color:
<SELECT name="backcolor" size="1" onChange=(document.bgColor=backcolor.options[backcolor.selectedIndex].value)>
<OPTION value="FFFFFF" >White
<OPTION value="FF0400" >Red
<OPTION value="800080" >Purple
<OPTION value="EFE800" >Yellow
<OPTION value="05EF00" >Green
<OPTION value="FF80FF" >Pink
<OPTION value="FFCCCC" >Peach
<OPTION value="FFCC99" >Orange
</SELECT>
</FORM>
</HTML>
Change the backgroundcolor on a page every x seconds
You can change the background color of a webpage every x
seconds with the command setTimeout. The next snippet shows
how to change the background color every 3 seconds.
setTimeout("document.bgColor = 'deeppink'", 3000)
setTimeout("document.bgColor = 'red'", 6000)
setTimeout("document.bgColor = 'blue'", 9000)
setTimeout("document.bgColor = 'white'", 12000)
You can change the background color of a webpage every x
seconds with the command setTimeout. The next snippet shows
how to change the background color every 3 seconds.
setTimeout("document.bgColor = 'deeppink'", 3000)
setTimeout("document.bgColor = 'red'", 6000)
setTimeout("document.bgColor = 'blue'", 9000)
setTimeout("document.bgColor = 'white'", 12000)
Change the background of a input field after it is filled in
To show the user that he has filled in a field we can change the background color of that field if the user clicks outside the field or presses TAB. To test if the field was left use onblur. To change the background color use text.style.background where text is the ID of the field.
<!DOCTYPE html>
<html>
<body>
<p>Put your text below:</p>
<input type = "text" id = "text0" onblur = "colorise()">
<script>
function colorise()
{
text0.style.background = "lightblue";
}
</script>
</body>
</html>
Change the backgroundcolor on a page every x seconds
You can change the background color of a webpage every x
seconds with the command setTimeout. The next snippet shows
how to change the background color every 3 seconds.
setTimeout("document.bgColor = 'deeppink'", 3000)
setTimeout("document.bgColor = 'red'", 6000)
setTimeout("document.bgColor = 'blue'", 9000)
setTimeout("document.bgColor = 'white'", 12000)o edit.
You can change the background color of a webpage every x
seconds with the command setTimeout. The next snippet shows
how to change the background color every 3 seconds.
setTimeout("document.bgColor = 'deeppink'", 3000)
setTimeout("document.bgColor = 'red'", 6000)
setTimeout("document.bgColor = 'blue'", 9000)
setTimeout("document.bgColor = 'white'", 12000)o edit.
Change the mouse pointer
With just one simple command we can change the looks of the mousepointer.
document.body.style.cursor = "default";
This sets the mouse pointer back in its default state.
Here is a list of choices of mousepointers that are available:
.alias {cursor: alias;}
.all-scroll {cursor: all-scroll;}
.auto {cursor: auto;}
.cell {cursor: cell;}
.col-resize {cursor: col-resize;}
.context-menu {cursor: context-menu;}
.copy {cursor: copy;}
.crosshair {cursor: crosshair;}
.default {cursor: default;}
.e-resize {cursor: e-resize;}
.ew-resize {cursor: ew-resize;}
.grab {cursor: grab;}
.grabbing {cursor: grabbing;}
.help {cursor: help;}
.move {cursor: move;}
.n-resize {cursor: n-resize;}
.ne-resize {cursor: ne-resize;}
.nesw-resize {cursor: nesw-resize;}
.ns-resize {cursor: ns-resize;}
.nw-resize {cursor: nw-resize;}
.nwse-resize {cursor: nwse-resize;}
.no-drop {cursor: no-drop;}
.none {cursor: none;}
.not-allowed {cursor: not-allowed;}
.pointer {cursor: pointer;}
.progress {cursor: progress;}
.row-resize {cursor: row-resize;}
.s-resize {cursor: s-resize;}
.se-resize {cursor: se-resize;}
.sw-resize {cursor: sw-resize;}
.text {cursor: text;}
.url {cursor: url(myBall.cur),auto;}
.w-resize {cursor: w-resize;}
.wait {cursor: wait;}
.zoom-in {cursor: zoom-in;}
.zoom-out {cursor: zoom-out;}
With just one simple command we can change the looks of the mousepointer.
document.body.style.cursor = "default";
This sets the mouse pointer back in its default state.
Here is a list of choices of mousepointers that are available:
.alias {cursor: alias;}
.all-scroll {cursor: all-scroll;}
.auto {cursor: auto;}
.cell {cursor: cell;}
.col-resize {cursor: col-resize;}
.context-menu {cursor: context-menu;}
.copy {cursor: copy;}
.crosshair {cursor: crosshair;}
.default {cursor: default;}
.e-resize {cursor: e-resize;}
.ew-resize {cursor: ew-resize;}
.grab {cursor: grab;}
.grabbing {cursor: grabbing;}
.help {cursor: help;}
.move {cursor: move;}
.n-resize {cursor: n-resize;}
.ne-resize {cursor: ne-resize;}
.nesw-resize {cursor: nesw-resize;}
.ns-resize {cursor: ns-resize;}
.nw-resize {cursor: nw-resize;}
.nwse-resize {cursor: nwse-resize;}
.no-drop {cursor: no-drop;}
.none {cursor: none;}
.not-allowed {cursor: not-allowed;}
.pointer {cursor: pointer;}
.progress {cursor: progress;}
.row-resize {cursor: row-resize;}
.s-resize {cursor: s-resize;}
.se-resize {cursor: se-resize;}
.sw-resize {cursor: sw-resize;}
.text {cursor: text;}
.url {cursor: url(myBall.cur),auto;}
.w-resize {cursor: w-resize;}
.wait {cursor: wait;}
.zoom-in {cursor: zoom-in;}
.zoom-out {cursor: zoom-out;}
Change the color of an element by hovering the mouse over it
This is not a Javascript text but I think it will come handy on designing a web-page. The next snippet shows how to change a color of an element when you hover the mouse over it.
<html>
<head>
<style>
p:hover
{
color: #FF0000
}
h1:hover
{
color: #FF0000
}
</style>
</head>
<body>
<h1>Hover the mouse over this text</h1>
<p>And here also</p>
</body>
</html>
Change the color of several elements on a webpage
To change the color (or another attribute) of several elements on a webpage at the same time use the following method. Start with giving the elements the same class name. We can then select them with that name. The next example shows how to do that.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Change several elements at the same time</title>
</head>
<body>
<h2 class="tochange">This heading wil change its color</h2>
<p class="tochange">This paragraph too</p>
<div class="tochange">
<p>Anything in this div changes too.</p>
</div>
<button onclick="changethecolor()">Klik om te kleuren</button>
<script>
function changethecolor() {
var elements;
var i;
elements = document.querySelectorAll(".tochange");
for (i = 0; i < elements.length; i++) {
elements[i].style.color = "red";
}
}
</script>
</body>
</html>
Short explanation.
First we catch all elements with the class name "tochange" into the array elements. Next we ieterate over the array and change the color of the elements text. This method can be used for changing all kinds of attributes of elements.
Change the font size and color of an element on a webpage
Sometimes you want to emphasize something on a webpage when a user clicks on that element. You can achieve that with the following method:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h1 onclick="change()">Change the font size and color by clicking here</h1>
<button class="Btn" onclick="change()">CLICK HERE</button>
<h3>Click the button to change its fontsize and color</h3>
<script>
function change() {
event.target.style.fontSize = "32px";
event.target.style.color = "red";
}
</script>
</body>
</html>
The HTML function onclick testss if an element is clicked and then calls the Javascript function change().
In Javascripts function change() the event.target knows which item has been clicked and the style part alters that elements size and color.
Change the text of a button
You can change the text of a button when the button is clicked or clicking performed a function. This way the user knows the action has already been done. You can do this by changing the innerHTML attribute of the button.
<!DOCTYPE html>
<html>
<body>
<button id="button0" type="button" onclick="changetext()">Click to change</button>
</form>
<script>
function changetext()
{
document.getElementById("button0").innerHTML="Changed text";
}
</script>
</body>
</html>
Change the text on a page
Sometimes there is a text on a webpage that you want to alter when for example a variable has changed its value or when some other action has taken place. The next example which can easily be adapted changes text in a <div> when a button is clicked.
Start with adding a button and a div with some text in your HTML code:
<button onclick="change()">Click here for changing text</button>
<div id="changediv">Hi this is text 1</div>
Now add some Javascript in the <script> section on your page:
function changediv()
{
var x = document.getElementById("mijndiv");
if (x.innerHTML === "Hi this is text 1") {
x.innerHTML = "Something different";
} else {
x.innerHTML = "Hi this is text 1";
}
}
Each time you press the button the text will change from Hi this is text 1 to Something different. This also works with other elements on your page like <p> and <a>.
Change your text in bold
If you need to change the appearance of a text in bold you can do that as follows.
var teststring = new String("this is the changed text");
document.write("This text is normal: "+teststring.bold());
VYou can use the following variations:
document.write(teststring.small())
document.write(teststring.strike());
document.write(teststring.italics());
document.write(teststring.fontsize(10));
document.write(teststring.fontcolor( "blue" ));
document.write(teststring.bold());
document.write(teststring.big());
Change the size of an image
If you need to change the width and height of an image you can do that with the next commands:
var image = document.getElementById('id');
xval=100
yval=100
image.width=xval;
image.height=yval;
Start with identifying the image by its ID. Then use width and height to change its size.
If you need to change the width and height of an image you can do that with the next commands:
var image = document.getElementById('id');
xval=100
yval=100
image.width=xval;
image.height=yval;
Start with identifying the image by its ID. Then use width and height to change its size.
Change the space between words
You can changethe spacing between words on a webpage with the element.style.wordSpacing = "numberpx" You need to change numberpx in the number you need like 25px.
Here is the element we are going to change:
<div id="text">Hello this is a test</div>
This is the code to change the spacing of the chosen element.
document.getElementById("text").style.wordSpacing = "25px";
You can changethe spacing between words on a webpage with the element.style.wordSpacing = "numberpx" You need to change numberpx in the number you need like 25px.
Here is the element we are going to change:
<div id="text">Hello this is a test</div>
This is the code to change the spacing of the chosen element.
document.getElementById("text").style.wordSpacing = "25px";
Change the text of a button
You can change the text of a button when the button is clicked or clicking performed a function. This way the user knows the action has already been done. You can do this by changing the innerHTML attribute of the button.
<!DOCTYPE html>
<html>
<body>
<button id="button0" type="button" onclick="changetext()">Click to change</button>
</form>
<script>
function changetext()
{
document.getElementById("button0").innerHTML="Changed text";
}
</script>
</body>
</html>
You can change the text of a button when the button is clicked or clicking performed a function. This way the user knows the action has already been done. You can do this by changing the innerHTML attribute of the button.
<!DOCTYPE html>
<html>
<body>
<button id="button0" type="button" onclick="changetext()">Click to change</button>
</form>
<script>
function changetext()
{
document.getElementById("button0").innerHTML="Changed text";
}
</script>
</body>
</html>
Change the text on a page
Sometimes there is a text on a webpage that you want to alter when for example a variable has changed its value or when some other action has taken place. The next example which can easily be adapted changes text in a <div> when a button is clicked.
Start with adding a button and a div with some text in your HTML code:
<button onclick="change()">Click here for changing text</button>
<div id="changediv">Hi this is text 1</div>
Now add some Javascript in the <script> section on your page:
function changediv()
{
var x = document.getElementById("mijndiv");
if (x.innerHTML === "Hi this is text 1") {
x.innerHTML = "Something different";
} else {
x.innerHTML = "Hi this is text 1";
}
}
Each time you press the button the text will change from Hi this is text 1 to Something different. This also works with other elements on your page like <p> and <a>. You can also add html codes to let a text stand out like this:
x.innerHTML = "<h1>Something different</h1>";
Sometimes there is a text on a webpage that you want to alter when for example a variable has changed its value or when some other action has taken place. The next example which can easily be adapted changes text in a <div> when a button is clicked.
Start with adding a button and a div with some text in your HTML code:
<button onclick="change()">Click here for changing text</button>
<div id="changediv">Hi this is text 1</div>
Now add some Javascript in the <script> section on your page:
function changediv()
{
var x = document.getElementById("mijndiv");
if (x.innerHTML === "Hi this is text 1") {
x.innerHTML = "Something different";
} else {
x.innerHTML = "Hi this is text 1";
}
}
Each time you press the button the text will change from Hi this is text 1 to Something different. This also works with other elements on your page like <p> and <a>. You can also add html codes to let a text stand out like this:
x.innerHTML = "<h1>Something different</h1>";
Change your text in bold
If you need to change the appearance of a text in bold you can do that as follows.
var teststring = new String("this is the changed text");
document.write("This text is normal: "+teststring.bold());
VYou can use the following variations:
document.write(teststring.small())
document.write(teststring.strike());
document.write(teststring.italics());
document.write(teststring.fontsize(10));
document.write(teststring.fontcolor( "blue" ));
document.write(teststring.bold());
document.write(teststring.big());
If you need to change the appearance of a text in bold you can do that as follows.
var teststring = new String("this is the changed text");
document.write("This text is normal: "+teststring.bold());
VYou can use the following variations:
document.write(teststring.small())
document.write(teststring.strike());
document.write(teststring.italics());
document.write(teststring.fontsize(10));
document.write(teststring.fontcolor( "blue" ));
document.write(teststring.bold());
document.write(teststring.big());
Clearing part of a webpage
Using innerHTML we can get information out of an object on a webpage or put information into that object. We can use that also to clear part of a webpage. This is done by document.body.innerHTML = ''; which replaces the body of the webpage with an empty string. Depending on where you put the command evrything before the command will be erased and everything following will stay visible.
Here is an example that clarifies this.
<html>
<head></head>
<body>
<p>This tekst will be erased</p>
<script>
document.body.innerHTML = '';
</script>
<p>This text will be shown</p>
</body>
</html>
Click on a button and execute a function delayed
Most of the time you want a function to execute immediately when you click a button. Sometimes however you want to delay the function for a certain time. This is how it is done.
<!DOCTYPE html>
<html>
<body>
<button onclick="delayfunc()">Try me</button>
<script>
function delayfunc() {
setTimeout(function(){ alert("Delayed for 3 seconds"); }, 3000);
}
</script>
<p>Click the button and wait for 3 seconds.</p>
</body>
</html>
Create a list and add entries
On a webpage there is a button and an input field.
<button id = "test">
click me for adding
</button>
<input id="inp">
<p id="listhere">HERE COMES MY LIST</p>
The next snippet will create a list and add items to it that you supply in the input field.
document.getElementById("test").onclick = function()
{
var node = document.createElement("Li");
var text = document.getElementById("inp").value;
var textnode=document.createTextNode(text);
node.appendChild(textnode);
document.getElementById("listhere").appendChild(node);
}ck here to edit.
On a webpage there is a button and an input field.
<button id = "test">
click me for adding
</button>
<input id="inp">
<p id="listhere">HERE COMES MY LIST</p>
The next snippet will create a list and add items to it that you supply in the input field.
document.getElementById("test").onclick = function()
{
var node = document.createElement("Li");
var text = document.getElementById("inp").value;
var textnode=document.createTextNode(text);
node.appendChild(textnode);
document.getElementById("listhere").appendChild(node);
}ck here to edit.
Create a random color
If you need a random color for your page or text this is how you can create it.
function makecolor() {
var letters = '0123456789ABCDEF';
var hexcolor = '#';
for (var i = 0; i < 6; i++) {
hexcolor += letters[Math.floor(Math.random() * 16)];
}
return hexcolor;
}
var newcolor = makecolor();
alert(newcolor)
If you need a random color for your page or text this is how you can create it.
function makecolor() {
var letters = '0123456789ABCDEF';
var hexcolor = '#';
for (var i = 0; i < 6; i++) {
hexcolor += letters[Math.floor(Math.random() * 16)];
}
return hexcolor;
}
var newcolor = makecolor();
alert(newcolor)
Copy a text to multiple elements
If there is a text on a page that can change and you want it to change on multiple places on the page you can do that by giving all fields the same class. The next example takes an input field and puts the information from that field in several elements all having the same class name.
<html>
<body>
<h1>Copy the text to multiple fields</h1>
<input type="text" class="lang" placeholder="Prog. language" />
<button class="but">Preferred language</button>
<p class = "lang">......</p>
<div class = "lang">......</div>
<a class = "lang">......</a>
<script>
let butele = document.querySelector(".but");
let langele = document.querySelectorAll(".lang");
butele.addEventListener("click", () =>
{
for (var i=1; i<langele.length; i++)
{
langele[i].innerHTML = langele[0].value;
}
});
</script>
</body>
</html>
Copy a text to the clipboard
The next lines of code show how you can copy a part from the webpage to the clipboard. From there you can paste it in any other program
First the HTML part:
<html>
<input type="text" value="Hello world" id="mytext">
<button onclick="copyit()">Copy this text</button>
</html>
And here is the Javascript code:
function copyit()
{
var copiedtext = document.getElementById('mytext')
copiedtext.select();
document.execCommand('copy')
console.log('Copied Text')
}
The next lines of code show how you can copy a part from the webpage to the clipboard. From there you can paste it in any other program
First the HTML part:
<html>
<input type="text" value="Hello world" id="mytext">
<button onclick="copyit()">Copy this text</button>
</html>
And here is the Javascript code:
function copyit()
{
var copiedtext = document.getElementById('mytext')
copiedtext.select();
document.execCommand('copy')
console.log('Copied Text')
}
Count how many times the user scrolls up or down
Here follows a tip which you will not use often but may come handy at one time.
The code below has a variable called timesscrolled that counts how many times a user has scrolled the mousewheel (up and down) on the page.
let totaalscroll = 0;
window.addEventListener("wheel", function (action) {
const again = action.deltaY;
if (aantal > 0) {
timesscrolled++;
} else {
timesscrolled--;
}
console.log(timesscrolled);
});
Create a new DOM element and give it an ID
The next example shows how to create a new element on a page. First we determine where the element should come. This is done by selecting the element that comes before the new place. Then we create the new element with element.appendChild(). The element gets an ID with element.setAttribute("id", "id-naam"); This example also shows a button on the screen. Pressing the button changes the text of the fresh made element. This serves as an example to show how to make a new element and select it to change it. Alter it for your own purposes.
<html>
<body>
<div id="new">
<p id="p1">ESP32 Simplified</p>
<p id="p2">Raspberry Pi Pico Simplified</p>
<button onclick="changetext()">Click to change</button>
</div>
<script>
var tag = document.createElement("p");
tag.setAttribute("id", "test");
var text = document.createTextNode("Here comes the new text");
tag.appendChild(text);
var element = document.getElementById("p2");
element.appendChild(tag);
function changetext()
{
document.getElementById("test").innerHTML="Javascript tips"
}
</script>
</body>
</html>
Create a paragraph on your webpage
If you need to put some text or data on a website you can create a paragraph on the page after a page element with a known ID. Here is an example that creates a paragraph with the text "Hello World" which is placed on the webpage after the <div> with the id "the-parent"
<!DOCTYPE html>
<html>
<body>
<div id=the-parent></div>
<script>
var paragraph = document.createElement('p');
paragraph.innerHTML = 'Hello world';
document.getElementById('the-parent').appendChild(paragraph);
</script>
</body>
</html>
If you need to insert the paragraph before the div element you can use the next lines.
var paragraph = document.createElement('p');
paragraph.innerHTML = 'Hello world';
el = document.getElementById('the-parent')
el.parentNode.insertBefore(paragraph, el);
If you need to put some text or data on a website you can create a paragraph on the page after a page element with a known ID. Here is an example that creates a paragraph with the text "Hello World" which is placed on the webpage after the <div> with the id "the-parent"
<!DOCTYPE html>
<html>
<body>
<div id=the-parent></div>
<script>
var paragraph = document.createElement('p');
paragraph.innerHTML = 'Hello world';
document.getElementById('the-parent').appendChild(paragraph);
</script>
</body>
</html>
If you need to insert the paragraph before the div element you can use the next lines.
var paragraph = document.createElement('p');
paragraph.innerHTML = 'Hello world';
el = document.getElementById('the-parent')
el.parentNode.insertBefore(paragraph, el);
Delete an element from the page
The next snippet shows how to delete an element from your webpage. In this example the page contains a button with the id but1 and a div with the id div1. Both elements are removed from the page when you click them.
<!DOCTYPE html>
<html>
<body>
<button id="but1", onclick="deleteme(this)">click me</button>
<br>
<div id="div1", onclick="deleteme(this)">try me</div>
</body>
<script>
function deleteme(element){
element.parentNode.removeChild(element);
}
</script>
</html>
The next snippet shows how to delete an element from your webpage. In this example the page contains a button with the id but1 and a div with the id div1. Both elements are removed from the page when you click them.
<!DOCTYPE html>
<html>
<body>
<button id="but1", onclick="deleteme(this)">click me</button>
<br>
<div id="div1", onclick="deleteme(this)">try me</div>
</body>
<script>
function deleteme(element){
element.parentNode.removeChild(element);
}
</script>
</html>
Different functions when clicking an element
.onclick = executes a function when a button or element gets clicked. We can change .onclick = to have the same element execute a different function each time it is clicked.
<button id="clickme">Click Me</button>
<script>
function one() {
alert('one clicked');
document.getElementById('clickme').onclick = two;
}
function two() {
alert('two clicked');
}
document.getElementById('clickme').onclick = one;
</script>
First no function is called in the button definition. That is done in the script by document.getElementById('clickme').onclick = one; Whenh clicked function one is executed and in there the function call is changed in two. So when the button is clicked again function two is activated and that changes the call back to function one. This makes the button click alternately call function one and function two.
.onclick = executes a function when a button or element gets clicked. We can change .onclick = to have the same element execute a different function each time it is clicked.
<button id="clickme">Click Me</button>
<script>
function one() {
alert('one clicked');
document.getElementById('clickme').onclick = two;
}
function two() {
alert('two clicked');
}
document.getElementById('clickme').onclick = one;
</script>
First no function is called in the button definition. That is done in the script by document.getElementById('clickme').onclick = one; Whenh clicked function one is executed and in there the function call is changed in two. So when the button is clicked again function two is activated and that changes the call back to function one. This makes the button click alternately call function one and function two.
Disable a button
To disable a button you can use the command button.disabled=true. The next example puts a button on the webpage that will be disabled after you clicked it.
Here is the HTML code:
<button id="test" onclick = clickfunc()>clickme</button>
And here is the Javascript code:
function clickfunc()
{
alert("Button is now disabled")
document.getElementById("test").disabled = true;
}
This also works with other HTML tags like <input>
To disable a button you can use the command button.disabled=true. The next example puts a button on the webpage that will be disabled after you clicked it.
Here is the HTML code:
<button id="test" onclick = clickfunc()>clickme</button>
And here is the Javascript code:
function clickfunc()
{
alert("Button is now disabled")
document.getElementById("test").disabled = true;
}
This also works with other HTML tags like <input>
Disable an eventlistener
An eventlistener can be attached to an element to invoke an action when for example a button is pressed or the mouse moves over an element. Naturally it is possible to disable that eventlistener when for example a condition is met or the button is pressed to often. Disabling the eventlistener is done with element.removeEventListener You need to specify exactly which event you want to disable as multiple events can be attached to one element.
The next example shows an alarm button that displays a message each time it is pressed. Next to that there is another button that will disable the eventlistener for the alarm button.
<!DOCTYPE html>
<html>
<body>
<p>Click the alarm button for a message<br>
Click on remove to disable the alarm</p>
<button id="alarm">Alarm</button>
<button onclick="removeevent()" id="btnid">Verwijder</button>
<script>
document.getElementById("alarm").addEventListener("click", showalarm);
function showalarm() {
alert("ALARM")
}
function removeevent() {
document.getElementById("alarm").removeEventListener("click",showalarm);
}
</script>
</body>
</html>
Disable double clicking a button
The next snippet shows how to disable double clicking a button. For achieving this we diaable the button immediately when it is clicked. We can do that with element.disabled = true To activate the button again use element.disabled = false The next example disables the button for 2 seconds after it has been clicked.
<!DOCTYPE html>
<html>
<head>
<body>
<button>Try me</button>
<script>
const trybut = document.querySelector('button');
trybut.disabled = false;
trybut.addEventListener('click', function()
{
trybut.disabled = true;
alert("you clicked");
setTimeout(() =>
{
trybut.disabled = false;
}, 2000);
});
</script>
</head>
</body>
</html>
Disable selecting and copying text with CSS
If there are certain parts of a text or another object that you want to prevent being selected and copied that can be done with some CSS code. The next example shows how to do that.
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
.unselectable {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
</style>
</head>
<body>
<p>This text can be selected and copied</p>
<div class="unselectable">This text can not be copied</div>
</body>
</html>
Using <div class="unselectable"> calls the CSS code which makes the object (div) un-selectable. The CSS code has several user-select: none lines that makes sure this works for all browsers.
If there are certain parts of a text or another object that you want to prevent being selected and copied that can be done with some CSS code. The next example shows how to do that.
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
.unselectable {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
</style>
</head>
<body>
<p>This text can be selected and copied</p>
<div class="unselectable">This text can not be copied</div>
</body>
</html>
Using <div class="unselectable"> calls the CSS code which makes the object (div) un-selectable. The CSS code has several user-select: none lines that makes sure this works for all browsers.
Display a scrolling text
The next program shows how to scroll a text from left to right across the screen. The text, size, color and speed can easily be adjusted.
<html>
<body onload="scroll()">
<h1 style="color:red; font-size:50px;">
<pre id="scrolltext">Javascript Tips </pre>
</h1>
<script>
function scroll()
{
text = document.getElementById("scrolltext").innerHTML;
setInterval(function ()
{
text = text[text.length - 1] + text.substring(0, text.length - 1);
document.getElementById("scrolltext").innerHTML=text;
}, 200);
}
</script>
</body>
</html>
The next program shows how to scroll a text from left to right across the screen. The text, size, color and speed can easily be adjusted.
<html>
<body onload="scroll()">
<h1 style="color:red; font-size:50px;">
<pre id="scrolltext">Javascript Tips </pre>
</h1>
<script>
function scroll()
{
text = document.getElementById("scrolltext").innerHTML;
setInterval(function ()
{
text = text[text.length - 1] + text.substring(0, text.length - 1);
document.getElementById("scrolltext").innerHTML=text;
}, 200);
}
</script>
</body>
</html>
Displaying text faster and faster
To emphasize a portion of a page we can have a text appear letter by letter and have the speed increase at every letter. Here is an example that achieves this.
<!DOCTYPE html>
<html>
<body>
<h1>Faster and faster</h1>
<button class="textbutton">Click to start</button>
<h2 class="textlocation"></h2>
<script>
document.querySelector('.textbutton').addEventListener('click',typeText);
var i = 0;
var text = "This text will appear faster and faster to emphasize that something is happening here";
var length = text.length
var speed = 50+ length *5;
function typeText() {
if (i < text.length) {
document.querySelector('.textlocation').innerHTML += text.charAt(i);
i++;
setTimeout(typeText, speed);
speed=speed-5;
}
}
</script>
</body>
</html>
A short explanation of the most important parts. Using var length = text.length determines the length of the text. The program then multiplies this value by 5 and adds 50. This determines the initial speed. Alter this to your own likings. next document.querySelector('.textlocation').innerHTML += text.charAt(i); puts the letters one by one on the screen. Every time a letter appears speed=speed-5; decreases the speed. The speed is then used with setTimeout(typeText, speed); to slow down the function.
You can alter this by starting at an initial speed of 0 and slowing down with speed=speed=5; Again, adjust to your own liking
To emphasize a portion of a page we can have a text appear letter by letter and have the speed increase at every letter. Here is an example that achieves this.
<!DOCTYPE html>
<html>
<body>
<h1>Faster and faster</h1>
<button class="textbutton">Click to start</button>
<h2 class="textlocation"></h2>
<script>
document.querySelector('.textbutton').addEventListener('click',typeText);
var i = 0;
var text = "This text will appear faster and faster to emphasize that something is happening here";
var length = text.length
var speed = 50+ length *5;
function typeText() {
if (i < text.length) {
document.querySelector('.textlocation').innerHTML += text.charAt(i);
i++;
setTimeout(typeText, speed);
speed=speed-5;
}
}
</script>
</body>
</html>
A short explanation of the most important parts. Using var length = text.length determines the length of the text. The program then multiplies this value by 5 and adds 50. This determines the initial speed. Alter this to your own likings. next document.querySelector('.textlocation').innerHTML += text.charAt(i); puts the letters one by one on the screen. Every time a letter appears speed=speed-5; decreases the speed. The speed is then used with setTimeout(typeText, speed); to slow down the function.
You can alter this by starting at an initial speed of 0 and slowing down with speed=speed=5; Again, adjust to your own liking
document.getElementById("ID of element") is not perse needed
To select an element from a webpage we start with giving the element an ID. In our code we use that ID to search the element with document.getElementById("ID of element") and then do something with it. But that is not perse necessary. You can use the ID itself to select the element.
<!DOCTYPE html>
<html>
<body>
<button id="testbut" type="button" onclick="changeit()">Click to change</button>
<script>
function changeit()
{
testbut.innerHTML="New text";
testbut.style.background = "skyblue";
}
</script>
</body>
</html>
This example shows how the text and color of a button change when you click it. We do not use document.getElementById("ID of element") but use the ID of the button.
Enable or disable buttons or input fields
Sometimes you want to enable a button, radiobutton or inputfield etc. after a certain action has completed. The document.getElementById('ID').disabled = true; command disables the element and with document.getElementById('ID').disabled = false; you can enable the elemnt. The next example puts 3 buttons on a webpage. The On and Off buttons activate or de-activate the Try Me button.
<html>
<head>
</head>
<body>
<p>
<input id="but01" type="button" value="Try Me" onClick="buttonclick();"></input>
</p>
<input id="but02" type="button" value="ON" onClick="butenable();"></input>
<input id="but03" type="button" value="OFF" onClick="butdisable();"></input>
</body>
<script>
function butdisable()
{
document.getElementById('but01').disabled = true;
}
function butenable()
{
document.getElementById('but01').disabled = false;
}
function buttonclick()
{
alert ("The button works")
}
</script>
</html>
Sometimes you want to enable a button, radiobutton or inputfield etc. after a certain action has completed. The document.getElementById('ID').disabled = true; command disables the element and with document.getElementById('ID').disabled = false; you can enable the elemnt. The next example puts 3 buttons on a webpage. The On and Off buttons activate or de-activate the Try Me button.
<html>
<head>
</head>
<body>
<p>
<input id="but01" type="button" value="Try Me" onClick="buttonclick();"></input>
</p>
<input id="but02" type="button" value="ON" onClick="butenable();"></input>
<input id="but03" type="button" value="OFF" onClick="butdisable();"></input>
</body>
<script>
function butdisable()
{
document.getElementById('but01').disabled = true;
}
function butenable()
{
document.getElementById('but01').disabled = false;
}
function buttonclick()
{
alert ("The button works")
}
</script>
</html>
Fill a table with an array
If you need to fill a table on your HTML page with the contents of an array you can use the following method.
In this example the array consists of multiple objects which have the name of the month (month), the temperature (tmp) and rain information (rain).
var testarray = [
{ month:"Jan", tmp:"10", rain:"yes" },
{ month:"Feb", tmp:"15", rain:"yes" },
{ month:"Mar", tmp:"20", rain:"no" },
];
Here is the complete HTML page that achieves this.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table style="width:25%" id="table1">
<tbody></tbody>
<thead>
<th>Month</th>
<th>Temperature</th>
<th>Rain</th>
</thead>
</table>
</body>
<script>
var testarray = [
{ month:"Jan", tmp:"10", rain:"yes" },
{ month:"Feb", tmp:"15", rain:"yes" },
{ month:"Mar", tmp:"20", rain:"no" },
];
var tabfil = "";
for (i=0; i<testarray.length; i++)
{
tabfil = tabfil + "<tr><td>"+testarray[i].month+"</td><td>"+testarray[i].tmp+"</td><td>"+testarray[i].rain+"</td></tr>";
}
document.querySelector("#table1 tbody").innerHTML = tabfil;
</script>
</html>
It looks more complicated then it is.
Start with defining the table in the HTML body part.
The script iterates over every array element.
The variable tabfil is first filled with <tr> which starts a new row in the table. Next <td> is added which starts a new column, and each column is filled with the contents of the object.
If you need to fill a table on your HTML page with the contents of an array you can use the following method.
In this example the array consists of multiple objects which have the name of the month (month), the temperature (tmp) and rain information (rain).
var testarray = [
{ month:"Jan", tmp:"10", rain:"yes" },
{ month:"Feb", tmp:"15", rain:"yes" },
{ month:"Mar", tmp:"20", rain:"no" },
];
Here is the complete HTML page that achieves this.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table style="width:25%" id="table1">
<tbody></tbody>
<thead>
<th>Month</th>
<th>Temperature</th>
<th>Rain</th>
</thead>
</table>
</body>
<script>
var testarray = [
{ month:"Jan", tmp:"10", rain:"yes" },
{ month:"Feb", tmp:"15", rain:"yes" },
{ month:"Mar", tmp:"20", rain:"no" },
];
var tabfil = "";
for (i=0; i<testarray.length; i++)
{
tabfil = tabfil + "<tr><td>"+testarray[i].month+"</td><td>"+testarray[i].tmp+"</td><td>"+testarray[i].rain+"</td></tr>";
}
document.querySelector("#table1 tbody").innerHTML = tabfil;
</script>
</html>
It looks more complicated then it is.
Start with defining the table in the HTML body part.
The script iterates over every array element.
The variable tabfil is first filled with <tr> which starts a new row in the table. Next <td> is added which starts a new column, and each column is filled with the contents of the object.
Flatten an array
If you need to flatten a multi dimensional array you can do that with array.flat(). Here is an example that shows how this works.
var array = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
array = array.flat()
alert (array)
If you need to flatten a multi dimensional array you can do that with array.flat(). Here is an example that shows how this works.
var array = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
array = array.flat()
alert (array)
Force focus to an inputfield
Sometimes you need to force the user to pay attention to a certain input field. The field might be left empty or filled in with a wrong value.
The next example shows 3 input fields and pressing the button forces the focus to field 2:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
</head>
<body>
Give your Name:<input type="text" id="input1" value="Luc"><br>
Give your Adres:<input type="text" id="input2" value="Somestreet"><br>
Give your Place:<input type="text" id="input3" value="Earth"><br>
<br>
<button type="button" onclick="check()">Select Text Box</button>
<script>
function check(){
document.getElementById("input2").select();
}
</script>
</body>
</html>
Sometimes you need to force the user to pay attention to a certain input field. The field might be left empty or filled in with a wrong value.
The next example shows 3 input fields and pressing the button forces the focus to field 2:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
</head>
<body>
Give your Name:<input type="text" id="input1" value="Luc"><br>
Give your Adres:<input type="text" id="input2" value="Somestreet"><br>
Give your Place:<input type="text" id="input3" value="Earth"><br>
<br>
<button type="button" onclick="check()">Select Text Box</button>
<script>
function check(){
document.getElementById("input2").select();
}
</script>
</body>
</html>
Format HTML code in a string with multiple lines
To format HTML code neatly we split it over multiple lines. If you want to put the code into a variable that will pose some problems.
var htmlcode = "<p>
A random text.
</p>";
The lines above will give an error in Javascript. To solve that put a backslash at the end of eacht line like the following snippet demonstrates.
var htmlcode = "<div>\
A random text.\
</div>";
To format HTML code neatly we split it over multiple lines. If you want to put the code into a variable that will pose some problems.
var htmlcode = "<p>
A random text.
</p>";
The lines above will give an error in Javascript. To solve that put a backslash at the end of eacht line like the following snippet demonstrates.
var htmlcode = "<div>\
A random text.\
</div>";
Get a selected text
If you need to get the part of a webpage (text) that has been selected, highlighted with the mouse, by the user you can use the next command:
text = window.getSelection().toString();
Here is an example that gets the text when the user highlights a text and then presses a key
document.onkeypress = function ()
{
text = window.getSelection().toString();
alert(text)
}
If you need to get the part of a webpage (text) that has been selected, highlighted with the mouse, by the user you can use the next command:
text = window.getSelection().toString();
Here is an example that gets the text when the user highlights a text and then presses a key
document.onkeypress = function ()
{
text = window.getSelection().toString();
alert(text)
}
Get a value from a table
To get a certain value out of the cell of a table you can use
document.getElementById("tablename").rows[X].cells[Y]. The table must have an ID and the row and column must be known. The following example shows how you can get the information:
<!DOCTYPE html>
<html>
<head>
<script>
function getcellvalue()
{
var cellvalue = document.getElementById("testtable").rows[1].cells[1];
alert(cellvalue.innerHTML);
}
</script>
</head>
<body>
<table style="border:4px solid red" id="testtable">
<tr>
<td>Red</td>
<td>Blue</td>
</tr>
<tr>
<td>Green</td>
<td>Yellow</td>
</tr>
</table>
<p>
<input type="button" onclick="getcellvalue()" value="Show the color">
</p>
</body>
</html>
To get a certain value out of the cell of a table you can use
document.getElementById("tablename").rows[X].cells[Y]. The table must have an ID and the row and column must be known. The following example shows how you can get the information:
<!DOCTYPE html>
<html>
<head>
<script>
function getcellvalue()
{
var cellvalue = document.getElementById("testtable").rows[1].cells[1];
alert(cellvalue.innerHTML);
}
</script>
</head>
<body>
<table style="border:4px solid red" id="testtable">
<tr>
<td>Red</td>
<td>Blue</td>
</tr>
<tr>
<td>Green</td>
<td>Yellow</td>
</tr>
</table>
<p>
<input type="button" onclick="getcellvalue()" value="Show the color">
</p>
</body>
</html>
Get mouse coordinates in the page or in an element
Using clientX and clientY we can get the mouse coordinates. The next program shows how to get the coordinates to call a function when the mouse moves (onmousemove). The function places the coordinates in an <h2> tag.
<!DOCTYPE html>
<html>
<body onmousemove = "getcoord(event)">
<h2 id="textfield"></h2>
<p>Above are the X and Y coordinates of the mouse location</p>
<br><br><br><br><br><br><br><br><br><br><br><br>
<script>
function getcoord(event) {
var x_pos = event.x;
var y_pos = event.y;
var xypos = "X position= " + x_pos + ", Y position = " + y_pos;
document.getElementById("textfield").innerHTML = xypos;
}
</script>
</body>
</html>
By putting onmousemove = "getcoord(event)" in the <p> tag for example the coordinates will only change (on the screen) when you move the mouse over the text of the <p> tag.
The <br> 's in the page are only there to give the page some body.
Using clientX and clientY we can get the mouse coordinates. The next program shows how to get the coordinates to call a function when the mouse moves (onmousemove). The function places the coordinates in an <h2> tag.
<!DOCTYPE html>
<html>
<body onmousemove = "getcoord(event)">
<h2 id="textfield"></h2>
<p>Above are the X and Y coordinates of the mouse location</p>
<br><br><br><br><br><br><br><br><br><br><br><br>
<script>
function getcoord(event) {
var x_pos = event.x;
var y_pos = event.y;
var xypos = "X position= " + x_pos + ", Y position = " + y_pos;
document.getElementById("textfield").innerHTML = xypos;
}
</script>
</body>
</html>
By putting onmousemove = "getcoord(event)" in the <p> tag for example the coordinates will only change (on the screen) when you move the mouse over the text of the <p> tag.
The <br> 's in the page are only there to give the page some body.
Get the screen resolution
If you need to know the screen resolution you can use the next commands that put the resolution in the variables width and height.
width = window.screen.availWidth;
height = window.screen.availHeight;
If you need to know the screen resolution you can use the next commands that put the resolution in the variables width and height.
width = window.screen.availWidth;
height = window.screen.availHeight;
Get the dimensions of an img that is not yet loaded
The next snippet shows how to get the dimensions of an image before you put it on the webpage.
function getdimensions(url, callback) {
var img = new Image();
img.src = url;
img.onload = function() { callback(this.width, this.height); }
}
getdimensions(
"https://i.postimg.cc/KzfwQZKS/butred2.png",
function(width, height) { alert(width + 'px ' + height + 'px') }
);
The next snippet shows how to get the dimensions of an image before you put it on the webpage.
function getdimensions(url, callback) {
var img = new Image();
img.src = url;
img.onload = function() { callback(this.width, this.height); }
}
getdimensions(
"https://i.postimg.cc/KzfwQZKS/butred2.png",
function(width, height) { alert(width + 'px ' + height + 'px') }
);
Get the window resolution
The previous tip showed how to get the screen resolution. This is the resolution of the total screen. You might want to know what the resolution is of the window you are working in. An example is when you want to put an element on a certain X-Y co-ordinate on the screen. The next snippet shows how to do that.
x = window.innerWidth
y = window.innerHeight
alert("Width : " + x + " Height : " + y);
The previous tip showed how to get the screen resolution. This is the resolution of the total screen. You might want to know what the resolution is of the window you are working in. An example is when you want to put an element on a certain X-Y co-ordinate on the screen. The next snippet shows how to do that.
x = window.innerWidth
y = window.innerHeight
alert("Width : " + x + " Height : " + y);
Get or loose hint in imput field
The next code shows how a hint is set into the input field when the user clicks next to it. When the user clicks into the field the hint is erased.
<!DOCTYPE html>
<html>
<body>
<p>Programming language:</p>
<input id="proglang" value="What language ">
</div>
<script>
function gotfocus()
{
if (this.value == this.defaultValue)
this.value = '';
}
function nofocus(event)
{
if (this.value == '')
this.value = this.defaultValue;
}
var event = document.getElementById('proglang');
event.onfocus = gotfocus;
event.onblur = nofocus;
</script>
</body>
</html>
The next code shows how a hint is set into the input field when the user clicks next to it. When the user clicks into the field the hint is erased.
<!DOCTYPE html>
<html>
<body>
<p>Programming language:</p>
<input id="proglang" value="What language ">
</div>
<script>
function gotfocus()
{
if (this.value == this.defaultValue)
this.value = '';
}
function nofocus(event)
{
if (this.value == '')
this.value = this.defaultValue;
}
var event = document.getElementById('proglang');
event.onfocus = gotfocus;
event.onblur = nofocus;
</script>
</body>
</html>
Hide an element when clicking on the webpage
To hide an element on a page when clicking on that page you can use element.style.display = 'none' You need to exchange element for the name of the part you want to hide. You can use this to hide any element you want like <div>, <a>, <p>, <h1> or any other element. The next example shows how to hide a div.
<!DOCTYPE html>
<html>
<body>
<script>
window.onload = function(){
var divvanish = document.getElementById('vanish');
document.onclick = function(e){
if(e.target.id !== 'vanish'){
vanish.style.display = 'none';
}
};
};
</script>
<div id="vanish">Click on the page and the text disappears.</div>
</body>
</html>
To hide an element on a page when clicking on that page you can use element.style.display = 'none' You need to exchange element for the name of the part you want to hide. You can use this to hide any element you want like <div>, <a>, <p>, <h1> or any other element. The next example shows how to hide a div.
<!DOCTYPE html>
<html>
<body>
<script>
window.onload = function(){
var divvanish = document.getElementById('vanish');
document.onclick = function(e){
if(e.target.id !== 'vanish'){
vanish.style.display = 'none';
}
};
};
</script>
<div id="vanish">Click on the page and the text disappears.</div>
</body>
</html>
Hide an element by clicking on a button
The next example shows how to hide an element from the webpage when clicking a button. The element is chosen by it's ID
<!DOCTYPE html>
<html>
<body>
<h2>Let an element disappear</h2>
<p id="demo">This will disappear.</p>
<button type="button" onclick="gone()">Click Me!</button>
</body>
<script>
function gone()
{
document.getElementById('demo').style.display='none';
}
</script>
</html>
The next example shows how to hide an element from the webpage when clicking a button. The element is chosen by it's ID
<!DOCTYPE html>
<html>
<body>
<h2>Let an element disappear</h2>
<p id="demo">This will disappear.</p>
<button type="button" onclick="gone()">Click Me!</button>
</body>
<script>
function gone()
{
document.getElementById('demo').style.display='none';
}
</script>
</html>
Hide multiple elements on a page
We can hide an element on a webpage with element.style.display = 'none'. By giving multiple elements the same class name we can hide several elements at the same time.
<html>
<body>
<div class= "remove">Element 1</div>
<div class= "remove">Element 2</div>
<br>
<button onclick="hideclass()">Hide elements</button>
<script>
function hideclass()
{
var removeclasses = document.querySelectorAll('.remove');
var i = 0;
var l = removeclasses.length;
for (i; i < l; i++)
{
removeclasses[i].style.display = 'none';
}
}
</script>
</body>
</html>
To show all the elements again use removeclasses[i].style.display = 'block';
We can hide an element on a webpage with element.style.display = 'none'. By giving multiple elements the same class name we can hide several elements at the same time.
<html>
<body>
<div class= "remove">Element 1</div>
<div class= "remove">Element 2</div>
<br>
<button onclick="hideclass()">Hide elements</button>
<script>
function hideclass()
{
var removeclasses = document.querySelectorAll('.remove');
var i = 0;
var l = removeclasses.length;
for (i; i < l; i++)
{
removeclasses[i].style.display = 'none';
}
}
</script>
</body>
</html>
To show all the elements again use removeclasses[i].style.display = 'block';
How long is user on the webpage
If you want to measure how much time a user is spending on your webpage you can use the followinh example.
<!DOCTYPE html>
<html>
<body>
<p id="timeonsite"></p>
<script>
var now;
var time;
var difference;
var seconds;
var minutes
window.onload = showit;
now = new Date().getTime();
function showit()
{
time = new Date().getTime();
difference = ( (time - now) / 1000) | 0;
minutes = ( (difference / 60) | 0);
difference = difference %60;
seconds ="" + ( (difference > 9) ? difference : "0" + difference);
document.getElementById("timeonsite").innerHTML = minutes + ":" + seconds;
setTimeout("showit()",1000);
}
</script>
</body>
</html>
If you want to measure how much time a user is spending on your webpage you can use the followinh example.
<!DOCTYPE html>
<html>
<body>
<p id="timeonsite"></p>
<script>
var now;
var time;
var difference;
var seconds;
var minutes
window.onload = showit;
now = new Date().getTime();
function showit()
{
time = new Date().getTime();
difference = ( (time - now) / 1000) | 0;
minutes = ( (difference / 60) | 0);
difference = difference %60;
seconds ="" + ( (difference > 9) ? difference : "0" + difference);
document.getElementById("timeonsite").innerHTML = minutes + ":" + seconds;
setTimeout("showit()",1000);
}
</script>
</body>
</html>
How many elements in a dropdown list
Using document.getElementById("dropdown").length; we can get the number of elements in the dropdown list with the ID "dropdown".
<!DOCTYPE html>
<html>
<body>
<select id="dropdown">
<option>C++</option>
<option>Javascript</option>
<option>Python</option>
</select>
<script>
var number = document.getElementById("dropdown").length;
document.write("Elements in dropdown list: "+ number);
</script>
</body>
</html>
With the tip Remove an option from the drop-down menu we can remove elements from the drop-down list.
Using document.getElementById("dropdown").length; we can get the number of elements in the dropdown list with the ID "dropdown".
<!DOCTYPE html>
<html>
<body>
<select id="dropdown">
<option>C++</option>
<option>Javascript</option>
<option>Python</option>
</select>
<script>
var number = document.getElementById("dropdown").length;
document.write("Elements in dropdown list: "+ number);
</script>
</body>
</html>
With the tip Remove an option from the drop-down menu we can remove elements from the drop-down list.
How many images on this page
Using document.images.length you can determine how many images are present on a page. You can use that as follows.
<!DOCTYPE html>
<html>
<body>
<img src="https://cdn.pixabay.com/photo/2021/08/13/12/51/sea-6543041_960_720.jpg">
<img src="https://cdn.pixabay.com/photo/2021/07/23/17/07/volcano-6487743_960_720.jpg">
<img src="https://cdn.pixabay.com/photo/2021/08/12/10/38/mountains-6540497_960_720.jpg">
<img src="https://javascript-tips.weebly.com/uploads/3/2/1/8/3218777/published/balkjs.jpg?1624135861">
<script>
var number = document.images.length;
document.write("<br>Number of images on this page: "+number);
</script>
</body>
</html>
Using document.images.length you can determine how many images are present on a page. You can use that as follows.
<!DOCTYPE html>
<html>
<body>
<img src="https://cdn.pixabay.com/photo/2021/08/13/12/51/sea-6543041_960_720.jpg">
<img src="https://cdn.pixabay.com/photo/2021/07/23/17/07/volcano-6487743_960_720.jpg">
<img src="https://cdn.pixabay.com/photo/2021/08/12/10/38/mountains-6540497_960_720.jpg">
<img src="https://javascript-tips.weebly.com/uploads/3/2/1/8/3218777/published/balkjs.jpg?1624135861">
<script>
var number = document.images.length;
document.write("<br>Number of images on this page: "+number);
</script>
</body>
</html>
How many rows in a table
If we need to know how many rows a table has we can check that with tablename.rows.length The next program shows how to get that number.
<!DOCTYPE html>
<html lang="en">
<body>
<table id="testtable" border="5">
<thead>
<tr>
<th>Month</th>
<th>Temp</th>
</tr>
</thead>
<tbody>
<tr><td>Jan</td><td>17</td></tr>
<tr><td>Feb</td><td>16</td></tr>
<tr><td>Mar</td><td>18</td></tr>
<tr><td>Apr</td><td>20</td></tr>
</tbody>
</table>
<script>
var datatable = document.getElementById("testtable");
var numberrows = datatable.rows.length;
alert("The number of rows = "+numberrows);
</script>
</body>
</html>
Be aware that the table header is also counted as a row. So in this case the alert will show 5 rows while there are actually 4 rows with data.
If we need to know how many rows a table has we can check that with tablename.rows.length The next program shows how to get that number.
<!DOCTYPE html>
<html lang="en">
<body>
<table id="testtable" border="5">
<thead>
<tr>
<th>Month</th>
<th>Temp</th>
</tr>
</thead>
<tbody>
<tr><td>Jan</td><td>17</td></tr>
<tr><td>Feb</td><td>16</td></tr>
<tr><td>Mar</td><td>18</td></tr>
<tr><td>Apr</td><td>20</td></tr>
</tbody>
</table>
<script>
var datatable = document.getElementById("testtable");
var numberrows = datatable.rows.length;
alert("The number of rows = "+numberrows);
</script>
</body>
</html>
Be aware that the table header is also counted as a row. So in this case the alert will show 5 rows while there are actually 4 rows with data.
ID can only be used on 1 element on a page
If you give several elemnts on a page the same ID, only the first element will be associated with that element.
<!DOCTYPE html>
<html>
<body>
<h1 id="id01">Only here workst the ID</h1>
<p id="id01">This text has the same ID but does not react on it/p>
<button id="id01">Just try it</button>
<script>
document.getElementById("id01").addEventListener("click", function() {
alert("Here ID01 works");
});
</script>
</body>
</html>
You can click any element on the page but only if you click the first line the function will be activated.
If you need multiple elements to react use class like in the tip : Change the color of several elements on a webpagere to edit.
If you give several elemnts on a page the same ID, only the first element will be associated with that element.
<!DOCTYPE html>
<html>
<body>
<h1 id="id01">Only here workst the ID</h1>
<p id="id01">This text has the same ID but does not react on it/p>
<button id="id01">Just try it</button>
<script>
document.getElementById("id01").addEventListener("click", function() {
alert("Here ID01 works");
});
</script>
</body>
</html>
You can click any element on the page but only if you click the first line the function will be activated.
If you need multiple elements to react use class like in the tip : Change the color of several elements on a webpagere to edit.
innerHTML not always shows all information
Using innerHTML we can retrieve text from a page. That can also be done with innerText and textContent. But be aware that you will not always get all information. Take a look at the following example:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
</head>
<body>
<p id="test">This text contains a tag <CENTER>some test text</CENTER></p>
<script>
alert(document.getElementById("test").innerHTML);
alert(document.getElementById("test").innerText);
alert(document.getElementById("test").textContent)
</script>
</body>
</html>
In all the three alerts you will be shown: "This text contains a tag" and the rest of the text is lost.
However if the tag is an <a>, <b>, <i> or <span> you will get the right information.
Using innerHTML we can retrieve text from a page. That can also be done with innerText and textContent. But be aware that you will not always get all information. Take a look at the following example:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
</head>
<body>
<p id="test">This text contains a tag <CENTER>some test text</CENTER></p>
<script>
alert(document.getElementById("test").innerHTML);
alert(document.getElementById("test").innerText);
alert(document.getElementById("test").textContent)
</script>
</body>
</html>
In all the three alerts you will be shown: "This text contains a tag" and the rest of the text is lost.
However if the tag is an <a>, <b>, <i> or <span> you will get the right information.
Input does not use innerHTML
Well the heading of this tip shows what it is. If you need to get information out of an ,input. field you can not use innerHTML. Use value in stead.
document.getElementById("test").value
Well the heading of this tip shows what it is. If you need to get information out of an ,input. field you can not use innerHTML. Use value in stead.
document.getElementById("test").value
Input field with increase and decrease
In an inputfield you can put a certain value. Here is an input field with arrows that increases and decreases the value and performs a calculation on that.
<!DOCTYPE html>
<html>
<body>
<h1>Celsius to Fahrenheit</h1>
<h2>Enter the temperature in Celsius</h2>
Temperature
<input
id="enter"
type="number"
size="5"
placeholder="0"
oninput="celtofar(this.value)"
onchange="celtofar(this.value)"/>
<br>
<br>
In Fahrenheit is dat: <span class="fahrenheit"></span>
<script>
function celtofar(valuecelsius) {
document.querySelector(".fahrenheit").innerHTML = ((valuecelsius * 1.8)+32).toFixed(2);
}
</script>
</body>
</html>
In an inputfield you can put a certain value. Here is an input field with arrows that increases and decreases the value and performs a calculation on that.
<!DOCTYPE html>
<html>
<body>
<h1>Celsius to Fahrenheit</h1>
<h2>Enter the temperature in Celsius</h2>
Temperature
<input
id="enter"
type="number"
size="5"
placeholder="0"
oninput="celtofar(this.value)"
onchange="celtofar(this.value)"/>
<br>
<br>
In Fahrenheit is dat: <span class="fahrenheit"></span>
<script>
function celtofar(valuecelsius) {
document.querySelector(".fahrenheit").innerHTML = ((valuecelsius * 1.8)+32).toFixed(2);
}
</script>
</body>
</html>
Insert a new element before or after another element
It is easy to put a new element on a webpage. We can indicate where we want to put the new element by putting it infront of an element with a known ID. The next snippet shows how to put a new <p> element before another <p> element with the ID "last"
<!DOCTYPE html>
<html>
<body>
<p>The first element</p>
<p id="last">The last element</p>
<script>
function inbetween(where, what)
{
where.insertAdjacentHTML('beforebegin', what);
}
var where = (document.getElementById("last"));
var what = "<p> A new element </p>";
inbetween(where,what);
</script>
</body>
</html>
By replacing where.insertAdjacentHTML('beforebegin', what); with where.insertAdjacentHTML('afterend', what); the new element is placed behind the <p> element.
It is easy to put a new element on a webpage. We can indicate where we want to put the new element by putting it infront of an element with a known ID. The next snippet shows how to put a new <p> element before another <p> element with the ID "last"
<!DOCTYPE html>
<html>
<body>
<p>The first element</p>
<p id="last">The last element</p>
<script>
function inbetween(where, what)
{
where.insertAdjacentHTML('beforebegin', what);
}
var where = (document.getElementById("last"));
var what = "<p> A new element </p>";
inbetween(where,what);
</script>
</body>
</html>
By replacing where.insertAdjacentHTML('beforebegin', what); with where.insertAdjacentHTML('afterend', what); the new element is placed behind the <p> element.
Insert a text before another element
Hers is a sample on how you can insert a line of text (or another element) behore an element of which the ID is known
This is the webpage:
<h1>
Headline of the page
</h1>
<div id="test">
This is a line of text
</div>
The next code inserts the text "This comes first" before the div on the page.
var element = document.getElementById('test');
var inserttext = document.createElement('p');
inserttext.innerHTML = 'This comes first';
element.parentNode.insertBefore(inserttext, element);
Hers is a sample on how you can insert a line of text (or another element) behore an element of which the ID is known
This is the webpage:
<h1>
Headline of the page
</h1>
<div id="test">
This is a line of text
</div>
The next code inserts the text "This comes first" before the div on the page.
var element = document.getElementById('test');
var inserttext = document.createElement('p');
inserttext.innerHTML = 'This comes first';
element.parentNode.insertBefore(inserttext, element);
Insert a row into a table
It may happen that you need to add a row with data into an existing table. The next example has a table with the following values:
One Two
Three Four
Seven Eight
Suppose we want to add the values Five and Six at the right location. Using var variable = document.getElementById(x).insertRow(2); we declare a variable that inserts the second row in the table.
var leftcel = newrow.insertCell(0);
var rightcel = newrow.insertCell(1);
leftcel.innerHTML = "Five";
rightcel.innerHTML = "Six";
These lines insert the cells into the row and put the right values in. The next example shows how the row with cells is inserted aftre pressing a button.
<!DOCTYPE html>
<html>
<head>
<script>
function addnewrow(x) {
var newrow = document.getElementById(x).insertRow(2);
var leftcel = newrow.insertCell(0);
var rightcel = newrow.insertCell(1);
leftcel.innerHTML = "Five";
rightcel.innerHTML = "Six";
}
</script>
</head>
<body>
<table style="border:4px solid red" id="testtable">
<tr>
<td>One</td>
<td>Two</td>
</tr>
<tr>
<td>Three</td>
<td>Four</td>
</tr>
<tr>
<td>Seven</td>
<td>Eight</td>
</tr>
</table>
<p>
<input type="button" onclick="addnewrow('testtable')" value="Add another row">
</p>
</body>
</html>
It may happen that you need to add a row with data into an existing table. The next example has a table with the following values:
One Two
Three Four
Seven Eight
Suppose we want to add the values Five and Six at the right location. Using var variable = document.getElementById(x).insertRow(2); we declare a variable that inserts the second row in the table.
var leftcel = newrow.insertCell(0);
var rightcel = newrow.insertCell(1);
leftcel.innerHTML = "Five";
rightcel.innerHTML = "Six";
These lines insert the cells into the row and put the right values in. The next example shows how the row with cells is inserted aftre pressing a button.
<!DOCTYPE html>
<html>
<head>
<script>
function addnewrow(x) {
var newrow = document.getElementById(x).insertRow(2);
var leftcel = newrow.insertCell(0);
var rightcel = newrow.insertCell(1);
leftcel.innerHTML = "Five";
rightcel.innerHTML = "Six";
}
</script>
</head>
<body>
<table style="border:4px solid red" id="testtable">
<tr>
<td>One</td>
<td>Two</td>
</tr>
<tr>
<td>Three</td>
<td>Four</td>
</tr>
<tr>
<td>Seven</td>
<td>Eight</td>
</tr>
</table>
<p>
<input type="button" onclick="addnewrow('testtable')" value="Add another row">
</p>
</body>
</html>
Make a table from a fetched JSON file
The next program shows how to fetch a JSON file from the internet and place its data in a table. In this example the JSON file is fetched from https://api.openbrewerydb.org/breweries and contains info about USA breweries. Here the name and the city of the brewerey are placed in a table.
<!DOCTYPE html>
<html>
<body>
<h1>Table from Json data</h1>
<div class="sample">USA breweries and cities</div>
<table border="3" class="brewtable"></table>
<button class="Btn">Click to fetch</button>
<h4>
Click to get the brewery names and cities
</h4>
<script>
let sampleEle = document.querySelector(".brewtable");
document.querySelector(".Btn").addEventListener("click", () => {
fetch("https://api.openbrewerydb.org/breweries")
.then((response) => response.json())
.then((result) => {
result.forEach((element) => {
sampleEle.innerHTML += "<tr>" + "<th>"+element.name +"</th>"+ "<th>" + element.city + "</th></tr>";
});
});
});
</script>
</body>
</html>
The next program shows how to fetch a JSON file from the internet and place its data in a table. In this example the JSON file is fetched from https://api.openbrewerydb.org/breweries and contains info about USA breweries. Here the name and the city of the brewerey are placed in a table.
<!DOCTYPE html>
<html>
<body>
<h1>Table from Json data</h1>
<div class="sample">USA breweries and cities</div>
<table border="3" class="brewtable"></table>
<button class="Btn">Click to fetch</button>
<h4>
Click to get the brewery names and cities
</h4>
<script>
let sampleEle = document.querySelector(".brewtable");
document.querySelector(".Btn").addEventListener("click", () => {
fetch("https://api.openbrewerydb.org/breweries")
.then((response) => response.json())
.then((result) => {
result.forEach((element) => {
sampleEle.innerHTML += "<tr>" + "<th>"+element.name +"</th>"+ "<th>" + element.city + "</th></tr>";
});
});
});
</script>
</body>
</html>
Make page element appear and disappear
The command style.display = "none" makes an elemet on your webpage disappaer. To have it re-appear you can use style.display = "block"
The next example make a text in a ,div. disappear when you push the button.
<html>
<body>
<div id="top" style="display:in-line;">This is a test
</div>
<button onclick="toggle()">Click and text disappears</button>
<script>
function toggle()
{
document.getElementById("top").style.display = "none";
}
</script>
</body>
</html>
The command style.display = "none" makes an elemet on your webpage disappaer. To have it re-appear you can use style.display = "block"
The next example make a text in a ,div. disappear when you push the button.
<html>
<body>
<div id="top" style="display:in-line;">This is a test
</div>
<button onclick="toggle()">Click and text disappears</button>
<script>
function toggle()
{
document.getElementById("top").style.display = "none";
}
</script>
</body>
</html>
Make page element appear and disappear 2
The previous tip demonstrated how to have elements on a page appear and disappaer. The disadvantage was that the element was removed from the page and all remaining information on the page scrolled upwards. To avoid this you can use element.style.visibility = "hidden"; This does not remove the element from the page but only makes it invisible. element.style.visibility = "visible"; makes the elemt visible again on the same location where it was so the rest of the page does not alter position. The next snippet shows how to use this.
<html>
<body>
<p id = "examtext">Example text</p>
<button type = "button" onclick = "textgone()">Hide</button>
<button type = "button" onclick = "textshow()">Show</button>
<script>
function textgone() {
document.getElementById("examtext").style.visibility = "hidden";
}
function textshow() {
document.getElementById("examtext").style.visibility = "visible";
}
</script>
</body>
</html>
Move the caption of a table
The caption of a table is most of the time at the top of the table. Using element.style.captionSide = "bottom" we can change its position to the bottom.
<html>
<body>
<table id = "languages" >
<caption id = "title">2021 Courses</caption>
<tr>
<th>Programming languages</th>
</tr>
<tr>
<td>C++</td>
</tr>
<tr>
<td>Javascript</td>
</tr>
<tr>
<td>Python</td>
</tr>
</table>
<br>
<button onclick = "changepos()">Click to move the caption</button>
<script>
function changepos() {
document.getElementById("title").style.captionSide = "bottom";
}
</script>
</body>
</html>
Move the mouse over an element to jump to another webpage
This is no Javascript but I would not keep it from you anyway.
Use this to jump to another webpage (in this case my weblog) when you hover the mouse over an element.
<div target=main onmouseover="window.open
('http://lucstechblog.blogspot.com/');" >http://lucstechblog.blogspot.com/</div>
This will work with all elements on a webpage like <p>, <a>, <h1> etc.
This is no Javascript but I would not keep it from you anyway.
Use this to jump to another webpage (in this case my weblog) when you hover the mouse over an element.
<div target=main onmouseover="window.open
('http://lucstechblog.blogspot.com/');" >http://lucstechblog.blogspot.com/</div>
This will work with all elements on a webpage like <p>, <a>, <h1> etc.
Move the mouse over an element to trigger a function
Using onmouseover you can test wether the mouse is located upon an element on the page. Using onmouseout tests if the mouse is no longer on that element. The next example shows how to use these commands to trigger a function to change the color of an element on the page and change it back.
html>
<head>
</head>
<body>
<p onmouseover="over()" onmouseout="out()">Move the mouse over this text to change it's color.</p>
<div onmouseover="over()" onmouseout="out()">
<h2>Try this text to</h2>
</div>
<script>
function over() {
event.target.style.color = "red";
}
function out() {
event.target.style.color = "black";
}
</script>
</body>
</html>
Using onmouseover you can test wether the mouse is located upon an element on the page. Using onmouseout tests if the mouse is no longer on that element. The next example shows how to use these commands to trigger a function to change the color of an element on the page and change it back.
html>
<head>
</head>
<body>
<p onmouseover="over()" onmouseout="out()">Move the mouse over this text to change it's color.</p>
<div onmouseover="over()" onmouseout="out()">
<h2>Try this text to</h2>
</div>
<script>
function over() {
event.target.style.color = "red";
}
function out() {
event.target.style.color = "black";
}
</script>
</body>
</html>
Open a new webpage
Using window.location.href = "URL" we can force Javascript to open a different webpage. The next example shows how to do that after pressing a button.
<!DOCTYPE html>
<html>
<h1>Open a different webpage</h1>
<button onclick="doit()">Go to my page</button>
<script>
function doit()
{
window.location.href ="http://lucstechblog.blogspot.com/";
}
</script>
</body>
</html>
Using window.location.href = "URL" we can force Javascript to open a different webpage. The next example shows how to do that after pressing a button.
<!DOCTYPE html>
<html>
<h1>Open a different webpage</h1>
<button onclick="doit()">Go to my page</button>
<script>
function doit()
{
window.location.href ="http://lucstechblog.blogspot.com/";
}
</script>
</body>
</html>
Open a new webpage 2
If you need to open another webpage in a new tab you can use the following command:
window.open('http://lucstechblog.blogspot.com/', '_blank');
If you need to open another webpage in a new tab you can use the following command:
window.open('http://lucstechblog.blogspot.com/', '_blank');
Prevent space from scrolling
Normally when you press the space bar somewhere in a webpage the browser will sctoll one page down. That is the default function of the spacebar. If you want to prevent this happening you can use preventDefault() like this:
window.addEventListener('keydown', function(e)
{
if(e.keyCode == 32 && e.target == document.body)
{
e.preventDefault();
}
});
Normally when you press the space bar somewhere in a webpage the browser will sctoll one page down. That is the default function of the spacebar. If you want to prevent this happening you can use preventDefault() like this:
window.addEventListener('keydown', function(e)
{
if(e.keyCode == 32 && e.target == document.body)
{
e.preventDefault();
}
});
Password protected page
The next example shows how you can build a very simple protection for your webpages. A prompt asks for a password and compares that with a predefined password. If it matchess the if() command will redirect the page to another webpage. If the match is false in this example you will be directed to another webpage. This is a very simple protection that anybody with a bit of knowledge of Javascript can break. You only have to open the page source with your browser and look at the code. However it will stop most of the uesers.
<!DOCTYPE html>
<html>
<body>
ssss
<script>
var password;
var pass1 = "luc";
password=prompt("Voer je password in:","");
if (password==pass1) {
window.location= "http://lucstechblog.blogspot.com/";
} else {
window.location= "https://javascript-tips.weebly.com/";
}
</script>
</body>
</html>
The next example shows how you can build a very simple protection for your webpages. A prompt asks for a password and compares that with a predefined password. If it matchess the if() command will redirect the page to another webpage. If the match is false in this example you will be directed to another webpage. This is a very simple protection that anybody with a bit of knowledge of Javascript can break. You only have to open the page source with your browser and look at the code. However it will stop most of the uesers.
<!DOCTYPE html>
<html>
<body>
ssss
<script>
var password;
var pass1 = "luc";
password=prompt("Voer je password in:","");
if (password==pass1) {
window.location= "http://lucstechblog.blogspot.com/";
} else {
window.location= "https://javascript-tips.weebly.com/";
}
</script>
</body>
</html>
Printing the current page
The drop down menu of your webbrowser has a print function. However sometimes you want to make things more convenient for the end-user by putting a print-button on the web-page. This can be done with inline Javascript easily:
<input type="button" value="Print This Page" onClick="window.print()" />
Put the above line in the body of your HTML code.
Yoy can also put the button on the webpage and have it call a function when pressed. This can be achieved as follows:
<!DOCTYPE html>
<html>
<title>Print current page</title>
<head>
</head>
<body>
<button onclick="sayHello()">Click me</button>
<script>
function sayHello()
{
window.print();
}
</script>
</body>
</html>
The drop down menu of your webbrowser has a print function. However sometimes you want to make things more convenient for the end-user by putting a print-button on the web-page. This can be done with inline Javascript easily:
<input type="button" value="Print This Page" onClick="window.print()" />
Put the above line in the body of your HTML code.
Yoy can also put the button on the webpage and have it call a function when pressed. This can be achieved as follows:
<!DOCTYPE html>
<html>
<title>Print current page</title>
<head>
</head>
<body>
<button onclick="sayHello()">Click me</button>
<script>
function sayHello()
{
window.print();
}
</script>
</body>
</html>
Put a comma seperated text as a list on screen
The next program shows how we can put a list on a webpage that is made from a text with comma seperated words.
<!DOCTYPE html>
<html>
<body>
<div id="listspace"> </div>
<script>
var text = "C++ , Javascript, Lua, Python"
var textarray = text.trim().split(',')
var nieuwlist = '<ul>'
for (var i=0; i<textarray.length; i++)
{
nieuwlist += '<li>' + textarray[i] + '</li>';
}
nieuwlist += '</ul>';
document.getElementById("listspace").innerHTML = nieuwlist;
</script>
</body>
</html>
The next program shows how we can put a list on a webpage that is made from a text with comma seperated words.
<!DOCTYPE html>
<html>
<body>
<div id="listspace"> </div>
<script>
var text = "C++ , Javascript, Lua, Python"
var textarray = text.trim().split(',')
var nieuwlist = '<ul>'
for (var i=0; i<textarray.length; i++)
{
nieuwlist += '<li>' + textarray[i] + '</li>';
}
nieuwlist += '</ul>';
document.getElementById("listspace").innerHTML = nieuwlist;
</script>
</body>
</html>
Put an element at an X-Y co-ordinate in the window
Using the CSS style you can place an element at an X and Y coordinate in a window. First determine which element by selecting it by it's ID and then place it at the desired position with style.left and style.top. The next snippet shows how to use this.
<!DOCTYPE html>
<html>
<div id="divtest">This is a test</div>
<script>
var element = document.getElementById('divtest');
element.style.position = "absolute";
element.style.left = 100 + 'px';
element.style.top = 100 +'px';
</script>
</body>
</html>
The element is here placed at the co-ordinates style.left 100 which is the X value and style.top 100 which is the Y value. Make sure to add "px" to the figure as the position is determined in pixels.
Using the CSS style you can place an element at an X and Y coordinate in a window. First determine which element by selecting it by it's ID and then place it at the desired position with style.left and style.top. The next snippet shows how to use this.
<!DOCTYPE html>
<html>
<div id="divtest">This is a test</div>
<script>
var element = document.getElementById('divtest');
element.style.position = "absolute";
element.style.left = 100 + 'px';
element.style.top = 100 +'px';
</script>
</body>
</html>
The element is here placed at the co-ordinates style.left 100 which is the X value and style.top 100 which is the Y value. Make sure to add "px" to the figure as the position is determined in pixels.
Refresh the page
You can refresh the current web-page with the next command:
window.location.reload();
You can refresh the current web-page with the next command:
window.location.reload();
Remove an option from the drop-down menu
A drop down menu offers the user several options. Using the next example you can remove options after a choice has been made.
<!DOCTYPE html>
<html>
<body>
<select id = "menu" onChange = "remove()">
<option>Make your choice</option>
<option>C++</option>
<option>Javascript</option>
<option>Python</option>
</select>
<p>Make a choice and it will be removed</p>
<script>
function remove()
{
var x = document.getElementById("menu");
x.remove(x.selectedIndex);
}
</script>
</body>
</html>
remove an element from the webpage
When a text has been read or a function been executed it may be so that you want to remove that specific text or another element from the webpage. Using document.querySelector("#element") you can select the element and with elem.remove(); you can remove that element. The next example puts a text and a button on a webpage and when the button is clicked both are removed.
<!DOCTYPE html>
<html>
<body>
<p id="test">133 This text is going to be removed</p>
<button id="test2" onclick="removetext()">Click me</button>
<script>
function removetext()
{
var elem = document.querySelector("#test");
elem.remove();
var elem = document.querySelector("#test2");
elem.remove();
}
</script>
</body>
</html>
When a text has been read or a function been executed it may be so that you want to remove that specific text or another element from the webpage. Using document.querySelector("#element") you can select the element and with elem.remove(); you can remove that element. The next example puts a text and a button on a webpage and when the button is clicked both are removed.
<!DOCTYPE html>
<html>
<body>
<p id="test">133 This text is going to be removed</p>
<button id="test2" onclick="removetext()">Click me</button>
<script>
function removetext()
{
var elem = document.querySelector("#test");
elem.remove();
var elem = document.querySelector("#test2");
elem.remove();
}
</script>
</body>
</html>
remove an element from the webpage 2
In the previous tip you saw how to remove an item from a webpage by selecting it with document.querySelector(). The same can be done with document.getElementById() as thye next sample shows.
<html>
<body>
<p id="p1">Python</p>
<p id="p2">Javascript</p>
<script>
var first = document.getElementById("p1");
var second = document.getElementById("p2");
first.remove();
</script>
</body>
</html>
Two elements (with id's p1 and p2) are placed on the page and then the first element is removed.
In the previous tip you saw how to remove an item from a webpage by selecting it with document.querySelector(). The same can be done with document.getElementById() as thye next sample shows.
<html>
<body>
<p id="p1">Python</p>
<p id="p2">Javascript</p>
<script>
var first = document.getElementById("p1");
var second = document.getElementById("p2");
first.remove();
</script>
</body>
</html>
Two elements (with id's p1 and p2) are placed on the page and then the first element is removed.
Remove all elements with a certain class
Using document.querySelectorAll() we can select all elements with a certain class. They are put into an array and can then all be removed from a webpage.
<!DOCTYPE html>
<html>
<body>
<p class="test">This text is going to be removed</p>
<button class="test" onclick="verwijder()">Click me</button>
<script>
function verwijder()
{
var elem, i;
elem = document.querySelectorAll(".test");
for (i=0; i < elem.length; i++)
{
elem[i].remove();
}
}
</script>
</body>
</html>
As the text and the button have the same class they both will be removed.
Using document.querySelectorAll() we can select all elements with a certain class. They are put into an array and can then all be removed from a webpage.
<!DOCTYPE html>
<html>
<body>
<p class="test">This text is going to be removed</p>
<button class="test" onclick="verwijder()">Click me</button>
<script>
function verwijder()
{
var elem, i;
elem = document.querySelectorAll(".test");
for (i=0; i < elem.length; i++)
{
elem[i].remove();
}
}
</script>
</body>
</html>
As the text and the button have the same class they both will be removed.
Remove alements between two elements
On your webpage there are several elements. Some elements have an ID. If you need to remove elements that are situated bewteen elements with a known id you can use the next example.
<!DOCTYPE html>
<html>
<body>
<div id="1">START</div>
<p>Language 1: Basic</p>
<p>Language 2: C++</p>
<p>Language 3: Javascript</p>
<p>Language 4: Lua</p>
<p>Language 5: Python</p>
<div id=2>END</div>
<script>
const startingPoint = document.getElementById("1");
const endingPoint = document.getElementById("2");
while (startingPoint.nextElementSibling &&
startingPoint.nextElementSibling !== endingPoint) {
startingPoint.nextElementSibling.remove();
}
</script>
</body>
</html>
All the elements between <div id="1">START</div> and <div id=2>END</div> are removed from the page.
Repeatedly react on addEventListener()
To repeatedly react on Repeatedly react on addEventListener() the best option is to call a function each time.
<html>
<body>
<p id="texthere">0</p>
<button id="button1">Click to increase</button>
<script>
var counter = 0
function testfunc()
{
counter = counter +1;
document.getElementById("texthere").innerHTML=counter;
}
var butpress = document.querySelector("#button1");
butpress.addEventListener("click", testfunc);
</script>
</body>
</html>
Each time the addEventListener() is activated it calls the function testfunc().
To repeatedly react on Repeatedly react on addEventListener() the best option is to call a function each time.
<html>
<body>
<p id="texthere">0</p>
<button id="button1">Click to increase</button>
<script>
var counter = 0
function testfunc()
{
counter = counter +1;
document.getElementById("texthere").innerHTML=counter;
}
var butpress = document.querySelector("#button1");
butpress.addEventListener("click", testfunc);
</script>
</body>
</html>
Each time the addEventListener() is activated it calls the function testfunc().
Replace an image with another
If you want to replace an image on a webpage by another image you can do that as demonstrated in the following example.
<!DOCTYPE html>
<html>
<body>
<img id="image1" src="https://images.pexels.com/photos/1116440/pexels-photo-1116440.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" width="400" height="200">
<button onclick="replacepic()">Replace image</button>
<script>
function replacepic()
{
var imgReplace = document.getElementById("image1");
imgReplace.width = 400;
imgReplace.height = 150;
imgReplace.src = "https://images.pexels.com/photos/3889990/pexels-photo-3889990.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500";
}
</script>
</body>
</html>
If you want to replace an image on a webpage by another image you can do that as demonstrated in the following example.
<!DOCTYPE html>
<html>
<body>
<img id="image1" src="https://images.pexels.com/photos/1116440/pexels-photo-1116440.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" width="400" height="200">
<button onclick="replacepic()">Replace image</button>
<script>
function replacepic()
{
var imgReplace = document.getElementById("image1");
imgReplace.width = 400;
imgReplace.height = 150;
imgReplace.src = "https://images.pexels.com/photos/3889990/pexels-photo-3889990.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500";
}
</script>
</body>
</html>
Replace an image with another 2
In javascript there are often more as one way to achieve something. This tip shows an alternate method for the previous tip.
The previous tip assumes we know the ID of the picture. If we do not know that we can get the number of picturen on a page with the following command:
var numpic = document.images.length;
To alter the third picture and its size we can use the following commands:
document.images[2].width = 100; // new width
document.images[2].height = 100; // new height
document.images[2].src= "here comes the link to a different picture";
To iterate over the images ID's for finding a certain one you can use the following loop:
<script>
function replacepic()
{
var numpics = document.images.length;
for (var i=0; i<numpics;i++)
{
alert(document.images[i].id);
}
}
</script>
In javascript there are often more as one way to achieve something. This tip shows an alternate method for the previous tip.
The previous tip assumes we know the ID of the picture. If we do not know that we can get the number of picturen on a page with the following command:
var numpic = document.images.length;
To alter the third picture and its size we can use the following commands:
document.images[2].width = 100; // new width
document.images[2].height = 100; // new height
document.images[2].src= "here comes the link to a different picture";
To iterate over the images ID's for finding a certain one you can use the following loop:
<script>
function replacepic()
{
var numpics = document.images.length;
for (var i=0; i<numpics;i++)
{
alert(document.images[i].id);
}
}
</script>
Rotate an object on a webpage to draw attention
To draw attention to an object on a webpage you can rotate the element when the page is loaded or when a button is clicked etc. The next script shows how to rotate a text when the page is loaded.
<!DOCTYPE html>
<html>
<head>
<h1 id="turn" style= "color:red";>Round and round goes the text</h1>
<h2>The text above will turn the amount of degrees which you can set in the script</h2>
<script>
var turntext = document.getElementById("turn");
var turndegrees = 360;
var anglenow =100;
setInterval(function(){
if (anglenow < turndegrees) {
anglenow += 1;
turntext.style.transform = 'rotate('+anglenow+'deg)';
}
}, 1);
</script>
</body>
</html>
The text in the <h1> tag will start at 100 degrees (anglenow) and turn to 360 degrees (turndegrees). It starts tilted. Set the vaule of anglenow to 0 and it will start horizontal and turn all the way round. The setInterval() function ends with the number 1 which determines the speed of rotation. The higher the numebr the slower the rotation.
Rotate the complete webpage
It is possible yo rotate the complete webpage upside down. This is the command that achieves that:
document.getElementsByTagName('body')[0].style.transform = 'rotate(180deg)';
You can replace 180deg by any angle you want. The word "deg" must be included for this to work.
To paraphrase Google: OK Javascript do a barrel roll !!!!
It is possible yo rotate the complete webpage upside down. This is the command that achieves that:
document.getElementsByTagName('body')[0].style.transform = 'rotate(180deg)';
You can replace 180deg by any angle you want. The word "deg" must be included for this to work.
To paraphrase Google: OK Javascript do a barrel roll !!!!
Run a function when the window closes
The next functions runs just before the window closes. You can use that for example to save variables
before the user closes the window.
window.onbeforeunload = closefunc;
function closefunc(){
// do what you need to do
return null;
}
The next functions runs just before the window closes. You can use that for example to save variables
before the user closes the window.
window.onbeforeunload = closefunc;
function closefunc(){
// do what you need to do
return null;
}
Run two functions with one button click
Usually you will call a function when a button is clicked. But what if you want to run two functions when you click the button. You can achieve this to call a function that then calls two other functions. Here is how to achieve that.
<!DOCTYPE html>
<body>
<button onclick="tweefuncties()">Klik mij</button>
<script>
function tweefuncties(){
actie();
nogeen();
}
function actie(){
alert("Functie actie")
}
function nogeen(){
alert("Nog een functie")
}
</script>
</body>
</html>
Usually you will call a function when a button is clicked. But what if you want to run two functions when you click the button. You can achieve this to call a function that then calls two other functions. Here is how to achieve that.
<!DOCTYPE html>
<body>
<button onclick="tweefuncties()">Klik mij</button>
<script>
function tweefuncties(){
actie();
nogeen();
}
function actie(){
alert("Functie actie")
}
function nogeen(){
alert("Nog een functie")
}
</script>
</body>
</html>
Set or clear a radiobutton
Normally a user can check or clear a radiobutton by clicking it. You can however also do that with Javascript.
document.getElementById("ID").checked = false;
document.getElementById("ID").checked = true;
Normally a user can check or clear a radiobutton by clicking it. You can however also do that with Javascript.
document.getElementById("ID").checked = false;
document.getElementById("ID").checked = true;
Set the maximum length of an input field
If you do not want the user to input long texts you can restrict the length of the input field.
<input id="test">
Type something
</input>
document.getElementById('test').setAttribute('maxlength', 10);
If you do not want the user to input long texts you can restrict the length of the input field.
<input id="test">
Type something
</input>
document.getElementById('test').setAttribute('maxlength', 10);
Select any tekst on your screen and use it
The next example shows how you can select any text on your screen, push a button and use that text for other purposes. Selecting text can be done with: window.getSelection().toString()
<!DOCTYPE html>
<html>
<body>
<button id="newinlist" onclick = "gettext()">Select any text and click</button>
<ul>
<li>ESP32 Simplified</li>
<li>Raspberry Pi Pico Simplified</li>
</ul>
<div>This is a longer text with some trivial sentences in it</div>
</body>
<script>
function gettext()
{
var selectedtext = window.getSelection().toString();
alert(selectedtext);
}
</script>
</html>
The next example shows how you can select any text on your screen, push a button and use that text for other purposes. Selecting text can be done with: window.getSelection().toString()
<!DOCTYPE html>
<html>
<body>
<button id="newinlist" onclick = "gettext()">Select any text and click</button>
<ul>
<li>ESP32 Simplified</li>
<li>Raspberry Pi Pico Simplified</li>
</ul>
<div>This is a longer text with some trivial sentences in it</div>
</body>
<script>
function gettext()
{
var selectedtext = window.getSelection().toString();
alert(selectedtext);
}
</script>
</html>
Scroll to the top of a page
Sometimes a web-page offers at the bottom of the page a button that brings you direct to the top of the page. This can easily be done with window.scrollTo(0,0) The (0,0) are the start coordinates of any webpage. The next example shows an almost empty web-page with a button at the bottom. Press the button and a function is called that uses the window.scrollTo(0,0) command to immediately bring you back to the top of the page.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to scroll to the top</p>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<button onclick="totop()">To the top</button><br><br>
<script>
function totop()
{
window.scrollTo(0, 0);
}
</script>
</body>
</html>
Sometimes a web-page offers at the bottom of the page a button that brings you direct to the top of the page. This can easily be done with window.scrollTo(0,0) The (0,0) are the start coordinates of any webpage. The next example shows an almost empty web-page with a button at the bottom. Press the button and a function is called that uses the window.scrollTo(0,0) command to immediately bring you back to the top of the page.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to scroll to the top</p>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<button onclick="totop()">To the top</button><br><br>
<script>
function totop()
{
window.scrollTo(0, 0);
}
</script>
</body>
</html>
Scroll to the bottom of a page
The following command let's you jump to the bottom of the webpage:
window.scrollTo(0,document.body.scrollHeight);
The following command let's you jump to the bottom of the webpage:
window.scrollTo(0,document.body.scrollHeight);
Show a message if the drop-down menu selection has changed
With onchange we can test wether a user has altered a choice in a drop-down menu. We can use this to show a message but this can easily be altered to call a function.
<html>
<head>
</head>
<body>
<select onchange="alert('You changed your mind');">
<option>choose your favorite language</option>
<option>C++</option>
<option>Javascript</option>
<option>Python</option>
</select>
<p>Choose an option to test.</p>
</body>
</html>
With onchange we can test wether a user has altered a choice in a drop-down menu. We can use this to show a message but this can easily be altered to call a function.
<html>
<head>
</head>
<body>
<select onchange="alert('You changed your mind');">
<option>choose your favorite language</option>
<option>C++</option>
<option>Javascript</option>
<option>Python</option>
</select>
<p>Choose an option to test.</p>
</body>
</html>
Show one or multiple alerts when a page is opened
There are occasions when you want to show an alert after the HTML page is opened. You can use this for a notification or to remind the user that he has to do something. For certainty you can show an alert some time later.
Using the setTimeout() function you can show an alert after a certain time. Put the following lines into your script and wait for the alerts:
setTimeout(function(){alert("test")}, 8000)
setTimeout(function(){alert("test number two")}, 3000)
Despite the fact that the order is different "test number two" will be shown first (after 3 seconds) and 5 seconds later the second alert will appear.
Show or hide an element on the webpage
Maybe you want to show or hide an element on a webpage dependend of the situation. Using style.display = "block" shows an element on the page while style.display = "none" makes it dissappear. The following example demonstrates how to let a <div> element appear or dissappear on pressing a button.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<p>Press the button to show or hide an element</p>
<button onclick="goneandback()">Click me</button>
<br><br>
<div id="hideshow">
The magic element
</div>
<script>
function goneandback()
{
var elemstate = document.getElementById("hideshow");
if (elemstate.style.display === "none")
{
elemstate.style.display = "block";
}
else
{
elemstate.style.display = "none";
}
}
</script>
</body>
</html>
Maybe you want to show or hide an element on a webpage dependend of the situation. Using style.display = "block" shows an element on the page while style.display = "none" makes it dissappear. The following example demonstrates how to let a <div> element appear or dissappear on pressing a button.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<p>Press the button to show or hide an element</p>
<button onclick="goneandback()">Click me</button>
<br><br>
<div id="hideshow">
The magic element
</div>
<script>
function goneandback()
{
var elemstate = document.getElementById("hideshow");
if (elemstate.style.display === "none")
{
elemstate.style.display = "block";
}
else
{
elemstate.style.display = "none";
}
}
</script>
</body>
</html>
Show or hide the contents of an inputfield
You do not want to diplay the input of a user on your screen if the information he needs to enter is secret liek a password. In that case we can mask the contents of the input field with bullets like the next snippet shows.
<!DOCTYPE html>
<html>
<head>
<h1 style ="color: red">Show or not</h1>
Paswoord:
<input type="password" value="secret" id="entrance" /><br /><br />
<input class="check" type="checkbox" />Show it
<h2>Click the checkbox to show or hide</h2>
<script>
document.querySelector(".check").addEventListener("click", shownow);
function shownow() {
var invoerveld = document.getElementById("entrance");
if (invoerveld.type === "password") {
invoerveld.type = "text";
} else {
invoerveld.type = "password";
}
}
</script>
</body>
</html>
As you can see the only thing you have to do is to check with if (entrance.type === "password") wether the type of the inputfield = "password" if that is so it is set to masking bullets. With entrance.type = "text"; the contents of the input field is changed to normal text again.
You do not want to diplay the input of a user on your screen if the information he needs to enter is secret liek a password. In that case we can mask the contents of the input field with bullets like the next snippet shows.
<!DOCTYPE html>
<html>
<head>
<h1 style ="color: red">Show or not</h1>
Paswoord:
<input type="password" value="secret" id="entrance" /><br /><br />
<input class="check" type="checkbox" />Show it
<h2>Click the checkbox to show or hide</h2>
<script>
document.querySelector(".check").addEventListener("click", shownow);
function shownow() {
var invoerveld = document.getElementById("entrance");
if (invoerveld.type === "password") {
invoerveld.type = "text";
} else {
invoerveld.type = "password";
}
}
</script>
</body>
</html>
As you can see the only thing you have to do is to check with if (entrance.type === "password") wether the type of the inputfield = "password" if that is so it is set to masking bullets. With entrance.type = "text"; the contents of the input field is changed to normal text again.
Show when page is last changed
A lesser know HTML command is document.lastModified. This command shows when a webpage is modified. We can show this info on a webpage which can be valuable information for the users.
<html>
<script>
document.write( "<B>Laatste wijziging "+ document.lastModified +"</B>");
</script>
</body>
</html>
The <B> makes the tekst appear in bold letters.
A lesser know HTML command is document.lastModified. This command shows when a webpage is modified. We can show this info on a webpage which can be valuable information for the users.
<html>
<script>
document.write( "<B>Laatste wijziging "+ document.lastModified +"</B>");
</script>
</body>
</html>
The <B> makes the tekst appear in bold letters.
Simulate a click on an element
The next snippet shows how you can simulate a click on an object in software.
document.getElementById("myelement").click();
Please note that this not works on <a> tagged elements.
The next snippet shows how you can simulate a click on an object in software.
document.getElementById("myelement").click();
Please note that this not works on <a> tagged elements.
Start a function immediately if page is loaded
There is a chance that sometime you want a function to be executed as soon as a webpage is loaded. You can do that as follows.
<!DOCTYPE html>
<html>
<title>Run function when page loads</title>
<head>
<script>
function runimmediate() {
alert('ok');
}
window.onload = runimmediate;
</script>
</head>
<body>
</body>
</html>
There is a chance that sometime you want a function to be executed as soon as a webpage is loaded. You can do that as follows.
<!DOCTYPE html>
<html>
<title>Run function when page loads</title>
<head>
<script>
function runimmediate() {
alert('ok');
}
window.onload = runimmediate;
</script>
</head>
<body>
</body>
</html>
Start a function when the whole page has loaded
It may happen that you want to wait with starting a function till te whole page is loaded. The next snippet shows how to do that:
document.addEventListener("DOMContentLoaded", function() {
alert("The document has been loaded");
});
It may happen that you want to wait with starting a function till te whole page is loaded. The next snippet shows how to do that:
document.addEventListener("DOMContentLoaded", function() {
alert("The document has been loaded");
});
Start multiple functions with one mouse-click
It is possible to start multiple functions at the same time with one mouse-click. To do so, seperate the functions with a ; The next example shows how it is done
<html>
<head>
<script>
function function01()
{
document.write ("First function. <br>");
}
function function02()
{
document.write ("Second function");
}
</script>
</head>
<body>
<p>Click the button to see the result</p>
<input type = "button" onclick = "function01(); function02()" value = "Click to start">
</body>
</html>
It is possible to start multiple functions at the same time with one mouse-click. To do so, seperate the functions with a ; The next example shows how it is done
<html>
<head>
<script>
function function01()
{
document.write ("First function. <br>");
}
function function02()
{
document.write ("Second function");
}
</script>
</head>
<body>
<p>Click the button to see the result</p>
<input type = "button" onclick = "function01(); function02()" value = "Click to start">
</body>
</html>
Test if a button was clicked
There are several ways to thest wether a button was clicked or not. The onclick function is one way. Using document.querySelector(".button").addEventListener("click", functionname); is another valid way. Here we test for a class name as the next example shows.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Test if button is pressed</title>
</head>
<body>
<h1>Check if button was clicked</h1>
<button class="BUTTON">Test the button</button>
<script>
document.querySelector(".BUTTON").addEventListener("click", buttonpressed);
function buttonpressed()
{
alert ("Yes the button was clicked");
}
</script>
</body>
</html>
There are several ways to thest wether a button was clicked or not. The onclick function is one way. Using document.querySelector(".button").addEventListener("click", functionname); is another valid way. Here we test for a class name as the next example shows.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Test if button is pressed</title>
</head>
<body>
<h1>Check if button was clicked</h1>
<button class="BUTTON">Test the button</button>
<script>
document.querySelector(".BUTTON").addEventListener("click", buttonpressed);
function buttonpressed()
{
alert ("Yes the button was clicked");
}
</script>
</body>
</html>
Test if a key was pressed
If you want to test on a page wether a key was pressed and you do not care which key use this snippet.
document.addEventListener("keypress", function()
{
alert("hoi")
});
If you want to test on a page wether a key was pressed and you do not care which key use this snippet.
document.addEventListener("keypress", function()
{
alert("hoi")
});
Test if a key was pressed 2
If you want to test if a key was pressed somewheren on the webpage you you use the next snippet.
document.onkeypress = function (e)
{
alert("pressed")
};
If you want to test if a key was pressed somewheren on the webpage you you use the next snippet.
document.onkeypress = function (e)
{
alert("pressed")
};
Test if the ENTER key was pressed in an input field
If you want to know if the user pressed enter in an input field you can use the next example.
<!DOCTYPE html>
<html>
<body>
<input id="test"> test</input>
<script>
var inputelement = document.getElementById("test");
inputelement.addEventListener("keyup", function(event)
{
if (event.key === "Enter")
{
alert("You pressed enter")
}
});
</script>
</body>
</html>
If you want to know if the user pressed enter in an input field you can use the next example.
<!DOCTYPE html>
<html>
<body>
<input id="test"> test</input>
<script>
var inputelement = document.getElementById("test");
inputelement.addEventListener("keyup", function(event)
{
if (event.key === "Enter")
{
alert("You pressed enter")
}
});
</script>
</body>
</html>
Test if the checkbox is checked
A checkbox is ideal for having a user making a fast choice. The next snippet shows how you can test if the checkbox has been checked or not.
<!DOCTYPE html>
<html>
<head>
<h1>Test a checkbox</h1>
Confirm: <input type="checkbox" class="choice" onclick="testchoice()" />
<script>
function testchoice()
{
if (document.querySelector(".choice").checked == true)
{
alert("confirmed");
}
else
{
alert("not chosen");
}
}
</script>
</body>
</html>
The line if (document.querySelector(".classname").checked == true) tests wether the checkbox has been checked or not and shows an alert depending on the state.
A checkbox is ideal for having a user making a fast choice. The next snippet shows how you can test if the checkbox has been checked or not.
<!DOCTYPE html>
<html>
<head>
<h1>Test a checkbox</h1>
Confirm: <input type="checkbox" class="choice" onclick="testchoice()" />
<script>
function testchoice()
{
if (document.querySelector(".choice").checked == true)
{
alert("confirmed");
}
else
{
alert("not chosen");
}
}
</script>
</body>
</html>
The line if (document.querySelector(".classname").checked == true) tests wether the checkbox has been checked or not and shows an alert depending on the state.
Test for an empty INPUT field
Using an INPUT field the user can fill in data. For using that data we need to make sure the INPUT field is not empty. That can be tested as the next example shows.
<html>
<body>
<script>
function testinput()
{
if(document.getElementById("input1").value == "")
{
alert('Fill in your name please.');
document.getElementById("input1").focus();
//break;
}
else
{
if(document.getElementById("input2").value == "")
{
alert('Fill in the nickname please');
document.getElementById("input2").focus();
}
}
}
</script>
Input Name <input id="input1" type="text"><br>
Input Nickname <input id="input2" type="text"><br>
<button onclick="testinput()" >Fill in and click</button>
</body>
</html>
By clicking the button the function testinput() is executed. This function tests if the input field is empty with: if(document.getElementById("input1").value == "") and if that is so a warning is displayed. The focus is changed to the INPUT field. If that bfield is higher or lower on the webpage the page will automatically scroll to that location.
Using an INPUT field the user can fill in data. For using that data we need to make sure the INPUT field is not empty. That can be tested as the next example shows.
<html>
<body>
<script>
function testinput()
{
if(document.getElementById("input1").value == "")
{
alert('Fill in your name please.');
document.getElementById("input1").focus();
//break;
}
else
{
if(document.getElementById("input2").value == "")
{
alert('Fill in the nickname please');
document.getElementById("input2").focus();
}
}
}
</script>
Input Name <input id="input1" type="text"><br>
Input Nickname <input id="input2" type="text"><br>
<button onclick="testinput()" >Fill in and click</button>
</body>
</html>
By clicking the button the function testinput() is executed. This function tests if the input field is empty with: if(document.getElementById("input1").value == "") and if that is so a warning is displayed. The focus is changed to the INPUT field. If that bfield is higher or lower on the webpage the page will automatically scroll to that location.
Test if the window has changed size
If you want to know if a user has changed the windows size you can listen for the window.resize event.
window.addEventListener('resize', function(event){
var newWidth = window.innerWidth;
var newHeight = window.innerHeight;
alert(newWidth);
alert(newHeight);
});
Test wether Javascript is activated or not
Believe it or not but there are people who have de-activated Javascript in their browser. And there are some TOR browsers that have Javascript de-activated automatically. A lot of functionality will not work if Javascript is disabled. We can test wether Javascript is activated and give the user a warnong if it is not.
<script>
document.write("Javascript is activated, you have full functionality")
</script>
<noscript><h1>JavaScript is disabled. Please turn it on for full functionality</h1></noscript>
Put these lines in the <head> or <body> part of your HTML code and the user will get a welcome message dependent of Javascript functionality.
Believe it or not but there are people who have de-activated Javascript in their browser. And there are some TOR browsers that have Javascript de-activated automatically. A lot of functionality will not work if Javascript is disabled. We can test wether Javascript is activated and give the user a warnong if it is not.
<script>
document.write("Javascript is activated, you have full functionality")
</script>
<noscript><h1>JavaScript is disabled. Please turn it on for full functionality</h1></noscript>
Put these lines in the <head> or <body> part of your HTML code and the user will get a welcome message dependent of Javascript functionality.
Three methods to generate a click event
There are 3 methods to generate a click event on an element on a webpage.
Method 1:
<div id="element">Click me</div>
<script>
document.getElementById('element').onclick = function()
{
alert('click');
}
</script>
Method 2:
<div id="element">Click me</div>
<script>
var el = document.getElementById("element");
el.addEventListener('click', function()
{
alert("click");
});
</script>
Methode 3:
<div id="element">Click me</div>
<script>
var el = document.getElementById("element");
el.onclick = function()
{
alert("click");
}
</script>
It does not matter which version you use. For clarity be consistent and use always the same code in a program.
There are 3 methods to generate a click event on an element on a webpage.
Method 1:
<div id="element">Click me</div>
<script>
document.getElementById('element').onclick = function()
{
alert('click');
}
</script>
Method 2:
<div id="element">Click me</div>
<script>
var el = document.getElementById("element");
el.addEventListener('click', function()
{
alert("click");
});
</script>
Methode 3:
<div id="element">Click me</div>
<script>
var el = document.getElementById("element");
el.onclick = function()
{
alert("click");
}
</script>
It does not matter which version you use. For clarity be consistent and use always the same code in a program.
Trigger a button click
When a button on a webpage is clicked a function is activated. By using the right code we can let de program trigger the button click. You can do that with: document.getElementById("buttonid").click(); The next snippet shows how to do that.
<!DOCTYPE html>
<html>
<head>
</head>
<title>Simulate pressing a button</title>
<body>
<p onmouseover="pressed()">Move the mouse over this text to simulate pressing the button</p>
<button type="button" id="testbutton" onclick="pressed()">Click me to test</button>
<script>
function klikknop()
{
document.getElementById("testbutton").click();
}
function pressed()
{
alert("The button has been pressed.");
}
</script>
</body>
</html>
Pressing the button has the alert show: The button has been pressed. When you move the mouse over the text the clicking of the button will be simulated. Be carefull in using this function !!
When a button on a webpage is clicked a function is activated. By using the right code we can let de program trigger the button click. You can do that with: document.getElementById("buttonid").click(); The next snippet shows how to do that.
<!DOCTYPE html>
<html>
<head>
</head>
<title>Simulate pressing a button</title>
<body>
<p onmouseover="pressed()">Move the mouse over this text to simulate pressing the button</p>
<button type="button" id="testbutton" onclick="pressed()">Click me to test</button>
<script>
function klikknop()
{
document.getElementById("testbutton").click();
}
function pressed()
{
alert("The button has been pressed.");
}
</script>
</body>
</html>
Pressing the button has the alert show: The button has been pressed. When you move the mouse over the text the clicking of the button will be simulated. Be carefull in using this function !!
Wait a certain amount of time
Unlike other languages Javascript has no sleep or delay function. Nevertheless you can activate a function after a certain time. The method to use for this is
setTimeout(function() {}, (x * 1000)); The variable x determines the amount of seconds before the function runs.
var number1 = 10;
var number2 = 20;
var sum = number1 + number2;
setTimeout(function() {alert("the sum of the addition = " + sum );
}, (10 * 1000));
In the above example the calculation is done immediately but the result is shown after 10 seconds. Please bear in mind that the program runs on and therefore the values of number1 and number2 might have altered in between.
Unlike other languages Javascript has no sleep or delay function. Nevertheless you can activate a function after a certain time. The method to use for this is
setTimeout(function() {}, (x * 1000)); The variable x determines the amount of seconds before the function runs.
var number1 = 10;
var number2 = 20;
var sum = number1 + number2;
setTimeout(function() {alert("the sum of the addition = " + sum );
}, (10 * 1000));
In the above example the calculation is done immediately but the result is shown after 10 seconds. Please bear in mind that the program runs on and therefore the values of number1 and number2 might have altered in between.
Wait a certain amount of time 2
If we need to activate a function after a certain amount of seconds
we can do that with the following snippet.
function sleep(amount)
{
return new Promise(resolve => setTimeout(resolve, amount));
}
async function delayfunc(waittime)
{
alert("Wait a predefined number of seconds");
await sleep(waittime);
alert("the function has been executed");
}
sleep(5000);
alert(123456);
If we need to activate a function after a certain amount of seconds
we can do that with the following snippet.
function sleep(amount)
{
return new Promise(resolve => setTimeout(resolve, amount));
}
async function delayfunc(waittime)
{
alert("Wait a predefined number of seconds");
await sleep(waittime);
alert("the function has been executed");
}
sleep(5000);
alert(123456);
What choice was made in a drop-down menu
The next example shows how to determine which choice a user made in a drop-down menu. The alerts shows the index of the menu.
<html>
<body>
<select id="choose">
<option>C++</option>
<option>Javascript</option>
<option>Python</option>
</select>
<input type="button" onclick="display()" value="Make your choice">
<p>Click the button to show the choosen index</p>
<script>
function display()
{
var index = document.getElementById("choose").selectedIndex;
alert(index);
}
</script>
</body>
</html>
If we change var index = document.getElementById("choose").selectedIndex; into var index = document.getElementById("choose").value; then the alert shows the name of the choice we made.
The next example shows how to determine which choice a user made in a drop-down menu. The alerts shows the index of the menu.
<html>
<body>
<select id="choose">
<option>C++</option>
<option>Javascript</option>
<option>Python</option>
</select>
<input type="button" onclick="display()" value="Make your choice">
<p>Click the button to show the choosen index</p>
<script>
function display()
{
var index = document.getElementById("choose").selectedIndex;
alert(index);
}
</script>
</body>
</html>
If we change var index = document.getElementById("choose").selectedIndex; into var index = document.getElementById("choose").value; then the alert shows the name of the choice we made.
Which page is this
Sometimes a website or a webpage gets copied. And you might want to know if the currect Javascript code runs from the original page or from a copy. This is how you can check the url:
var currentUrl = window.location.href;
Sometimes a website or a webpage gets copied. And you might want to know if the currect Javascript code runs from the original page or from a copy. This is how you can check the url:
var currentUrl = window.location.href;