JavaScript Examples [51 Useful Examples]

JavaScript is powerful for web developers, offering countless ways to enhance website functionality. It provides the building blocks for modern web applications, from handling simple arithmetic operations to creating complex interactive elements. These practical examples can help you learn the fundamentals of variables, operators, loops, and other essential JavaScript concepts.

As a JavaScript developer, you should be familiar with its core features, such as arithmetic operators (addition, subtraction, multiplication, division), variables, output methods, and commenting techniques.

Table of Contents

What is JavaScript?

JavaScript is a lightweight, object-based scripting language that adds functionality to HTML code. It makes web pages interactive, allowing users to engage with content dynamically.

This versatile language serves multiple purposes. Developers use JavaScript for:

  • Game development
  • Mobile app creation
  • Making HTML forms dynamic
  • Building client-side dynamic pages

One major benefit of JavaScript is its universal browser compatibility. All major browsers support it, including:

  • Chrome
  • Firefox
  • Edge
  • Safari
  • Opera

JavaScript runs on any operating system, including Windows, Linux, and Mac. To use JavaScript, developers simply add code within <script> tags in an HTML file. When the browser loads the HTML, it automatically runs the JavaScript code.

With features like let introduced in ECMAScript 2015 (ES6), JavaScript continues to evolve as a powerful tool for web development.

Check out How to Check Which Radio Button is Selected Using jQuery?

Editors For JavaScript

Choosing the right editor can improve your coding experience when working with JavaScript. Several popular options exist:

  • VS Code – Feature-rich with excellent extensions
  • Sublime Text – Fast and lightweight
  • Atom – Highly customizable
  • Notepad++ – Simple but effective
  • Komodo Edit – Good for beginners

These editors offer syntax highlighting, code completion, and debugging tools that make JavaScript development easier and more efficient.

How to Start with JavaScript?

JavaScript adds interactivity to websites. To begin coding in JavaScript, you need to understand a few basic principles.

You must place JavaScript code between <script> and </script> tags in your HTML document. These scripts can go in either the <head> or <body> section, or both. Here’s a simple example:

<script>
  alert("Hello, welcome to JavaScript!");
</script>

There are two main ways to include JavaScript in your webpage:

  1. Directly in HTML – Writing code between script tags
  2. External files – Storing code in separate .js files

Using external files is often better for organization. To link an external JavaScript file:

<script src="yourFileName.js"></script>

You can create interactive elements like buttons that trigger JavaScript functions:

<button onclick="showMessage()">Click Me</button>

The function showMessage() would be defined in your JavaScript code to perform a specific action when the button is clicked.

For beginners, start with simple tasks like displaying alerts or changing text content before moving to more complex projects.

JavaScript Examples

Check out Execute Functions After Page Load Using jQuery

Now, let me show you the 51 useful examples of JavaScript.

Example-1: Display Alert in JavaScript

JavaScript offers several ways to create pop-up dialog boxes to interact with users. These dialog boxes help show messages, get confirmations, or collect user input while browsing your website.

Display Alert Box Using JavaScript

The alert box is the simplest dialog box in JavaScript. It shows a message and has an OK button to close it.

function showAlert() {
  alert("Created Account");
}

When this function runs, a small box appears on screen with the message “Created Account” and an OK button. Users must click OK to continue using the page.

You can add line breaks in your alert messages using the \n character:

alert("Hello\nHow are you?");

This creates an alert with text on two lines.

A basic example of an alert in a form:

<input type="text" id="txtFirstName" name="firstname">
<input type="text" id="txtLastName" name="lastname">
<button onclick="showAlert()">Submit</button>

When users click Submit, they’ll see the alert message.

Display Confirmation Box Using JavaScript

A confirmation box asks users to verify or accept something. It displays both OK and Cancel buttons.

function showConfirmationMessage() {
  var result = confirm("Do you want to use this account?");
  
  if (result == true) {
    alert("Account created successfully");
  } else {
    alert("Sorry, try again. Your account was not created");
  }
}

The confirm() function returns:

  • true if the user clicks OK
  • false if the user clicks Cancel

This is useful when you need users to verify actions before proceeding.

Display Prompt Box Using JavaScript

The prompt box collects text input from users through a dialog box.

function showPromptBox() {
  var username = prompt("Please enter your username", "");
  var message;
  
  if (username == null || username == "") {
    message = "User cancelled the prompt.";
  } else {
    message = "Hello " + username + "! Welcome to your SharePoint site";
  }
  
  document.getElementById("messageArea").innerHTML = message;
}

The prompt function takes two parameters:

  • The message to display
  • A default value for the input field (can be empty)

This dialog box includes a text input field, an OK button, and a Cancel button.

Read Handle Dropdown Change Event in jQuery

Example-2: Mouse Movement Events in JavaScript

JavaScript offers powerful events that respond to mouse movements. Two key events are onmouseover and onmouseout. These events trigger functions when a user’s mouse enters or leaves an element.

Here’s how they work:

  • onmouseover: Fires when a mouse pointer moves onto an element
  • onmouseout: Fires when a mouse pointer moves away from an element

You can use these events to create interactive image effects. For example:

function makeImageLarger(image) {
  image.style.height = "64px";
  image.style.width = "64px";
}

function makeImageSmaller(image) {
  image.style.height = "32px";
  image.style.width = "32px";
}

To implement these functions, add the events directly to your HTML:

<img onmouseover="makeImageLarger(this)" 
     onmouseout="makeImageSmaller(this)"
     src="image.jpg" width="32" height="32">

You can reverse these effects by swapping the events. This creates the opposite effect, where images shrink on hover and enlarge when the mouse leaves.

These mouse events pair well with onclick for creating fully interactive elements that respond to different types of user interactions.

Read How to Check if a Checkbox is Checked Using jQuery

Example-3: Using JavaScript for Key Press Alerts

JavaScript can create alert messages when users press keys in text boxes. To implement this function, add an event listener to your input element.

<!DOCTYPE html>
<html>
<body>
  <p><b>Key Press Alert Example</b></p>
  <input type="text" id="textInput" onkeypress="showAlert()">
  
  <script>
    function showAlert() {
      alert("You pressed a key in the text box!");
    }
  </script>
</body>
</html>

This code creates a simple text box that displays an alert whenever any key is pressed within it.

Example-4: JavaScript Form Validation Examples

Here are some form validation examples of JavaScript.

Empty Field Check

JavaScript makes it easy to check if users have filled out required fields. This simple validation stops form submission when important information is missing.

function checkRequired() {
  if(document.getElementById('nameField').value.trim() == "") {
    alert('Please fill out this field');
    nameField.focus();
    return false;
  }
  alert("Form submitted successfully");
  return true;
}

This code checks if a text field is empty when the user clicks submit. If it’s empty, an alert appears and the cursor moves to the empty field.

Email Format Verification

Email validation ensures users enter properly formatted email addresses before submitting forms.

function validateEmail() {
  const emailPattern = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
  const userEmail = document.getElementById('emailField').value;
  
  if(userEmail.match(emailPattern)) {
    alert("Email format is valid");
    return true;
  } else {
    alert("Please enter a valid email address");
    emailField.focus();
    return false;
  }
}

The pattern checks for the typical email format with an @ symbol and domain extension.

Text-Only Input Control

Sometimes forms need fields that only accept letters. This validation prevents numbers and special characters.

function checkLettersOnly() {
  const letterPattern = /^[a-zA-Z]+$/;
  const textInput = document.getElementById('lettersField').value;
  
  if(textInput.match(letterPattern)) {
    alert("Input contains only letters");
    return true;
  } else {
    alert("Please use letters only (A-Z, a-z)");
    lettersField.focus();
    return false;
  }
}

This function blocks submission when non-letter characters are entered.

Numeric Value Validation

This validation ensures users enter digits only for fields that should only contain numbers (like age or quantity).

function checkNumbersOnly() {
  const numberPattern = /^[0-9]+$/;
  const numInput = document.getElementById('numberField').value;
  
  if(numInput.match(numberPattern)) {
    alert("Input contains only numbers");
    return true;
  } else {
    alert("Please enter numbers only");
    numberField.focus();
    return false;
  }
}

This helps prevent errors in calculations or database entries that require numerical data.

Alphanumeric Input Validation

For usernames or product codes that allow both letters and numbers, alphanumeric validation is useful.

function checkAlphanumeric() {
  const alphaNumPattern = /^[0-9a-zA-Z]+$/;
  const userInput = document.getElementById('alphaNumField').value;
  
  if(userInput.match(alphaNumPattern)) {
    alert("Input contains only letters and numbers");
    return true;
  } else {
    alert("Please use only letters and numbers");
    alphaNumField.focus();
    return false;
  }
}

This function blocks special characters while allowing both text and numbers.

IP Address Format Check

IP address validation ensures users enter correctly formatted network addresses.

function validateIPAddress() {
  const ipPattern = /^(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]?)$/;
  const ipInput = document.getElementById('ipField').value;
  
  if(ipInput.match(ipPattern)) {
    alert("Valid IP address format");
    return true;
  } else {
    alert("Please enter a valid IP address");
    ipField.focus();
    return false;
  }
}

The pattern checks for four numbers between 0-255, separated by periods – the standard IPv4 format.

Read Call a JavaScript Function When a Checkbox is Checked or Unchecked

Example-5: Retrieve Today’s Date in JavaScript

JavaScript makes it easy to get the current date and time using the built-in Date object. When you create a new Date instance without parameters, it automatically captures the current date and time.

Here’s how to display different date components on a webpage:

<script>
  var date = new Date();
  
  // Get individual date components
  document.getElementById("currentDay").innerHTML = "Today's date: " + date.getDate();
  document.getElementById("currentMonth").innerHTML = "Current month: " + (date.getMonth()+1);
  document.getElementById("currentYear").innerHTML = "Current year: " + date.getFullYear();
  
  // Format full date (YYYY-MM-DD)
  document.getElementById("fullDate").innerHTML = "Full date: " + 
    date.getFullYear() + '-' + (date.getMonth()+1) + '-' + date.getDate();
    
  // Get current time (HH:MM:SS)
  document.getElementById("time").innerHTML = "Current time: " + 
    date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
</script>

When this code runs, it will display the day (10), month (5), year (2025), formatted date (2025-5-10), and the exact time at execution.

Example-6: Reversing Arrays in JavaScript

In JavaScript, we can easily flip the order of elements in an array using the built-in reverse() method. This method changes the original array by switching the positions of elements.

Here’s a simple example showing how to reverse an array of seasons:

var seasons = ["Summer", "Winter", "Monsoon", "Spring"];

// Before reversal
console.log(seasons); // Output: Summer, Winter, Monsoon, Spring

// Reverse the array
seasons.reverse();

// After reversal
console.log(seasons); // Output: Spring, Monsoon, Winter, Summer

The reverse() method is useful when you need to display data in reverse order or change the sequence of elements in your array.

Example-7: JavaScript Merging Arrays with concat()

The concat() method provides a simple way to join arrays in JavaScript. This method doesn’t change the original arrays but returns a new array containing all the elements from the combined arrays.

Let’s see how to merge two arrays containing days of the week:

function mergeArrays() {
    var firstPart = ["Sunday", "Monday"];
    var secondPart = ["Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    var fullWeek = firstPart.concat(secondPart);
    
    return fullWeek;
}

This creates a new array with all seven days in order. The original arrays remain unchanged. Developers can use this technique when they need to combine data from different sources without altering the original collections.

Check out Create an Expandable Table with Collapsible Rows Using HTML, CSS, and JavaScript

Example-8: Reverse String in JavaScript

One common task in JavaScript is reversing strings. This operation can be useful for data manipulation or solving programming challenges.

Here’s a simple function that reverses a string:

function reverseStringMethod(str) {
    var result = "";
    for (var i = str.length - 1; i >= 0; i--) {
        result += str.charAt(i);
    }
    return result;
}

This function works by looping through each character from the end of the string to the beginning. When applied to “Bijay Kumar”, it produces “ramuK yajiB”.

Alternative Method:

function quickReverse(str) {
    return str.split("").reverse().join("");
}

Example-9: JavaScript Opening Pages with window.open()

The window.open() method lets you create new browser windows or tabs from your JavaScript code. Here’s a simple example:

<!DOCTYPE html>
<html>
<body>
  <p>Click the button to open a new website in a separate window.</p>
  <button onclick="launchNewWindow()" id="openButton">Open Website</button>
  
  <script>
    function launchNewWindow() {
      window.open("https://www.example.com/");
    }
  </script>
</body>
</html>

When users click the button, a new browser window or tab opens with the specified URL. The behavior (new tab or window) depends on browser settings.

Check out Create a Registration Form with HTML, CSS, and JavaScript

Example-10: if else statement in JavaScript

The if/else statement in JavaScript lets you run code based on whether a condition is true or false. You can create decisions in your programs using these statements.

var daysInFebruary = 29;

if(daysInFebruary == 29) {
    document.write("This year is a leap year");
} else {
    document.write("This is not a leap year");
}

In this example, the program checks if February has 29 days. If true, it identifies the year as a leap year. Otherwise, it indicates it’s not a leap year.

Common comparison operators include:

  • < (less than)
  • <= (less than or equal)
  • > (greater than)
  • >= (greater than or equal)
  • == (equal)
  • != (not equal)

Example-11: Printing Pages with JavaScript

JavaScript offers a simple way to print web pages using the window.print() method. When a user clicks a button with this function attached, the browser’s print dialog opens automatically.

Here’s a basic example:

<button onclick="printThisPage()">Print This Page</button>

<script>
function printThisPage() {
  window.print();
}
</script>

This code creates a button that triggers the print dialog when clicked. The function is clean and easy to implement on any webpage.

Read Create Interactive HTML Forms with CSS and JavaScript

Example-12: Insert Element in Array JavaScript

JavaScript offers several methods to add elements to arrays. The push() method is commonly used to insert elements at the end of an array.

Here’s a simple example:

var days = ["Sunday", "Monday", "Tuesday", "Wednesday"];

function pushElementToArray() {
  days.push("Saturday");
  // Updates the array by adding "Saturday" at the end
}

Other useful array insertion methods include:

  • unshift() – adds elements to the beginning
  • splice(index, 0, item) – inserts at a specific position

These methods make array manipulation straightforward in JavaScript applications.

Example-13: Get Current URL in JavaScript

JavaScript makes it easy to find the URL of your current page. The most direct way is using window.location.href, which gives you the complete URL.

Here’s a simple example:

<p id="urlDisplay"></p>

<script>
  document.getElementById("urlDisplay").innerHTML = 
    "Current page URL: " + window.location.href;
</script>

This code creates a paragraph that shows the full URL of the page you’re viewing. The window.location object contains other useful properties for working with URLs as well.

Example-14: Getting Elements By Class Name in JavaScript

The getElementsByClassName() method helps find HTML elements that share the same class name. This tool is very useful when you want to work with multiple elements at once.

Consider this simple example:

function RetriveByClassName() {
  var x = document.getElementsByClassName("myclass");
  alert(x[0].innerHTML);
}

This function finds all elements with the class “myclass” and displays the content of the first one in an alert box. The method returns an HTMLCollection object, which works like an array with numbered indexes starting at 0.

Example-15: JavaScript’s getElementsByName() Method

The getElementsByName() method lets you find HTML elements using their name attribute. This method returns a NodeList of matching elements.

Here’s how you might use it to check a checkbox:

function selectCheckbox() {
  var pets = document.getElementsByName("domesticAnimal");
  
  for (var i = 0; i < pets.length; i++) {
    if (pets[i].type == "checkbox") {
      pets[i].checked = true;
    }
  }
}

When triggered by a button click, this function finds all elements with the name “domesticAnimal” and checks them if they’re checkboxes.

Example-16: Controlling Browser Navigation with JavaScript

Disabling Back Navigation in Browsers

JavaScript offers ways to handle browser navigation controls. To disable the back button functionality, we can use the window.history.back() method in our code.

<button onclick="preventBackNavigation()">Back</button>

<script>
function preventBackNavigation() {
  window.history.forward();
}
</script>

This code creates a button that, when clicked, prevents users from going back. The function pushes users forward in their browsing history, making it impossible to return to previous pages.

Preventing Forward Navigation in Browsers

Similarly, we can control forward navigation using the window.history.forward() method:

<button onclick="blockForwardNavigation()">Forward</button>

<script>
function blockForwardNavigation() {
  window.history.forward();
}
</script>

This technique is useful for online exams, sensitive forms, and payment processes where you need to prevent users from navigating away and potentially causing data issues.

Example-17: Controlling Dropdown Lists with JavaScript

Disabling Dropdown Lists using JavaScript

You can disable a dropdown list by setting its disabled property to true using JavaScript. This prevents users from interacting with the dropdown until it’s enabled again.

Here’s a simple example:

<select id="petOptions">
  <option>Cats</option>
  <option>Dogs</option>
</select>

<button onclick="makeDropdownInactive()">Disable Dropdown</button>

<script>
function makeDropdownInactive() {
  document.getElementById("petOptions").disabled = true;
}
</script>

When the button is clicked, the dropdown becomes inactive and grayed out.

Enabling Dropdown Lists using JavaScript

To enable a dropdown that has been disabled, set its disabled property to false. This restores the dropdown’s functionality.

<select id="petOptions">
  <option>Cats</option>
  <option>Dogs</option>
</select>

<button onclick="makeDropdownActive()">Enable Dropdown</button>

<script>
function makeDropdownActive() {
  document.getElementById("petOptions").disabled = false;
}
</script>

This technique is useful when certain form elements should only be active under specific conditions.

Example-18: Disable mouse right click using JavaScript

JavaScript allows you to disable the right-click function on webpages. This can be useful for protecting content from being easily copied or when you want to control how users interact with your site.

Here’s a script that prevents right-clicking:

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;
};

The script works by:

  • Capturing mouse events
  • Checking which mouse button was pressed
  • Returning false to prevent the default context menu

JavaScript Date Countdown Tool

A countdown timer is simple to create with JavaScript. This tool helps track time until a specific date.

Here’s the basic code structure for a countdown timer:

// Set target date
var targetDate = new Date("Jan 5, 2026").getTime();

// Update timer every second
var timer = setInterval(function() {
  var now = new Date().getTime();
  var timeLeft = targetDate - now;
  
  // Calculate days, hours, minutes, seconds
  var days = Math.floor(timeLeft / (1000 * 60 * 60 * 24));
  var hours = Math.floor((timeLeft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((timeLeft % (1000 * 60)) / 1000);
  
  // Display timer
  document.getElementById("timer").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s";
  
  // Handle expiration
  if (timeLeft < 0) {
    clearInterval(timer);
    document.getElementById("timer").innerHTML = "EXPIRED";
  }
}, 1000);

This timer can be enhanced with JSON data for custom formatting or multiple countdown events.

Example-20: Checkbox Validation with JavaScript

This example demonstrates how to validate if a checkbox is checked using JavaScript. When a user clicks a button, the code checks the checkbox status and displays an appropriate message.

The HTML structure includes a checkbox input and a button that triggers the validation function:

<input type="checkbox" id="chkBox">
<button onclick="showCheckBoxAlert()" id="btnClick">Click</button>

The JavaScript function checks the checkbox state using the checked property:

function showCheckBoxAlert() {
  var x = document.getElementById("chkBox");
  if(!x.checked) {
    alert('Check box is unchecked');
  } else {
    alert('Check box is checked');
  }
  return false;
}

This validation is useful for forms requiring user agreement to terms or confirming selections before submission.

Example-21: Getting Query String Values in JavaScript

JavaScript makes it easy to extract query string values from URLs. Query strings appear after the “?” in a URL and contain parameters passed to a webpage.

Consider this example code that gets a specific parameter by name:

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];
    }
  }
}

To use this function, simply call it with the parameter name you want:

// Gets "WSSWebPartPage" from a URL like:
// example.com?VisibilityContext=WSSWebPartPage
var value = GetParameterValues("VisibilityContext");

A more modern approach uses URLSearchParams:

const urlParams = new URLSearchParams(window.location.search);
const value = urlParams.get('VisibilityContext');

Example-22: JavaScript Get or Set Radio Button Value

Getting Selected Radio Button Value

Radio buttons let users pick one option from a group. To find which radio button is selected, we use JavaScript to check the value property of the checked button.

Here’s a simple way to get a radio button’s value:

<input type="radio" name="Gender" onclick="getRadioValue(this)" value="Male"> Male
<input type="radio" name="Gender" onclick="getRadioValue(this)" value="Female"> Female

<script>
function getRadioValue(button) {
  alert(button.value);
}
</script>

When a user clicks on a radio button, the getRadioValue function shows the value of the selected option.

Setting Radio Button Value

JavaScript can also set a radio button’s checked state programmatically. This is useful when you need to pre-select options based on user preferences or other conditions.

<input type="radio" id="optionYes"> Yes
<input type="radio" id="optionNo"> No

<button onclick="selectOption('optionYes')">Select Yes</button>
<button onclick="selectOption('optionNo')">Select No</button>

<script>
function selectOption(id) {
  document.getElementById(id).checked = true;
}
</script>

The checked = true property marks the button as selected. This method works for any radio button you need to control through code.

Example-23: Getting Screen Height with JavaScript

JavaScript lets you find out the height of a user’s screen in pixels. This can be useful when designing responsive websites or applications.

Here’s a simple way to detect screen height:

function showScreenHeight() {
  var totalHeight = "Total Height: " + screen.height + "px";
  document.getElementById("pId").innerHTML = totalHeight;
}

When a user clicks a button linked to this function, it displays the screen height value. The screen.height property returns the total height of the user’s screen in pixels.

Example-24: Auto Refresh Page JavaScript

This example shows how to make a webpage refresh automatically using JavaScript. The code uses a function called AutoRefresh() that works with the setTimeout() method to reload the page after a set time.

<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>

In this code, the page will refresh every 3000 milliseconds (3 seconds) when loaded. The onload event in the body tag triggers the function.

Example-25: Convert Celsius Value to Fahrenheit Value in JavaScript

JavaScript makes temperature conversion easy with simple math formulas. The code below creates a two-way converter that works as you type values.

<p>Celsius Value: <input id="txtCelsius" onkeyup="convert('C')"></p>
<p>Fahrenheit Value: <input id="txtFahrenheit" onkeyup="convert('F')"></p>

The conversion function handles both directions:

  • Celsius to Fahrenheit: (C × 9/5) + 32
  • Fahrenheit to Celsius: (F - 32) × 5/9

The Math.round() function ensures whole numbers for easier reading. The onkeyup event makes the conversion happen instantly as users type.

Example-26: Getting Today’s Date in JavaScript

To show the current date in JavaScript, you can use the Date() object. This built-in feature easily captures the current date and time from your system.

<html>
<body>
  <p>Today's date is:</p>
  <p id="dateDisplay"></p>
  
  <script>
    var today = new Date();
    document.getElementById("dateDisplay").innerHTML = today;
  </script>
</body>
</html>

The code creates a new Date object and displays it in the HTML element with the “dateDisplay” ID.

Example-27: Scroll Down Event in JavaScript

The scroll event in JavaScript allows developers to detect when a user scrolls within an element or the entire page. This example demonstrates how to track scrolling activity within a specific div element.

To implement a scroll down tracker:

  1. Create a div with the overflow: scroll property
  2. Add an onscroll event handler to the div
  3. Use a counter variable to track scroll actions
<div onscroll="scrollDownEvent()">
    <!-- Content that exceeds the div height -->
</div>

<p>Scrolled <span id="pSpan">0</span> times.</p>

<script>
var x = 0;
function scrollDownEvent() {
    document.getElementById("pSpan").innerHTML = x += 1;
}
</script>

The JavaScript function scrollDownEvent() increments a counter each time scrolling occurs within the div. The counter value displays in a span element outside the scrollable area.

This technique works well for tracking user engagement with content. It can be useful for analytics, triggering animations, or loading additional content when users reach certain scroll positions.

Example-28: JavaScript Animation Example

This example shows how to create a simple animation using JavaScript. The code creates a small black box that moves diagonally across a larger pink container when a button is clicked.

The animation works by:

  • Setting up two containers with CSS positioning
  • Using setInterval() to update the position every 30 milliseconds
  • Incrementing the position values for both top and left properties
  • Stopping the animation when it reaches the bottom edge
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';
    }
  }
}

Example-29: Play and Pause Video in JavaScript

JavaScript’s built-in methods make controlling video playback simple. With just a few lines of code, you can add play and pause functionality to your web pages.

Here’s how to implement basic video controls:

<button id="playButton">Play Video</button>
<button id="pauseButton">Pause Video</button>
<video id="myVideo" width="320" height="240">
  <source src="sample-video.mp4" type="video/mp4">
</video>
const video = document.getElementById("myVideo");

document.getElementById("playButton").addEventListener("click", function() {
  video.play();
});

document.getElementById("pauseButton").addEventListener("click", function() {
  video.pause();
});

This code connects HTML buttons to JavaScript functions that control the video element. When users click the buttons, the video will play or pause accordingly.

Example-30: Change Background Color of Div Using JavaScript

JavaScript can easily modify a div’s background color. In this example, we create a blue div that changes to red when a button is clicked.

<div id="divId">Top 51 JavaScript examples.</div>
<button onclick="changeBackgroundColour()">Click it</button>

<script>
function changeBackgroundColour() {
    document.getElementById("divId").style.backgroundColor = "red";
}
</script>

The key is using the style.backgroundColor property with the element’s ID to change its color.

Example-31: Changing Page Color Every 5 Seconds with JavaScript

This example shows how to make a webpage that changes its background color automatically every few seconds using JavaScript. The code creates a full-screen div element that changes color randomly.

The process works in three main steps:

  1. Create the HTML structure with a full-screen div
  2. Write a function to generate random colors using hex codes
  3. Set up an interval timer to apply the new color regularly
// Function to generate random color
function getRandomColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

// Change background color at set intervals
setInterval(function() {
  document.getElementById("fullScreenId").style.backgroundColor = getRandomColor();
}, 5000);  // 5000 milliseconds = 5 seconds

This creates a simple yet eye-catching visual effect for your webpage.

Example-32: Display a Message every 3 seconds using JavaScript

JavaScript allows you to show messages at set time intervals. You can create a button that displays text after a delay.

Here’s how to make a message appear 3 seconds after clicking a button:

function displayMessage() {
  document.getElementById("messageArea").innerHTML = "Your message appears here!";
}

// Usage with button
<button onclick="setTimeout(displayMessage, 3000);">Show Message</button>
<p id="messageArea"></p>

The setTimeout() function waits 3000 milliseconds (3 seconds) before running the function.

Example-33: JavaScript Get Max Value in an Array of Objects

Finding the maximum value in an array of objects is a common task in JavaScript programming. You can use the Math.max() method combined with apply() to achieve this efficiently.

Here’s how to find the maximum value in a simple array:

var marks = [40, 95, 70, 45, 75, 55];

function maximumArrayValue(array) {
  return Math.max.apply(null, array);
}

// Result: 95

For arrays of objects, you can use the map() function to extract the specific property before finding the maximum:

const items = [{id: 1, value: 10}, {id: 2, value: 35}, {id: 3, value: 20}];
const maxValue = Math.max.apply(Math, items.map(item => item.value));
// Result: 35

Example-34: Sort and Reverse an Array of Objects Using JavaScript

JavaScript offers simple methods to arrange arrays in different orders. The sort() method organizes array elements alphabetically, while reverse() flips their order.

When working with arrays, you can combine these methods to create a descending sort:

// Array of Indian banks
var banksOfIndia = ["CentralBankOfIndia", "AndhraBank", "BankOfBaroda", "CanaraBank", "AllhabadBank"];

// Sort alphabetically then reverse
banksOfIndia.sort();     // Alphabetical order
banksOfIndia.reverse();  // Reverse to get descending order

This technique works with arrays of strings, numbers, and even objects when using a proper comparison function.

Example-35: Find Index of Largest Value in an Array in JavaScript

This example shows how to locate the index position of the largest number in a JavaScript array.

// Sample array
var marks = [30, 100, 50, 90, 40];

// Function to find index of largest value
function findLargestValueIndex(array) {
  var startIndex = 1;
  var maxIndex = 0;
  
  for(startIndex; startIndex < array.length; startIndex++) {
    if(array[maxIndex] < array[startIndex]) {
      maxIndex = startIndex;
    }
  }
  return maxIndex;
}

// Output the result
console.log("The largest number index is: " + findLargestValueIndex(marks));

The function compares each array element with the current maximum and updates the index when it finds a larger value. With our example array, it returns index 1 where the value 100 is stored.

Example-36: Try and Catch in JavaScript

JavaScript’s try-catch blocks help handle errors in your code. The try block contains code that might cause an error, while the catch block runs if an error occurs.

try {
  // Code that might cause an error
  x = y + 1;
  document.write(x);
} catch(err) {
  // Error handling code
  document.write(err);
}

This pattern prevents your program from crashing when errors happen. Instead, it lets you handle the error gracefully.

Example-37: Getting True or False from Numbers in JavaScript

In JavaScript, you can turn numbers into boolean values using the Boolean() function. Any non-zero number converts to true, while zero becomes false.

Here’s a simple example:

function checkNumberBoolean() {
    var result = Boolean(100/10);  // Evaluates to Boolean(10)
    return result;  // Returns true
}

Try this yourself with different numbers. Positive numbers, negative numbers, and decimals all return true. Only zero returns false.

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

In JavaScript, determining whether an object is an array can be done using the Array.isArray() method. This method returns a boolean value – true if the object is an array and false if it’s not.

Here’s a simple example:

function checkArrayValueOrNot() {
  var states = ["Maharashtra", "Tamil Nadu", "Uttar Pradesh", "West Bengal", "Delhi"];
  var result = Array.isArray(states);
  document.getElementById("demo").innerHTML = result;
}

When this function runs on a button click, it will display true because states is indeed an array. This method works in all modern browsers and provides a reliable way to verify array types in JavaScript.

Example-39: Print Stars in Pyramid Structure Using JavaScript

This JavaScript example shows how to create a pyramid pattern using star symbols. The code uses nested for loops to build the pyramid structure:

function printStarInPyramidStructure() {
    var rows = 5;
    for(var i = 1; i <= rows; i++) {
        for(var j = 1; j <= i; j++) {
            document.write(" * ");
        }
        document.write("<br/>");
    }
}

The outer loop controls the number of rows, while the inner loop prints stars based on the current row number. When triggered by a button click, this function displays a triangle pattern of stars.

Example-40: Display Table Number in JavaScript

This example shows how to create a multiplication table using JavaScript. The program takes a number from a user input field and displays its multiplication table from 1 to 10.

HTML Structure and JavaScript Function:

<input type="text" id="txtNumber" placeholder="Enter number">
<input type="button" value="Print Table" onclick="displayNumberInTable()">
<p id="tableId"></p>

The JavaScript function loops through numbers 1-10, multiplies each by the user’s input, and adds the results to the page:

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>";
  }
}

When a user enters a number and clicks the button, the multiplication table appears on the page.

Example-41: JavaScript Display Tooltip Messages

Tooltips help users understand elements on a webpage by showing helpful text when hovering over items. You can create tooltips with simple JavaScript and CSS.

This example shows tooltips appearing when users hover over form fields:

<div class="name" onmouseover="show(tooltipFirstName)" onmouseout="hide(tooltipFirstName)">
    FirstName:
    <div class="tooltip" id="tooltipFirstName">Give a Valid Name</div>
</div>

The JavaScript functions that control the tooltip visibility are straightforward:

function show(element) {
    element.style.display = "block";
}

function hide(element) {
    element.style.display = "";
}

CSS positions the tooltips and sets their default hidden state:

  • .tooltip elements are initially hidden (display:none)
  • When activated, they appear as small boxes with helpful guidance text

Example-42: Reload Page JavaScript

JavaScript offers a simple way to refresh a webpage. The location.reload() method loads the current page again when called. Here’s how you can create a button that reloads your page:

<!DOCTYPE html>
<html>
<body>
  <p>Page content goes here</p>
  <button onclick="reloadPage()">Reload This Page</button>
  
  <script>
    function reloadPage() {
      location.reload();
    }
  </script>
</body>
</html>

When users click the button, the page refreshes completely, showing updated content if available.

Example-43: Loop Control in JavaScript

Stopping Loops with Break

The break statement lets you exit a loop early. When JavaScript hits a break statement, it jumps out of the loop completely.

Here’s what the break statement does in a loop:

for (var x = 0; x <= 15; x++) {
  if (x == 10) {
    break;  // Loop stops when x equals 10
  }
  // Code to check and display odd/even numbers
}

When this code runs, it will only show numbers 0-9. Once the value reaches 10, the break statement runs and the loop ends right away.

Skipping Steps with Continue

The continue statement skips the current loop iteration and moves to the next one. Unlike break, it doesn’t exit the entire loop.

for (var x = 0; x <= 15; x++) {
  if (x === 10) {
    continue;  // Skip only when x equals 10
  }
  // Code to check and display odd/even numbers
}

This code will display all numbers from 0-15 except for 10. When x equals 10, the continue statement skips the rest of that iteration.

Example-44: JavaScript Conditional Operator

The conditional operator in JavaScript is a useful shortcut for simple if-else statements. It takes three operands: a condition, a value if true, and a value if false.

Here’s a simple blood donation eligibility checker that uses the conditional operator:

function checkDonationEligibility() {
  var age = Number(document.getElementById("ageInput").value);
  
  if (isNaN(age)) {
    return "Please enter a valid number";
  } else {
    return (age > 18) ? "Eligible for blood donation" : "Not eligible for blood donation";
  }
}

This function gets the user’s age from an input field, checks if it’s a valid number, and then uses the conditional operator ? : to determine eligibility. The syntax works like this:

condition ? valueIfTrue : valueIfFalse

The blood donation app first validates if the input is a number. Then it checks if the age is greater than 18. If true, it returns an eligibility message. If false, it shows they aren’t eligible.

Example-45: Example of this Keyword in JavaScript

The this keyword in JavaScript works as a reference to an object. In functions, it helps access properties within the same object.

Let’s look at a practical example using a mobile phone object:

var MobilePhone = {
  brandName: "Samsung",
  modelNumber: 35566,
  size: 6,
  fullName: function() {
    return this.brandName + " mobilephone model number " + this.modelNumber;
  }
};

When the fullName() method is called, this refers to the MobilePhone object. This allows the function to access the brandName and modelNumber properties that belong to the same object.

Example-46: JavaScript Validation API

The JavaScript Validation API helps check user input in forms. This example demonstrates how to validate a number input field with specific requirements.

<input id="txtNumber" type="number" min="200" max="500" required>
<button onclick="formValidation()">Click</button>

The validation function uses checkValidity() to verify if the input meets all requirements:

function formValidation() {
  var inputValue = document.getElementById("txtNumber");
  if (!inputValue.checkValidity()) {
    document.getElementById("pId").innerHTML = inputValue.validationMessage;
  } else {
    document.getElementById("pId").innerHTML = "Input is valid";
  }
}

This method works with different JavaScript data types, displaying appropriate error messages when validation fails.

Example-47: JavaScript Set Dropdown Value on Button Click

This example shows how to set a specific value in a dropdown menu when a button is clicked. The code creates a simple form with a dropdown list of states and a button.

<!DOCTYPE html>
<html>
<body>
  Select your favorite state:
  <select id="strongStateInUSA">
    <option value="California">California</option>
    <option value="Texas">Texas</option>
    <option value="NewYork">New York</option>
  </select>
  <button type="button" onclick="setTheDropdownValue()" id="btnClick">Click</button>
  
  <script>
    function setTheDropdownValue() {
      document.getElementById("strongStateInUSA").value = "California";
    }
  </script>
</body>
</html>

When the button is clicked, the JavaScript function setTheDropdownValue() runs and sets the dropdown value to “California”.

Example-48: Display Images Based on User Selection

This example shows how to create a simple image display system that changes based on user input. When a user enters a number, JavaScript loads the corresponding image from an array.

The code works by:

  1. Setting up an initial default image
  2. Creating an array with paths to different images
  3. Prompting the user to select a number
  4. Displaying the image that matches their selection
var imageArray = new Array(
  "path/to/first-image.jpg", 
  "path/to/second-image.jpg"
);

var userChoice = prompt("Pick a number 1 or 2");
userChoice--; // Adjust for zero-based array indexing
document.images["displayImage"].src = imageArray[userChoice];

This technique can be expanded to create more complex selection-based image displays for websites and applications.

Example-49: JavaScript Bind Arrays Value into Dropdown List

Creating dropdown lists with array data is a common task in web development. Let’s see how to populate a dropdown from a JavaScript array.

The process involves:

  1. Creating an array with country data
  2. Getting a reference to the dropdown element
  3. Looping through the array to create options
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);
  }
}

This function runs when a button is clicked, filling the dropdown with country names from the array.

Example-50: JavaScript Browser Detection

JavaScript can identify which browser a user is using through the navigator.userAgent property. This simple code checks the browser type when a user clicks a button.

The detection works by searching for specific browser identifiers in the userAgent string:

function getBrowserName() {
  if(navigator.userAgent.indexOf("Opera") != -1 || 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');
  }
}

This function uses the indexOf() method to check if specific browser names appear in the userAgent string. When found, it displays an alert with the browser name.

Example-51: How to Sort Array Values Using sort() Method in JavaScript

The JavaScript sort() method allows you to organize array elements in a specific order. By default, it sorts elements alphabetically.

Here’s a simple example of sorting bank names:

// Array of USA banks
var banksOfUSA = ["WellsFargo", "ChaseBank", "BankOfAmerica", "Citibank", "USBank"];

// Function to sort the array
function banksNameInAlphabeticalOrder() {
  banksOfUSA.sort();
  document.getElementById("pId").innerHTML = banksOfUSA;
}

When triggered by a button click, this function sorts the array and displays the results in alphabetical order: BankOfAmerica, ChaseBank, Citibank, USBank, WellsFargo

Download JavaScript Examples PDF

A free JavaScript examples PDF is available for download, featuring 51 helpful code samples. This resource is perfect for web developers looking to improve their JavaScript skills through practical examples.

I hope this tutorial helps you learn JavaScript from the above practical examples.

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.