JavaScript Code Snippets

Below are some useful JavaScript code snippets for use in everyday projects.

The following example changes the paragraph text to bold upon the click of a button.

<p id="demo">This is a paragraph of text.</p>

<button type="button" 
        onclick="document.getElementById('demo').style.fontWeight='bold'">
    Make paragraph text bold
</button>

JavaScript can be used to change HTML content. In the case of the example below, the contents of a paragraph is changed when a button is clicked.

<p id="demo">This is a paragraph of text.</p>

<button type="button" 
        onclick='document.getElementById("demo").innerHTML = "New paragraph text."'>
    Change text
</button>

Here is an example of how to generate a random number between two values, in this case 1 and 59, then display it.

var min = 1;
var max = 59;
var randomNumber = Math.floor(Math.random() * (max - min + 1) + min);

document.write(randomNumber);

Here, a random password is generated from a specified set of characters. The length of the password is also randomly selected from a given minimum and maximum length.

// Possible characters in password.
var alpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
var numbers = '0123456789';
var nonAlpha = '{]+-[*=@:)}$^%;(_!&#?>/|.';

// Combine possible password characters into one string.
var charSet = alpha + numbers + nonAlpha;

// Minimum and maximum password length.
var minLength = 20;
var maxLength = 30;

// Select a random password length between the minimum and maximum.
var length = Math.floor(Math.random() * (maxLength - minLength + 1) + minLength);

// variable for new password.
var result = "";

// Construct new password.
for (i = 1; i <= length; i++)
{
    
    // Add a randomly selected character to the new password.
    result += charSet[Math.floor(Math.random() * ((charSet.length-1) - 0 + 1) + 0)];

}

// Display the password.
document.write(result);

Below is an example of how to process all elements of a particular type on a page. In this example, a 'for' loop is used to process all of the links on a page, access the 'href' attribute and display it.

for (var i = 0, l=document.links.length; i<l; i++) 
{

   document.write(document.links[i].href + "<br/>");
  
}

Below is an example of how JavaScript can be used to provide confirmation to a user action. A confirmation box is provided, with 'OK' and 'Cancel' buttons. The choice a user makes is displayed on the page.

<button onclick="confirmClick()">Example confirmation</button>

<p id="ConfirmationText"></p>

<script>

function confirmClick() {

   var txt;

   if (confirm("Please confirm your choice!")) {

      txt = "You pressed the 'OK' button!";

   } 
   else 
   {

      txt = "You pressed the 'Cancel' button!";

   }

   document.getElementById("ConfirmationText").innerHTML = txt;

}

</script>

The code below takes a value that has been entered into an input item with an 'id' of 'inputSomething' and first checks to see if something has been entered. If something has been entered, examples follow of how to check for a valid boolean, single character, integer and float. It should be noted that a float will parse successfully as an integer, except that it truncates the number at the decimal point. This is why an additional check is made, comparing the parsed version with the non-parsed version.

// Assign the value entered to a variable.
var inputAsString = document.getElementById("inputSomething").value;

// Check if a value has been entered.
if (!inputAsString)
{

    document.write("Nothing has been entered.");

}
else
{

    // Check if the value is a valid boolean.
    if (inputAsString.toLowerCase() == 'true' || inputAsString.toLowerCase() == 'false')
    {
        document.write("'" + inputAsString + "' is a valid boolean." + "<br />");
    }
    else
    {
        document.write("'" + inputAsString + "' is not a valid boolean." + "<br />");
    }
    
    // Check if the value is a single character.
    if (inputAsString.length == 1 && inputAsString.charAt(0))
    {
        document.write("'" + inputAsString + "' is a valid char." + "<br />");
    }
    else
    {
        document.write("'" + inputAsString + "' is not a valid char." + "<br />");
    }
    
    // Check if the value is a valid int.
    if (parseInt(inputAsString) && inputAsString == parseInt(inputAsString))
    {
        document.write("'" + inputAsString + "' is a valid int." + "<br />");
    }
    else
    {
        document.write("'" + inputAsString + "' is not a valid int." + "<br />");
    }
    
    // Check if the value is a valid float.
    if (parseFloat(inputAsString))
    {
        document.write("'" + inputAsString + "' is a valid float." + "<br />");
    }
    else
    {
        document.write("'" + inputAsString + "' is not a valid float." + "<br />");
    }

}