JavaScript Examples PDF free download (51 Examples)

In this tutorial, we will see various JavaScript examples. you can also download JavaScript examples pdf for free.

If you are a web developer then you should know what is JavaScript and how to use JavaScript in various web applications.

I hope the below examples will be helpful to you, to learn JavaScript. So let’s start with various javascript examples.

SharePoint 2016 Tutorial Contents

What is JavaScript?

JavaScript is a lightweight object-based scripting programing language. Basically to add the functionality in HTML code javascript is used. Because of the JavaScript, web pages become more interactive with the user.

Mostly JavaScript use for game development and mobile application development. JavaScript makes the HTML form dynamic. JavaScript is used to create client-side dynamic pages.

We can run JavaScript with the help of any browser. We can use the Javascript code in the HTML file using the Script tag. When we run the HTML code in the browser then the javascript also runs.

The main advantage of JavaScript scripting language is all browsers like IE, Chrome, Mozilla, Opera, etc supports JavaScript. JavaScript runs on any operating system like Windows, Linux, mac anything.

Editors For JavaScript

Before knowing, how to start with JavaScript, we have to know what are the available editors for JavaScript. Some of the recommend editors for JavaScript are:

  • Notepad
  • Notepad++
  • Sublime Text
  • Visual Studio Code
  • Atom
  • BBEdit
  • Komodo Edit
  • Emacs etc.

How to Start with JavaScript?

Before start writing your first JavaScript code, Few things you should remember on how to start with JavaScript.

We need to put JavaScript code inside <script> and </script> tags.

Example:

<script>
alert("Welcome to Top 51 JavaScript Examples You Should Learn");
</script>

We can put any number of scripts inside an HTML document, either in the <body> or <head> section of the HTML page or in both tags.

<!DOCTYPE html>
<html>
<head>
<script>
function demoFunction() {
alert("JavaScript Examples")
}
</script>
</head>
<body>
<p>Demo JavaScript Examples</p>
<button type="button" id="btnDemo" onclick="myFunction()">Download It Now</button>
<p>Welcome to Top 51 JavaScript Examples You Should Learn PDF</p>
<button type="button" id="btnSubmit" onclick="myFunction()">Download It Now</button>
<script>
function myFunction() {
alert("JavaScript Examples PDF Download")
}
</script>
</body>
</html>

We can also store JavaScript code in an external .js file and call that file inside our HTML Code. We should not write all JavaScript code inside the HTML file.

We can store below script code inside a .js file like (51JavaScriptExamples.js)

function showAlert() {
alert (Welcome to 51 JavaScript examples tutorial);
}

And in the HTML file we can call like below:

<!DOCTYPE html>
<html>
<body>
<p>51 JavaScript Examples</p>
<button type="button" onclick="showAlert()">Show Alert Box</button>
<script src="myScript.js"></script>
</body>
</html>

Now we will see the 51 JavaScript Examples.

Example-1: Display Alert in JavaScript

In the below example, We can show an alert in JavaScript.

<!DOCTYPE html>
<html>
<body>
<p>Top 51 JavaScript Example: Display alert in javascript</p>
<p>Give Your Details</p>
First name:<br>
<input type="text" id="txtFirstName" name="firstname">
<br>
Last name:<br>
<input type="text" name="lastname" id="txtLastName">
<br>
<br>
<button onclick="showAlert()" id=btnSubmit>Submit</button>
<script>
function showAlert() {
alert("Created Account");
}
</script>
</body>
</html>

The output: We can see in the output one alert message is coming and telling that “Created Account”

javascript popup window onclick
javascript popup window onclick

Display Conformation box using JavaScript

In the Conformation Box, one box will appear and ask for conformation like “OK” and “Cancel” option.

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Top 51 JavaScript Example: Display Confirmation Box using JavaScript</p>
<button onclick="showConformationMessage()" id=btnClick>Click here to check your account is created or not </button>
<script type="text/javascript">
function showConformationMessage(){
var name = confirm("Are you want to use the account");
if (name == true){
alert(" Account created sucessfully");
}
else{
alert("sorry,try again Your account is not created");
}
}
</script>
</body>
</html>

Output:

The output is showing a confirmation box which is asking for “Are you want to use the account”. We can click on “Ok” or “Cancel”

Display Prompt box using JavaScript

Prompt box in JavaScript allows user to input in a textbox. Here we will see how we can show a prompt box using JavaScript.

<!DOCTYPE html>
<html>
<body>
<p>Top 51 JavaScript Examples: Display Prompted box using JavaScript</p>
<button onclick="showPromptBox()">Click here to see prompt box</button>
<p id="pId"></p>
<script>
function showPromptBox() {
var text;
var username = prompt("Please enter your username", "");
if (username == null || username == "") {
text = "User cancelled the prompt.";
} else {
text = "Hello !" + username + "Welcome to your SharePoint site";
}
document.getElementById("pId").innerHTML =text;
}
</script>
</body>
</html>

Output:

JavaScript Examples PDF
cool javascript examples

When click on OK we can able to see below output.

alert box in javascript
alert box in javascript

Example-2: mouseover and mouseout in javascript

This example shows how we can use onmouseover javascript functionality as well as onmouseout in javascript. Below is an example, where a user mouse over an image, it will display the large picture.

<!DOCTYPE html>
<html>
<body>
<img onmouseover="largePictureOnMouseOver(this)"onmouseout="smallPictureOnMouseOut(this)" border="0" src="https://onlysharepoint2013.sharepoint.com/:i:/r/sites/Raju/tsinfo/SiteAssets/cool-javascript-examples.jpg?csf=1&e=igNfKB" width="32" height="32">
<p>The large picture will display when mouse pointer over the image and when mouse pointer is moved out of picture</p>
<script>
function largePictureOnMouseOver(p) {
p.style.height = "64px";
p.style.width = "64px";
}
function smallPictureOnMouseOut(p) {
p.style.height = "32px";
p.style.width = "32px";
}
</script>
</body>
</html>

Similarly, in the below JavaScript example, we can use onmouseout which will display a larger picture when the user removes the mouse pointer from a picture.

<!DOCTYPE html>
<html>
<body>
<img onmouseout="largePictureOnMouseOver(this)"onmouseover="smallPictureOnMouseOut(this)" border="0" src="https://onlysharepoint2013.sharepoint.com/:i:/r/sites/Raju/tsinfo/SiteAssets/cool-javascript-examples.jpg?csf=1&e=igNfKB" width="32" height="32">
<p>The small picture will display when mouse pointer over the image and when mouse pointer is moved out of picture, large picture is displaying</p>
<script>
function largePictureOnMouseOver(p) {
p.style.height = "64px";
p.style.width = "64px";
}
function smallPictureOnMouseOut(p) {
p.style.height = "32px";
p.style.width = "32px";
}
</script>
</body>
</html>

Example-3: Use onkeypress In JavaScript to Display Alerts

By using JavaScript, we can display alert box when user press on the text box.

<!DOCTYPE html>
<html>
<body>
<p><b>OnKeyDown JavaScript Example<b></p>
<input type="text"  id="txtKey"onkeydown="onKeyDown()">
<script>
function onKeyDown() {
alert("You press the down arrow key in the text box");
}
</script>
</body>
</html>

Example-4: JavaScript Validation Examples

We can validate input controls using JavaScript easily. Below are a few JavaScript validation examples.

Textbox required validation in javascript

By using JavaScript, we can validate for empty value in textboxes. Whenever an user tries to submit a form without entering a value in the textbox, it will display mandatory field validation messages in an alert box.

<html>
<body>
<script type='text/javascript'>
function textBoxValidation()
{
if(document.getElementById('txtBox').value.trim()== "")
{
alert('Textbox should not be blank');
txtBox.focus();
return false;
}
alert("Your name submitted sucessfully")
return true;
}
</script>
<form>
Name:<input type='text' id='txtBox'/> <input type='button' onclick="textBoxValidation()"id="btnSubmit" value='Submit' />
</form>
</body>
</html>
Textbox required validation in javascript
Textbox required validation in javascript

Email validation in JavaScript

The below JavaScript code validates a textbox for correct email id. Whatever user enters if not a proper email id then it will display a message in the alert box.

<html>
<p>51 example of JavaScript</p>
<body>
<script type='text/javascript'>
function emailValidation()
{
var emailIdValue= /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if(document.getElementById('txtEmail').value.match(emailIdValue))
{
alert("Email Validation sucessfully");
return true;
}
else
{
alert("This email is invalid, give a proper email id");
txtEmail.focus();
return false;
}
}
</script>
<form>
Enter the E-mail Address value: <input type='text' id='txtEmail'/>
<input type='button' onclick="emailValidation()" id="btnSubmit" value='Submit' />
</form>
</body>
</html>
javascript email id validation example
javascript form validation example

Letter Validation in JavaScript

There will be some scenarious where you want users to enter only letters like (A-Z or a-z), We can do letter only validations using JavaScript.

<html>
<body>
<script type='text/javascript'>
function letterValidation()
{
var letterValue = /^[a-zA-Z]+$/;
if(document.getElementById('txtletter').value.match(letterValue))
{
alert("Yes you enter letters only.");
return true;
}
else
{
alert('Enter only Letters like A-Z or a-z');
txtletter.focus();
return false;
}
}
</script>
<form>
Please Letters Only: <input type='text' id='txtletter'/>
<input type='button' id="btnSubmit" onclick="letterValidation()" value='Submit' />
</form>
</body>
</html>

Number Validation in JavaScript

Sometimes, you may get business requirement where you need to allows users to enter only numbers, we can do JavaScript number validation very easily.

<html>
<body>
<script type='text/javascript'>
function onlyNumberValidation()
{
var numbers = /^[0-9]+$/;
if(document.getElementById('txtletter').value.match(letterAndNumberValue))
{
alert("Yes you enter numbers only.");
return true;
}
else
{
alert('Only numbers are allowed');
txtletter.focus();
return false;
}
}
</script>
<form>
Enter Value: <input type='text' id='txtletter'/>
<input type='button' id="btnSubmit" onclick="onlyNumberValidation()" value='Submit' />
</form>
</body>
</html>

Letter and Number Validation in JavaScript

Sometimes, you may get business requirement where you need to allows users to enter either letter and numbers, we can validate letters and numbers by using JavaScript very easily.

<html>
<body>
<script type='text/javascript'>
function letterAndNumberValidation()
{
var letterAndNumberValue = /^[0-9a-zA-Z]+$/;
if(document.getElementById('txtletter').value.match(letterAndNumberValue))
{
alert("Yes you enter letters or numbers only.");
return true;
}
else
{
alert('Only letters and numbers allowed');
txtletter.focus();
return false;
}
}
</script>
<form>
Enter Value: <input type='text' id='txtletter'/>
<input type='button' id="btnSubmit" onclick="letterAndNumberValidation()" value='Submit' />
</form>
</body>
</html>

IP Address Validation in JavaScript

We can validate IP Address using JavaScript easily.

<html>
<body>
<script type='text/javascript'>
function ipAddressValidation()
{
var ipAddressPattern = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
if(document.getElementById('txtletter').value.match(ipAddressPattern))
{
alert("Yes you enter corrent IP address.");
return true;
}
else
{
alert('IP Address Validation Failed');
txtletter.focus();
return false;
}
}
</script>
<form>
Enter Value: <input type='text' id='txtletter'/>
<input type='button' id="btnSubmit" onclick="ipAddressValidation()" value='Submit' />
</form>
</body>
</html>

Example-5: Retrieve Today’s Date in JavaScript

We can retrive current date, current month, current year, curren time from Date using JavaScript.

<!DOCTYPE html>
<html>
<body>
<p>getDate() method is used for display today's date in JavaScript</p>
<p id="currentDateDate"></p>
<p id="currentMonth"></p>
<p id="currentYear"></p>
<p id="currentFullDate"></p>
<p id="currentTime"></p>
<script>
var date = new Date();
document.getElementById("currentDateDate").innerHTML ="Current Date using JavaScript: "+date.getDate();
document.getElementById("currentMonth").innerHTML ="Current Month using JavaScript: "+(date.getMonth()+1);
document.getElementById("currentYear").innerHTML ="Current Year using JavaScript: "+date.getFullYear();
document.getElementById("currentFullDate").innerHTML ="Current Full Date using JavaScript: "+date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate();
document.getElementById("currentTime").innerHTML ="Current Time using JavaScript: "+date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
</script>
</body>
</html>

Once you run code, you can see the output like below:

  • Current Date using JavaScript: 23
  • Current Month using JavaScript: 9
  • Current Month using JavaScript: 2018
  • Current Full Date using JavaScript: 2018-9-23
  • Current Time using JavaScript: 20:58:59
Retrieve Today's Date in JavaScript
Working with Dates using JavaScript

Example-6: Reverse array javascript

We use arrays in JavaScript to store multiple values. We can easily reverse an array using JavaScript by using reverse() method.

<!DOCTYPE html>
<html>
<body>
<p>Reverse Array JavaScript Example:</p>
<button onclick="reverseArrayValue()" id="btnClick">Click</button>
<p id="pId"></p>
<script>
var season = ["Summer", "Winter", "Monsoon","Spring"];
document.getElementById("pId").innerHTML = season;
function reverseArrayValue() {
season.reverse();
document.getElementById("pId").innerHTML = season;
}
</script>
</body>
</html>

We can able to see how the code is helpful to change the sequence of season.

Example-7: JavaScript concate or merge two Arrays

Now we will see how we can concate or merge two arrays in JavaScript by using the concat() method.

Here I have two arrays like:

var twoDay= ["Sunday", "Monday"];
var fiveDay= ["Tuesday", "Wednsday","Thursday", "Friday","Saturday"];

Below is the JavaScript code which will concat both the arrays.

<!DOCTYPE html>
<html>
<body>
<p>We will see after clicking the button how two array will join</p>
<button onclick="concateTwoArray()" id="btnClick">Click</button>
<p id="pId"></p>
<script>
function concateTwoArray() {
var twoDay= ["Sunday", "Monday"];
var fiveDay= ["Tuesday", "Wednsday","Thursday", "Friday","Saturday"];
var totalDay = twoDay.concat(fiveDay);
document.getElementById("pId").innerHTML = totalDay ;
}
</script>
</body>
</html>
JavaScript concate or merge two Arrays
JavaScript concate or merge two Arrays

Example-8: Reverse String in JavaScript

We can reverse a string in JavaScript by using below script.

<!DOCTYPE html>
<html>
<body>
<p>Reverse String in JavaScript</p>
Main String: "Bijay Kumar";
<p id="reverseText"></p>
<script>
var reverseString=reverseStringMethod("Bijay Kumar");
document.getElementById("reverseText").innerHTML = "Reverse String: "+reverseString ;
function reverseStringMethod(str) {
var result = "";
for (var i = str.length - 1; i >= 0; i--) {
result += str.charAt(i);
}
return result;
}
</script>
</body>
</html>

The result will appear like below:

Reverse String in JavaScript
reverse a string in javascript without using reverse function

Example-9: JavaScript Open a page using window.open() method

We can open a new web page using window.open() method in JavaScript. The below code will open https://www.tsinfotechnologies.com in a new window.

<!DOCTYPE html>
<html>
<body>
<p>In this example we can able to see how the winow.open method is used to open a new window page in JavaScript </p>
<button onclick="openNewWindow()" id="btnClick">Click</button>
<script>
function openNewWindow() {
window.open("https://www.tsinfotechnologies.com/");
}
</script>
</body>
</html>

Example-10: if else statement in JavaScript

We can use if/else statement to executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed.

<!DOCTYPE html>
<html>
<body>
<p>In this code we will check particular year is a leap year or not</p>
<script type="text/javascript">
var daysInFebruary=29;
if( daysInFebruary==29 ){
document.write("This year is a leapYear");
}
else
{
document.write("This is not a leapyear");
}
</script>
</body>
</html>

Example-11: Print page In JavaScript

We can print a page using window.print() method in JavaScript. Here once the user clicks on the button, Print setup page will appear.

<!DOCTYPE html>
<html>
<body>
<p><b>Here we will check how print method is work while clicking on button click<b></p>
<button onclick="PrintPage()" id="btnClick">Click it</button>
<script>
function PrintPage() {
window.print();
}
</script>
</body>
</html>
Print page using JavaScript
print javascript using window.print()

Example-12: Insert element in array javascript

This JavaScript example, we will see how we can insert an element into an array in JavaScript. We can use the Push method to insert an element to an array in JavaScript.

<!DOCTYPE html>
<html>
<body>
<p>In this code we will see how to push an element to array</p>
<button onclick="pushElementToArray()" id="btnClick">Click</button>
<p id="pId"></p>
<script>
var days = ["Sunday", "Monday", "Tuesday", "Wednsday"];
document.getElementById("pId").innerHTML = days;
function pushElementToArray() {
days.push("Saturday");
document.getElementById("pId").innerHTML = days;
}
</script>
</body>
</html>
insert element in array javascript
insert element in array javascript

Example-13: get current url javascript

We can get currrent url using JavaScript by using the window.location.href attribute easily. You can see in the below JavaScript examples it display’s the current URL.

<!DOCTYPE html>
<html>
<body>
<p>This widow.location() method will display currently which page you are opening.</p>
<p id="pId"></p>
<script>
document.getElementById("pId").innerHTML ="The full URL of this page is:<br>" + window.location.href;
</script>
</body>
</html>
get current url javascript
get current url javascript

Example-14: getElementsByClassName() method in JavaScript

This example we will see how we can use getElementsByClassName() method in JavaScript. In an alert box, we are displaying the value from a class div.

<!DOCTYPE html>
<html>
<body>
<div class="myclass">The value is presented inside the class</div>
<button onclick="RetriveByClassName()" id="btnClick">Click</button>
<script>
function RetriveByClassName() {
var x = document.getElementsByClassName("myclass");
alert(x[0].innerHTML);
}
</script>
</body>
</html>
getelementsbyclassname javascript
getelementsbyclassname javascript

Example-15: getElementByName() method in JavaScript

We can use getElementByName() method to retrieve HTML element uisng name attribute. Here I am trying to check a checkbox based on the name attribute which we retrieve getElementByName() method.

<!DOCTYPE html>
<html>
<body>
<p>How to check a checkbox using getElementByName() method in JavaScript</p>
Tiger: <input name="forestAnimal" type="checkbox" value="Tiger">
Cow: <input name="domesticAnimal" type="checkbox" value="Cow">
<button onclick="retriveElementByName()"  id="btnClick">Click</button>
<script>
function retriveElementByName(){
var animalName = document.getElementsByName("domesticAnimal");
var i;
for (i = 0; i < animalName.length; i++) {
if (animalName[i].type == "checkbox") {
animalName[i].checked = true;
}
}
}
</script>
</body>
</html>
getElementByName() method in JavaScript
javascript popup window onclick example

Example-16: Disable Browser back and forward button in browser using JavaScript

By using JavaScript, we can easily disable browser back and forward button. We can use window.history.back() and window.history.forward() methods to disable browser back and forward button respectively.

Disable back button in browser using javascript

By using window.history.back() JavaScript method, we can disable browser back button in JavaScript.

<!DOCTYPE html>
<html>
<body>
<p>Disable browser back button using JavaScript</p>
<button onclick="disableBackButton()" id="btnBack">Back</button>
<script>
function disableBackButton() {
window.history.back();
}
</script>
</body>
</html>

Disable Forward button in browser using JavaScript:

By using window.history.forward() we will be able to disable forward button in browser using JavaScript.

<html>
<head>
<p>Disable browser forward button using JavaScript window.history.forward() method</p>
<script>
function disableTheForwardButton() {
window.history.forward()
}
</script>
</head>
<body>
<input type="button" value="Forward" onclick="disableTheForwardButton()" id="btnForward">
</body>
</html>

Example-17: Disable and Enable Dropdown List using JavaScript

We can easily enable or disable dropdown list using JavaScript by using disabled property.

Disable Dropdown list using JavaScript

Below is the JavaScript code which we can use to disable dropdown list.

<!DOCTYPE html>
<html>
<body>
<form>
<select id="selectAnimal">
<option>Cats</option>
<option>Dogs</option>
</select>
</form>
<p>Click the button to disable the dropdown list.</p>
<button onclick="disableDropDown()" id="btnClick>Click</button>
<script>
function disableDropDown() {
document.getElementById("selectAnimal").disabled = true;
}
</script>
</body>
</html>
Disable Dropdown list using JavaScript
Enable Dropdown List using JavaScript
alert box in javascript

Enable Dropdown list using JavaScript

Below is the JavaScript code which we can use to enable dropdown list. We can enable dropdown list by simply setting disabled property to false.

<!DOCTYPE html>
<html>
<body>
<form>
<select id="selectAnimal">
<option>Cats</option>
<option>Dogs</option>
</select>
</form>
<p>Click the button to enable the dropdown list.</p>
<button onclick="enableDropDown()" id="btnClick>Click</button>
<script>
function enableDropDown() {
document.getElementById("selectAnimal").disabled = false;
}
</script>
</body>
</html>

Example-18: Disable mouse right click using javascript

Below is the PowerShell script, by using which we can disable mouse right click using JavaScript.

<html>
<body >
<p>In this Example we can able to see how to disable mouse right click in JavaScript.</p>
<script type=”text/javascript”>
if (document.layers) {
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown = function() {
return false;
};
}
else {
document.onmouseup = function(x) {
if (x != null && x.type == “mouseup”) {
if (x.which == 2 || x.which == 3) {
return false;
}
}
};
}
document.oncontextmenu = function() {
return false;
};
</script>

Example-19: JavaScript Date Countdown Timer

We can display a javascript date countdown timer using javascript easily. Below is a timer example in JavaScript.

<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<p id="pId"></p>
<script>
var expiredDate = new Date("Jan 5, 2020 15:37:29").getTime();
var t = setInterval(function() {
var nowdate = new Date().getTime();
var timePeriod = expiredDate - nowdate;
var days = Math.floor(timePeriod/ (1000 * 60 * 60 * 24));
var hours = Math.floor((timePeriod % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((timePeriod % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((timePeriod % (1000 * 60)) / 1000);
document.getElementById("pId").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
if (timePeriod < 0)
{
clearInterval(t);
document.getElementById("pId").innerHTML = "EXPIRED";
}
},
1000);
</script>
</body>
</html>

Once you run the code you can see the results like below:

JavaScript Date Countdown Timer
javascript date countdown timer

Example-20: Check box validation using JavaScript (javascript checkbox checked)

This example shows how to check checkbox is checked or not in javascript. For this example, on a button click we are displaying if a check box is checked or not.

<!DOCTYPE html>
<html>
<body>
Checkbox: <input type="checkbox" id="chkBox">
<p>JavaScript check box validation example</p>
<button onclick="showCheckBoxAlert()" id="btnClick">Click</button>
<script>
function showCheckBoxAlert() {
var x = document.getElementById("chkBox");
if(!x.checked)
{
alert('Check box is unchecked');
return false;
}
else
{
alert('Check box is checked');
return false;
}
}
</script>
</body>
</html>

If user does not check the check box, it will display an alert message.

Check box validation using JavaScript
confirm box in javascript

Example-21: get query string value in javascript

By using JavaScript we can retrieve query string values from a URL. Or we can get url parameter value by name using javascript.

Here my url is:

https://onlysharepoint2013.sharepoint.com/sites/Raju/tsinfo/SitePages/51JsExample.aspx?PageView=Shared&InitialTabId=Ribbon.WebPartPage&VisibilityContext=WSSWebPartPage

VisibilityContext=”WSSWebPartPage”

In the output we can able to see: “WSSWebPartPage”

<html>
<body>
<button onclick="GetParameterValues('MyID')" id="btnClick">Click me</button>
<script>
function GetParameterValues(param) {
var url = window.location.href.slice(window.location.href.indexOf("?") + 1).split("&");
for (var i = 0; i < url.length; i++) {
var urlparam = url[i].split("=");
if (urlparam[0] == param) {
return urlparam[1];
}
}
alert(urlparam[1]);
}
</script>
</body>
</html>

Example-22: JavaScript get or set radio button value

We can get radio button value easily using JavaScript.

Get radio button selected value using JavaScript

We can easily Get radio button selected value using JavaScript.

<!DOCTYPE html>
<html>
<body>
<p>Retrieve Get radio button selected value using JavaScript</p>
<p>Select the gender:</p>
<input type="radio" name="Gender" onclick="myFunction(this)" value="Male">Male<br>
<input type="radio" name="Gender" onclick="myFunction(this)" value="Female">Female<br>
<script>
function myFunction(Gender) {
alert(Gender.value);
}
</script>
</body>
</html>

Set radio button value using JavaScript

We can set radio button value using JavaScript by using JavaScript code.

<!DOCTYPE html>
<html>
<body>
<p>Set radio button value using JavaScript</p>
Married: <input type="radio" id="radiomarried">
Unmarried: <input type="radio" id="radioUnmarried">
<p>Click the "Try it" button to check the radio button.</p>
<button onclick="selectTheMariedButton()">Click if you are maried</button>
<button onclick="selectTheUnmariedButton()">Click if you are not maried</button>
<script>
function selectTheMariedButton() {
var x = document.getElementById("radiomarried");
x.checked = true;
alert("Married is selected");
}
function selectTheUnmariedButton() {
var y = document.getElementById("radioUnmarried");
y.checked = true;
alert("Unmarried is selected");
}
</script>
</body>
</html>

Example-23: JavaScript screen height

We can easily get screen height using JavaScript.

<!DOCTYPE html>
<html>
<body>
<p>51 Top JavaScript Example</p>
<p>When clicking on button it is showing the Screen height</p>
<button onclick="showScreenHeight()" id="btnClick">Click</button>
<p id="pId"></p>
<script>
function showScreenHeight() {
var totalHeight = "Total Height: " + screen.height + "px";
document.getElementById("pId").innerHTML =totalHeight;
}
</script>
</body>
</html>

Example-24: auto refresh page javascript

Now we can see how we can auto refresh page using JavaScript.

<html>
<head>
<p>auto refresh page javascript</p>
<script type="text/JavaScript">
function AutoRefresh( t ) {
setTimeout("location.reload(true);", t);
}
</script>
</head>
<body onload="JavaScript:AutoRefresh(3000);">
</body>
</html>

Example-25: Convert Celcius Value to Faranheit Value in JavaScript

We see how we can convert celcius value to farahheit value in JavaScript.

<!DOCTYPE html>
<html>
<body>
<p>51 Top JavaScript Examples: Convert celcius to faranheit value</p>
<p>Celcius Value:<input id="txtCelcius" onkeyup="convert('C')"> </p>
<p>Farenhit Value:<input id="txtFahrenhit" onkeyup="convert('F')"> </p>
<script>
function convert(degree) {
var p;
if (degree == "C") {
p = document.getElementById("txtCelcius").value * 9 / 5 + 32;
document.getElementById("txtFahrenhit").value = Math.round(p);
} else {
p = (document.getElementById("txtFahrenhit").value -32) * 5 / 9;
document.getElementById("txtCelcius").value = Math.round(p);
}
}
</script>
</body>
</html>
Convert Celcius Value to Faranheit Value in JavaScript
Convert Celcius Value to Faranheit Value in JavaScript

Example-26: javascript get today’s date

We can retrieve today’s date using JavaScript.

<!DOCTYPE html>
<html>
<body>
<p>51 Top JavaScript Example:Showing Todays date and time</p>
<p>Todays date is:</p>
<p id="pId"></p>
<script>
var date = new Date();
document.getElementById("pId").innerHTML = date;
</script>
</body>
</html>

Example-27: Scroll Down Event in JavaScript

This JavaScript examples shows how can we use scroll down event in JavaScript.

<!DOCTYPE html>
<html>
<head>
<style>
div {
border: 1px solid black;
width: 200px;
height: 100px;
overflow: scroll;
}
</style>
</head>
<body>
<p>This example is showing how scroll down event will work</p>
<div onscroll="scrollDownEvent()">TSInfo Technologies, one of the leading SharePoint Offshore SharePoint development company based out in Bangalore, India. We focus on SharePoint development, migration, support and training. May be it is web part development, workflow development or Add-in development, our SharePoint expert team will help you to deliver the project successfully. Our team has done few migration projects successfully, be it from MOSS 2007 -> SharePoint 2010 -> SharePoint 2013 -> SharePoint 2013, or migrating from SharePoint On-premises to SharePoint Online Office 365, we can deliver it succesfully. Are you looking out for an IT outsourcing partner?</div>
<p>Scrolled <span id="pSpan">0</span> times.</p>
<script>
var x = 0;
function scrollDownEvent() {
document.getElementById("pSpan").innerHTML = x += 1;
}
</script>
</body>
</html>
Scroll Down Event in JavaScript
javascript scroll to bottom

Example-28: JavaScript Animation example

Below is an example of JavaScript animation.

<!DOCTYPE html>
<html>
<style>
#myBigContainer {
width: 600px;
height: 500px;
position: relative;
background: pink;
}
#mySmallContainer {
width: 100px;
height: 50px;
position: absolute;
background-color: black;
}
</style>
<body>
<p>
<button onclick=" javaScriptAniminationForMove()">Try this</button>
</p>
<div id ="myBigContainer">
<div id ="mySmallContainer"></div>
</div>
<script>
function javaScriptAniminationForMove() {
var element = document.getElementById("mySmallContainer");
var p = 0;
var idValue = setInterval(frame, 30);
function frame() {
if (p == 500) {
clearInterval(idValue);
}
else
{
p++;
element.style.top = p+ 'px';
element.style.left = p + 'px';
}
}
}
</script>
</body>
</html>
JavaScript Animation example
JavaScript animation examples

Example-29: Play and Pause video in JavaScript

We can easly play video and pause video file in javascript.

<!DOCTYPE html>
<html>
<body>
<p>51 Top JavaScript Example:Play and stop a video using JavaScript</p>
<p>When we click on Play button the video will play and when click on stop button the video will stop</p>
<button onclick="playVideo()" id="btnPlay()" type="button">Play The Video</button>
<button onclick="stopVideo()"id="btnStop" type="button">Stop The Video</button><br>
<video id="waterFallVid" width="320" height="250">
<source src="https://onlysharepoint2013.sharepoint.com/sites/Raju/tsinfo/SiteAssets/WaterFall.mov" type="video/mp4">
</video>
<script>
var video = document.getElementById("waterFallVid");
function playVideo()
{
video.play();
}
function stopVideo()
{
video.pause();
}
</script>
</body>
</html>

You can see below example, by clicking on a button video is playing and in another button click video we are pausing the video using JavaScript.

Play and Pause video in JavaScript
Play and pause video file using JavaScript

Example-30: Change background color of div javascript

Below JavaScipt we can change background color of div like below:

<!DOCTYPE html>
<html>
<head>
<style>
#divId{
width: 300px;
height: 300px;
background-color:blue;
color: white;
}
</style>
</head>
<body>
<p>When Click on Button click the background colour will change.</p>
<button onclick="changeBackgroundColour()" id="btnClick">Click it</button>
<div id="divId">
Top 51 JavaScript examples.
</div>
<script>
function changeBackgroundColour() {
document.getElementById("divId").style.backgroundColor = "red";
}
</script>
</body>
</html>

Example-31: Change the page colour in Every 5 sec in JavaScript

We can easily change page color in regular intervals ( every 5 second ) in JavaScript.

<p>In this example we can able to see in every 5 second the page colour is changing using JavaScript</p>
<style>
#fullScreenId {
position: relative;
height: 100%;
width: 100%;
}
</style>
<body>
<div id="fullScreenId"></div>
<script>
var div = document.getElementById("fullScreenId");
function getRandomColorInEach5Sec() {
var letters = '0123456789ABCDEF';
var randomColor = '#';
for (var i = 0; i < 6; i++ ) {
randomColor += letters[Math.floor(Math.random() * 16)];
}
return randomColor;
}
function chnageTheFullScreenColour(){
div.style.backgroundColor= getRandomColorInEach5Sec();
}
setInterval(chnageTheFullScreenColour,1000);
</script>
</body>
</head>
</html>

Example-32: Display Message every 3 second using Javascript

By using JavaScript we can display message in regular intervals using JavaScript like below:

<!DOCTYPE html>
<html>
<body>
<p>After Click on button after 3 second we can able to see the text</p>
<button onclick="setTimeout(displayTextIn3SecondAfterClickOnButton, 3000);">Click On It</button>
<p id="pId"></p>
<script>
function displayTextIn3SecondAfterClickOnButton() {
document.getElementById("pId").innerHTML = document.write("Enjoy Top 51 JavaScript Example");
}
</script>
</body>
</html>

Example-33: JavaScript get max value in array of objects

In JavaScript, we can easily get max number in an array of objects. Below is the code which will give the max number in the array.

<!DOCTYPE html>
<html>
<body>
<p>By using Math.max.apply method we can find out the maximum array value</p>
<p>The maximum aray value is:</p>
<p id="pId"></p>
<script>
var marks = [40, 95, 70, 45, 75, 55];
document.getElementById("pId").innerHTML = maximumArayValue(marks);
function maximumArayValue(array) {
return Math.max.apply(null, array);
}
</script>
</body>
</html>
JavaScript get max value in array of objects
javascript get max value in array of objects

Example-34: Sort and Reverse an array of Objects using JavaScript

Below JavaScript examples, it shows how to sort and reverse an array of objects in JavaScript by using the sort() and reverse() method.

<!DOCTYPE html>
<html>
<body>
<p>The reverse() method reverses the elements in an array.</p>
<p>By combining sort() and reverse() you can sort an array in descending order.</p>
<button onclick=”sortAndReverseArrayValue()”>Click</button>
<p id=”pId”></p>
<script>
var banksOfIndis = [“CentralBankOfIndia”,”AndhraBank”,”BankOfBaroda”,”CanaraBank”,”AllhabadBank”];
document.getElementById(“pId”).innerHTML = banksOfIndis;
function sortAndReverseArrayValue() {
banksOfIndis.sort();
banksOfIndis.reverse();
document.getElementById(“pId”).innerHTML = banksOfIndis;
}
</script>
</body>
</html>
Sort and Reverse an array of Objects using JavaScript
javascript example: Sort and Reverse an array of Objects

Example-35: Find index of Largest value in An Array in JavaScript

This JavaScript example explains how to find index of largest value in an array in JavaScript.

<!DOCTYPE html>
<html>
<body>
<p>In this example we can able to check the index value of largest array value</p>
<script>
var marks = [30, 100, 50, 90, 40];
function IndexValueOfALargestArrayValue(array){
var startingValue = 1;
var maximumValue = 0;
for(startingValue; startingValue < array.length; startingValue++){
if(array[maximumValue] < array[startingValue]){
maximumValue = startingValue;
}
}
return maximumValue;
}
document.write("The largest Number Index value is:" +IndexValueOfALargestArrayValue(marks));
</script>
</body>
</html>
Find index of Largest value in An Array in JavaScript
how to find the index of the largest number in an array javascript

Example-36: Try and Catch in JavaScript

This JavaScript example explains how to use try and catch in JavaScript. Try catch block is necessary for catching errors in JavaScript code.

<html>
<body>
<p id="pId"></p>
<script>
var x;
try {
x = y + 1;
document.write(x);
}
catch(err) {
document.write(err);
}
</script>
</body>
</html>
Try and Catch in JavaScript
try catch javascript best practices

Example-37: Return Boolean value of an Integer In JavaScript

This JavaScript example shows how we can return boolean value of an integer express in JavaScript.

<!DOCTYPE html>
<html>
<body>
<p>Click on the buton to check the boolean value of 100/10<p>
<button onclick="boleanValueOfANumber()" id="btnClick">Click</button>
<script>
function boleanValueOfANumber()
{
var x = 100;
var y=10;
var booleanValue=Boolean(100/10);
document.write(booleanValue);
}
</script>
</body>
</html>

We can able to see in the output is “true”.

Example-38: JavaScript Check an object is an array or not

We can check an object is an array or not in JavaScript by using the isArray() method. The isArray() method output will display true or false value.

<!DOCTYPE html>
<html>
<body>
<p>Click the button to check if "fruits" is an array.</p>
<button onclick="checkArrayValueOrNot()" id="btnClick">Click </button>
<p id="demo"></p>
<script>
function checkArrayValueOrNot() {
var states =["Maharashtra","Tamil Nadu","Uttar Pradesh","West Bengal","Delhi"];
var x = document.getElementById("demo");
x.innerHTML = Array.isArray(states);
}
</script>
</body>

Example-39: Print Stars in Pyramid Structure Using JavaScript

The javascript example explains how to print stars in pyramid structure in javascript.

<html>
<head>
<p>51 Top JavaScript Example: Print start in PyramidStructure using JavaScript</p>
<body>
<button onclick="printStarInPyramidStructure()" id="btnClick">Click me</button>
<script>
function printStarInPyramidStructure()
{
var rows=5;
for(var i=1;i<=rows;i++)
{
for(var j=1;j<=i;j++)
{
document.write(" * ");
}
document.write("<br/>");
}
}
</script>
</body>
</head>
</html>
Pyramid Structure Using JavaScript
how to print star pattern in javascript

Example-40: Display Table Number in JavaScript

We can display table number in JavaScript.

<html>
<head>
</head>
<body style="text-align: center;">
<p><input type="text" id="txtNumber" placeholder="Enter number"/></p>
<p><input type="button" value="Print Table" onclick='displayNumberInTable()'/>
<p id="tableId"></p>
<script type="text/javascript">
function displayNumberInTable(){
var n = Number(document.getElementById('txtNumber').value);
for(var i=1; i<=10; i++){
var table= document.getElementById('tableId');
table.innerHTML += (n*i) + "<br/>"
}
}
</script>
</body>
</html>

Example-41: JavaScript Display Tooltip message

We can display tooltip messages on mouse over in JavaScript. Below is the JavaScript code which will display tooltip message in JavaScript.

<html>
<head>
<style>
.name{
float:center;
margin:100px;
border:0.5px solid black;
}
.tooltip{
position:fixed;
margin:5px;
width:200px;
height:50px;
border:1px solid black;
display:none;
}
</style>
</head>
<body>
<div class = "name" onmouseover="show(tooltipFirstName)" onmouseout="hide(tooltipFirstName)">
FirstName:
<div class = "tooltip" id= "tooltipFirstName">
Give a Valid Name
</div>
</div>
<div class = "name" onmouseover="show(tooltipQualification)" onmouseout="hide(tooltipQualification)">
Qualification:
<div class = "tooltip" id= "tooltipQualification">
Enter your Qualification
</div>
</div>
<div class = "name" onmouseover="show(tooltipAdress)" onmouseout="hide(tooltipAdress)">
Permanenet Adress:
<div class = "tooltip" id= "tooltipAdress">
Give Your proper Permanenet address
</div>
</div>
<script>
function show (element) {
element.style.display="block";
}
function hide (element) {
element.style.display="";
}
</script>
</body>

Example-42: Reload page JavaScript

Reload is nothing but a method is used to reload the curent document. Below is the JavaScript code which will reload a page on button click. Once you click on the button, it will reload the page.

<!DOCTYPE html>
<html>
<body>
<p>Top 51 JavaScript Example</p>
<p>This code is reload the page again</p>
<button onclick="ReloadThepage()" id="btnClick">Click Here To Reload The Page</button>
<script>
function ReloadThepage() {
location.reload();
}
</script>
</body>
</html>

Example-43: Break and Continue in JavaScript

This javascript exampl, you will see how to use break and continue in JavaScript.

JavaScript Break

This javascript example explains how to use break keyword.

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button onclick="breakStatementExample()" id="btnClick">Click</button>
<script>
function breakStatementExample()
{
var x;
for ( x=0; x<=15; x++) {
if(x==10)
{
break;
}
if (x === 0)
{
document.write(x +" "+ "is"+" " + "an" + " " + "even number"+ "<br>");
}
else if (x % 2 === 0) {
document.write(x + " "+ "is"+ " " + "an" + " " + "even number"+ "<br>");
}
else {
document.write(x + " "+ "is"+ " " + "a" + " " + "odd number"+ "<br>" );
}
}
}
</script>
</body>
</html>
Break and Continue in JavaScript
javascript break if

JavaScript Continue

This javascript example explains how you can use Continue keyword.

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button onclick="breakStatementExample()" id="btnClick">Click</button>
<script>
function breakStatementExample()
{
var x;
for ( x=0; x<=15; x++) {
if (x === 10) {
continue;
}
if (x === 0)
{
document.write(x +" "+ "is"+" " + "an" + " " + "even number"+ "<br>");
}
else if (x % 2 === 0) {
document.write(x + " "+ "is"+ " " + "an" + " " + "even number"+ "<br>");
}
else {
document.write(x + " "+ "is"+ " " + "a" + " " + "odd number"+ "<br>" );
}
}
}
</script>
</body>
</html>
JavaScript Continue
javascript continue foreach

Example-44: JavaScript Conditional Operator

This javascript example explains how to use conditional operator. This particular example user will enter his or her age and by using conditional operation it will check if the user’s age more than 18 years or not. If user’s age is greater than 18 years then we will show an alert message that “Eligibel for blood donation” else “Not eligibel for blod donation”.

<!DOCTYPE html>
<html>
<body>
<p>This example will display eligible for blod donation or not, Enter age in the text box</p>
<input id="txtage" />
<button onclick="exampleOfTernaryOpearator()" id="btnClick">Submit</button>
<p id="pId"></p>
<script>
function exampleOfTernaryOpearator() {
var minimumAge, donateable;
minimumAge = Number(document.getElementById("txtage").value);
if (isNaN(minimumAge)) {
donateable = "Input should be an integer value";
} else {
donateable= (minimumAge >18) ? "Eligibel for blood donation" : "Not eligibel for blod donation";
}
document.getElementById("pId").innerHTML =donateable;
}
</script>
</body>
</html>

Example-45: Example of this KeyWord in JavaScript

This javascript example shows how we can use this keyword inside javascript functions.

<!DOCTYPE html>
<html>
<body>
<p id="pId"></p>
<script>
// Create an object:
var MobilePhone= {
brandName: "Samsung",
modelNumber: 35566,
size:6,
fullName : function() {
return this.brandName +" "+"mobilephone"+ " " +"model number"+" "+ this.modelNumber;
}
};
// Display data from the object:
document.getElementById("pId").innerHTML = MobilePhone.fullName();
</script>
</body>
</html>

Example-46: JavaScript Validation API

This javascript example explains how we can use JavaScript validations API.

<!DOCTYPE html>
<html>
<body>
<p>51 JavaScript Examples: Form Validation</p>
<p>Price of SharePoint Book:</p>
<input id="txtNumber" type="number" min="200" max="500" required>
<button onclick="formValidation()" id="btnClick">Click</button>
<p>Price of SharePoint book must be in between 200 to 500</p>
<p id="pId"></p>
<script>
function formValidation() {
var inputValue = document.getElementById("txtNumber");
if (!inputValue.checkValidity()) {
document.getElementById("pId").innerHTML = inputValue.validationMessage;
}
else
{
document.getElementById("pId").innerHTML = "Input is valid";
}
}
</script>
</body>
</html>
JavaScript Validation API
form validation using javascript code

Example-47: JavaScript Set dropdown value on Button Click

This JavaScript example explains how we can set dropdown value on button click. Here I have a dropdown list which has some values and on one button click I will set a particular value using JavaScript.

<!DOCTYPE html>
<html>
<body>
Select your favorite fruit:
<select id="strongStateInIndia">
<option value="Karnataka">Karnataka</option>
<option value="Uttarpradesh">Uttarpradesh</option>
<option value="Andhrapradesh">Andhrapradesh</option>
</select>
<button type="button" onclick="setTheDropdownValue()" id="btnClick">Click</button>
<script>
function setTheDropdownValue() {
document.getElementById("strongStateInIndia").value = "Karnataka";
}
</script>
</body>
</html>
JavaScript Set dropdown value on Button Click
get selected value of dropdown in javascript on button click

Example-48: Display Images Based on User Selection

This javascript example explains, how to display images based on user selection using JavaScript. Here I have uploaded two images and asked users to enter a number (1-2). Based on user’s selection it will display the image.

<html>
<head>
<body>
<p>Top 51 JavaScript Example:Pick a number and as per the number automatically image is displaying</p>
<img name="wave" src="https://onlysharepoint2013.sharepoint.com/sites/Raju/tsinfo/SiteAssets/Wavepic.jpg" width="260" height="250" >
<script language="JavaScript">
var waveImage=new Array("https://onlysharepoint2013.sharepoint.com/sites/Raju/tsinfo/SiteAssets/leavespic.jpg", "https://onlysharepoint2013.sharepoint.com/sites/Raju/tsinfo/SiteAssets/waterfallFromTop.jpg");
var n = prompt("Pick a number 1 or 2");
n--;
document.images["wave"].src = waveImage[n];
</script>
</body>
</html>

Example-49: JavaScript Bind Arrays Value into Dropdown list

This javascript examples explain how to bind a dropdown list from an array in JavaScript. Here I have a country array whose values we are binding into a dropdownlist.

<html >
<head>
<p>51 Top JavaScript Example: Bind dropdown list from an array</p>
</head>
<body>
<input type="button" id="btnCountry" value="Populate the country name" onclick="populateCountryList()" />
<select id="ddlCountry">
</select>
<script type="text/javascript">
function populateCountryList() {
var country = [
{ Name: "India" },
{Name: "China" },
{ Name: "USA" },
{ Name: "Australia" }
];
var ddlCountry = document.getElementById("ddlCountry");
for (var i = 0; i < country.length; i++) {
var option = document.createElement("OPTION");
option.innerHTML = country[i].Name;
ddlCountry.options.add(option);
}
}
</script>
JavaScript Bind Arrays Value into Dropdown list
values in dropdownlist using javascript

Example-50: javascript browser detection

This javascript example explains how to detect browser name in javascript. On a button click we are checking here which browser user is using, in javascript.

<!DOCTYPE html>
<html>
<body>
<p>Get browser name using JavaScript</p>
<button onclick="getBrowserName()">Get Browser Name</button>
<script>
function getBrowserName() {
if((navigator.userAgent.indexOf("Opera") || navigator.userAgent.indexOf('OPR')) != -1 )
{
alert('Opera');
}
else if(navigator.userAgent.indexOf("Chrome") != -1 )
{
alert('Google Chrome');
}
else if(navigator.userAgent.indexOf("Safari") != -1)
{
alert('Safari');
}
else if(navigator.userAgent.indexOf("Firefox") != -1 )
{
alert('Mozilla Firefox');
}
else if((navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true ))
{
alert('Internet Explorer');
}
else
{
alert('Other');
}
}
</script>
</body>
</html>

Example-51: How to sort array value using sort() method in JavaScript

We can easily sort array javascript, below is the code to sort an array values using JavaScript sort() method.

<!DOCTYPE html>
<html>
<body>
<p>sort array value in alphabatical order</p>
<p>Click on button click we can see our short array value</p>
<button onclick="banksNameInAlphabaticalOrder()" id="btnClick">Click</button>
<p id="pId"></p>
<script>
var banksOfIndis = ["CentralBankOfIndia","AndhraBank","BankOfBaroda","CanaraBank","AllhabadBank"];
function banksNameInAlphabaticalOrder() {
banksOfIndis.sort();
document.getElementById("pId").innerHTML = banksOfIndis;
}
</script>
</body>
</html>

The above code will sort an array of objects in alphabetical order.

Download JavaScript Examples PDF

You can download JavaScript examples PDF free.

You may like following tutorials:

In this tutorial we saw 51 javascript examples pdf which you can download for free.

Donwload Hub site pdf

Download SharePoint Online Tutorial PDF FREE!

Get update on Webinars, video tutorials, training courses etc.

>