Learn JavaScript by Example: Tutorials, Code Snippets & How-To’s

Table of contents

JavaScript Logo

Learn JavaScript in simple and easy steps starting from basic to advanced concepts with examples including JavaScript tutorials, code snippets, use cases and scenarios.

Vanilla JavaScript or plain JavaScript does not require any third-party libraries or frameworks, and it offers, natively, prototype-based objects, AJAX animations, events, regular expressions, functions as first-class objects, closures, math libraries, array libraries, string libraries, promises and more.

Also check our JavaScript blog for more resources and tutorials.

More tutorials and snippets: WordPress | jQuery

Latest JavaScript Tutorials ⟶

Top Bar Countdown

Ciprian on Thursday, November 25, 2021 — 431 Views

How to add a top bar countdown for your next product sale

You can (probably) see this top bar righ now, with a nice 30% off sale for my WordPress Lighthouse plugin.…

Vanilla JavaScript Draggable Carousel

Ciprian on Thursday, October 21, 2021 — 1,029 Views

How to Create a Draggable Carousel using Vanilla JavaScript

A few months ago I added a new, fancy JavaScript carousel to my homepage. It looked and behaved great, but…

JavaScript Canvas Blob

Ciprian on Wednesday, October 6, 2021 — 656 Views

Canvas JS: Big Ball of Particles

For a while now, I had this animated, constantly exploding ball of particles on one of my landing pages. Built…


Ciprian on Thursday, May 20, 2021 — 1,989 Views

JavaScript Drag & Drop

Here’s a nice list of plain JavaScript dragging and dropping solutions. They are minimal, as they serve as proof of…

How to save all values from a form

What’s this all about? I need to get all form data and save it in a hidden input field. I want to use it on a second form on the same page.

    $('.form-paypal').submit(function(event) {

function saveValues() {
    var fields = $(':input').serializeArray();
    jQuery.each(fields, function(i, field) {
        $('#results').append(field.name + ':' + field.value + '|');

I also had a hidden div to collect everything:

<div id="results" style="display:none;"></div>

That’s it. Now I can submit the second form and use the details in the first form.

How to declare a global variable inside a jQuery function

A jQuery (or Javascript) global variable is a variable with global scope, meaning that it is visible and accessible throughout the program, unless shadowed. This article deals with a problem I used to bang my head about the other day.

jQuery (or Javascript) global variables

I needed to declare a global variable inside a jQuery function (it works with regular JavaScript, too), and read it inside another function. If the first function isn’t called/initiated, the second function doesn’t know the value of the global variable.

For example, this function sets the sort order of a column of a table, nothing really interesting:

function clickMe(sortOrder) {
    sortOrderNew = sortOrder;

When the function is executed, a global Javascript variable is set. Notice there is no var in the declaration.

This line:

var sortOrderNew = sortOrder;

would set a local variable inside the said function.

Now, a second function needs this global variable. If it is set, it will automatically pick it up, if not, it will set a local variable with a fallback value:

function chipPaginate(page) {
    if (typeof sortOrderNew === 'undefined')
        var sortOrder = 3;

    if (typeof sortOrderNew !== 'undefined')
        var sortOrder = sortOrderNew;


Notice I’m doing some checks to see if sortOrderNew is defined. If not, it will assign it the value of 3 (it makes sense inside my function). Again, notice I’m using var in front of my variables, to set them locally.

Global variables conclusion

if (typeof myVariable === 'undefined') checks if myVariable is defined or not.

var myVariable = 5;

Omitting var will make myVariable global (i.e. readable among functions and available to other code).

Generate a unique string based on timestamp

This small function generates a unique string and, optionally, adds a prefix:

function generateUniqueString() {
    var out = '',
        ts = String(new Date().getTime()),
        i = 0;

    for (i=0; i<ts.length; i+=2) {
        out += Number(ts.substr(i, 2)).toString(36);

    return ('prefix' + out);

JSFiddle Demo

Hint: Replace the prefix with another unique string and you will get a stronger unique string. Note that in some very rare instances, 1 in cases with high-traffic web apps, the string might be identical.

Demistifying JavaScript history.back() and history.go() methods

One of my clients needed his online shop customers to be able to go back several steps with one click and keep the current session variables in memory. The obvious solution was the browser’s back button. But I couldn’t instruct the customer to click it one time or 3 times or 5 times. So, I chose to add a link with a JavaScript history object.

back() – Go to the previous URL entry in the history list. This does the same thing as the browser’s back button.

forward() – Go to the next URL entry in the history list. This does the same thing as the browser’s forward button. This is only effective when there is a next document in the history list. The back function or browser’s back button must have previously been used for this function to work.

go(position) – This function will accept an integer or a string. If an integer is used, the browser will go forward or back (if the value is negative) the number of specified pages in the history object (if the requested entry exists).

<a href="javascript:history.back()">Go back</a>


<a href="javascript:history.go(-3)">Go back to step X</a>

The back() and go() methods are supported in all major browsers.

History is one of the subobjects of Windows, and an interface to the history stored by your browser. Properties and methods apply to the object history of windows or to each frame in the window.

history.go(0) acts like pressing the reload button.

The length property returns the number of URLs in the history list.

Note: Internet Explorer and Opera start at 0, while Firefox, Chrome, and Safari start at 1.

console.log("Number of URLs in history list: " + history.length);

JavaScript character counter for text areas

A while ago, I had to implement a JavaScript character counter for a business listing directory. The description field was supposed to hold about 400 characters. More than that would look like spam. Here’s the solution I have come up with.

JavaScript terminal

Today’s tutorial is about creating a terminal screen together with lime terminal characters in JavaScript.

Let’s start with the CSS:

textarea {
    background-color: #000000;
    color: #14FC03;
    border: 1px solid #111;

JavaScript is next:

var tl=new Array(
    "Initializing script",
    "Activating engine",
    "Running queries...",
    "Throwing errors...",
    "Catching errors",
var speed = 60,
    str_length = tl[0].length,

function type_text() {
    contents = '';
    row = Math.max(0, index-7);
    while (row<index)
        contents += tl[row++] + '\r\n';
    document.forms[0].elements[0].value = contents + tl[index].substring(0, text_pos) + "_";
    if (text_pos++==str_length) {
        if (index!=tl.length) {
            str_length = tl[index].length;
            setTimeout("type_text()", 1500);

And, finally, the HTML:

    <div align="center">
        <textarea rows="10" cols="80" wrap="soft"></textarea>

Random JavaScript tutorials

I needed some structural updates for a site, and among them, I added some JavaScript snippets. I will show you 3 of them in this article.

The simplest, most lightweight clock ever written in JavaScript

1. Use this JavaScript code where you want the clock to appear:

var now=new Date();
console.log(now.getDate() + ' ' + "JanFebMarAprMayJunJulAugSepOctNovDec".substr(now.getMonth()*3,3)+', '+now.getFullYear());

Form field hints using a bit of CSS

1. Add this CSS code to your document:

dl {
    position: relative;
    width: 350px;
dt {
    clear: both;
    float: left;
    width: 130px;
    padding: 4px 0 2px 0;
    text-align: left;
dd {
    float: left;
    width: 200px;
    margin: 0 0 8px 0;
    padding-left: 6px;
.hint {
    display: none;
    position: absolute;
    right: -250px;
    width: 200px;
    margin-top: -4px;
    border: 1px solid #c93;
    padding: 10px 12px;
    background-color: #ffc;
.hint .hint-pointer {
    position: absolute;
    left: -10px;
    top: 5px;
    width: 10px;
    height: 19px;
    background: url(_images/pointer.gif) left top no-repeat;

2. Add this JavaScript code to your document:

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {

function prepareInputsForHints() {
    var inputs = document.getElementsByTagName("input");
    for (var i=0; i<inputs.length; i++) {
        // test to see if the hint span exists first
        if (inputs[i].parentNode.getElementsByTagName("span")[0]) {
            // the span exists! on focus, show the hint
            inputs[i].onfocus = function () {
                this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
            // when the cursor moves away from the field, hide the hint
            inputs[i].onblur = function () {
                this.parentNode.getElementsByTagName("span")[0].style.display = "none";
    // repeat the same tests as above for selects
    var selects = document.getElementsByTagName("select");
    for (var k=0; k<selects.length; k++) {
        if (selects[k].parentNode.getElementsByTagName("span")[0]) {
            selects[k].onfocus = function () {
                this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
            selects[k].onblur = function () {
                this.parentNode.getElementsByTagName("span")[0].style.display = "none";

3. Add this HTML code to your document:

    <dt><label for="firstname">First Name:</label></dt>
        <input name="firstname" id="firstname" type="text">
        <span class="hint">This is your firstname.<span class="hint-pointer"> </span></span>
    <dt><label for="lastname">Last Name:</label></dt>
        <input name="lastname" id="lastname" type="text" />
        <span class="hint">This is your last/family name.<span class="hint-pointer"> </span></span>
    <dt><label for="email">Email:</label></dt>
        <input name="email" id="email" type="text" />
        <span class="hint">This is your regular e-mail address.<span class="hint-pointer"> </span></span>
    <dt><label for="year">Birth Year:</label></dt>
        <select id="year" name="year">
            <option value="">Year</option>
            <option value="2007">2007</option>
            <option value="2006">2006</option>
            <option value="2005">2005</option>
            <option value="2004">2004</option>
            <option value="2003">2003</option>
        <span class="hint">This is your birth year.<span class="hint-pointer"> </span></span>
    <dt><label for="username">Username:</label></dt>
        <input name="username" id="username" type="text" />
        <span class="hint">This is your username/nickname (5 to 9 characters).<span class="hint-pointer"> </span></span>
    <dt><label for="password">Password:</label></dt>
        <input name="password" id="password" type="password" />
        <span class="hint">This is your secret password (5 to 9 characters).<span class="hint-pointer"> </span></span>
    <dt class="button"> </dt>
    <dd class="button">
        <input type="submit" class="button" value="Submit" />

Show/Hide switch function for an HTML element (DIV)

1. Place this code snippet in the HEAD element:

#mylayer {
    visibility: hidden;
    width: 400px;
    height: 370px;
function ShowHide(id) {
    obj = document.getElementsByTagName("div");
    if (obj[id].style.visibility == 'visible') {
        obj[id].style.visibility = 'hidden';
    } else {
        obj[id].style.visibility = 'visible';

2. Place this code snippet in the BODY element:

<a href="javascript:ShowHide('mylayer')">Show/Hide DIV switch</a>
<div id="mylayer">This is dummy content this is dummy content this is dummy content this is dummy content this is dummy content this is dummy content</div>

JavaScript centered popup window

This tutorial is about JavaScript popups and how to show a window in the center of the screen and focus on it. The trick is easy and the containing function is small. Here is the JavaScript code:

function window_popup(content, x, y, title) {
    var thisWindow;
    thisWindow = window.open(content, title, "width="+x+", height="+y+", scrollbars=auto, screenX=0, screenY=0, toolbar=no, location=no, menubar=no");

And here is the caller function:

<a href="#" onclick="window_popup('mypage.html', 400, 300, 'mypage')">Open My Page</a>

Remember to quote the page name and title, otherwise the script will generate an error. Popup window attributes can be changed in the second line of the function

"scrollbars=auto, screenX=0, screenY=0, toolbar=no, location=no, menubar=no"

depending on what the role of the window is.

Funnel page load optimisation snippet

Here’s a quick snippet to preload the next step in a theoretical funnel/workflow:


* Preconnect/Prefetch/Prerender in HTML5
if (stripos(getPageUrl(), 'funnel/step-one') !== false) {
    // Firefox
    echo '<link rel="prefetch" href="' . str_replace('funnel/step-one', 'funnel/step-two', getPageUrl()) . '">';
    // Chrome
    echo '<link rel="prerender" href="' . str_replace('funnel/step-one', 'funnel/step-two', getPageUrl()) . '">';


 * Preconnect/Prefetch/Prerender in JS
function preconnectTo(url) {
    var hint = document.createElement('link');
    hint.rel = 'preconnect';
    hint.href = url;

// Usage
if (window.location.href.indexOf('funnel/step-one') > -1) {
    preconnectTo(window.location.href.replace('funnel/step-one', 'funnel/step-two'));

// Usage (alternative)
if (/step-one/.test(self.location.href)) {
    preconnectTo(self.location.href.replace('funnel/step-one', 'funnel/step-two'));

Numerical integration using JavaScript


  • Use * to indicate multiplication: Type 4*x for 4x;
  • Use ^ to indicate powers: Type 4*x^3 for 4×3; 12*x^-6 for 12x?6.
  • Use parentheses to delimit the argument of a function; i.e., type sin(x) rather than sin x.
  • Use parentheses to define the scope of an operation: For example, type 4*x*(x^2+1)^3 for 4x(x2+1)3; 4^(2*x+1) for 42x+1; (sin(x))^2 for (sin(x))2.
  • Do not type sin^2(x) for sin2(x), type (sin(x))^2 instead.
  • Do not use brackets [ ] or braces { }, use only parentheses to delimit a mathematics expression.
  • Functions you may use:

Trig: sin, cos, tan, cot, sec, csc;

Inverse Trig: asin, acos, atan;

Log/exponential: ln (natural log), or use log; exp, the natural exponential; Note: You can also enter the natural exponential exp(x) as e^x for ex.

Misc: sqrt, usage sqrt(x) for ?x (or, use exponential notation: x^(1/2)).

Copy web page content using innerHTML

I need to extract some data from a web page and place it on a fishing site. The source web page is updated frequently, and I don’t have the necessary time to update it. So, I’ll use the Javascript innerHTML function.

First of all, I should identify the element I’m trying to copy, let’s say a div with the #info ID:

<div id="info">
This information updates daily.

The next step is to include the source web page as an iframe with width and height equal to 0:

<iframe name="thief" width="0" height="0" frameborder="0" src="source.html"></iframe>

The final code should read from the IFRAME and display the content on the destination page, in a specially created div:

<div id="destination">
This content will be replaced.
// this script will copy the ontent of the 'info' div into the 'thief' div in the destination page
parent.document.all('thief').innerHTML = document.all('info').innerHTML;

Interactive panels with lightbox and email overlays

Interactive Panels

I’d like to share one of my recent creations, CSS/JS interactive panels. Each panel contains an image, content and two call-to-action buttons. In addition, there is a lightbox link opening a second image. Each call-to-action button opens a transparent overlay with an email form. The panels use pure JavaScript and FontAwesome. See code and demo.

JavaScript bookmarklets collection

Bookmarklet 1: Show Password

A simple JavaScript snippet can be used to view passwords in web browsers. To use the code, open your web browser and open the webpage for which the password is hidden in asterisks.

Use the Show Password bookmarklet to instantly view hidden passwords at the click of a button.

Create a new bookmark and add the code below:

javascript: var p=r(); function r(){var g=0;var x=false;var x=z(document.forms);g=g+1;var w=window.frames;for(var k=0;k<w.length;k++) {var x = ((x) || (z(w[k].document.forms)));g=g+1;}if (!x) alert('Password not found in ' + g + ' forms');}function z(f){var b=false;for(var i=0;i<f.length;i++) {var e=f[i].elements;for(var j=0;j<e.length;j++) {if (h(e[j])) {b=true}}}return b;}function h(ej){var s='';if (ej.type=='password'){s=ej.value;if (s!=''){prompt('Password found ', s)}else{alert('Password is blank')}return true;}}

Bookmarklet 2: Show Coordinates

Google Maps does not offer a menu option for obtaining the coordinates – latitude and longitude – of a location. However, you can use another bookmarklet to extract the coordinates.

  1. Find the location for which you would like to obtain coordinates in Google Maps.
  2. Right click on your chosen location, and select “center map here.”
  3. Click on the Show Coordinates Bookmark.

This will activate a small pop-up window that will show the coordinates for the centered location in decimal format. You may copy and paste these coordinates wherever needed.

Create a new bookmark and add the code below:


Bookmarklet 3: Fun 3D Browser

This bookmarklet will turn the current page into a 3D parallax-enhanced page.

Create a new bookmark and add the code below:

javascript:if(!window.ThreeDit){ThreeDit=function(a,b){function G(a){p=a.clientX+g.scrollLeft;q=a.clientY+g.scrollTop}function F(){var a=g.scrollLeft-t;var b=g.scrollTop-u;p=v=g.scrollLeft+r;q=w=g.scrollTop+s;n+=a;o+=b;x=v+l.clientLeft-e.pageXOffset;y=w+l.clientTop-e.pageYOffset;t=g.scrollLeft;u=g.scrollTop}function E(){r=e.innerWidth/2;s=e.innerHeight/2;p=v=g.scrollLeft+r;q=w=g.scrollTop+s;x=v+l.clientLeft-e.pageXOffset;y=w+l.clientTop-e.pageYOffset}function D(){n+=(p-n)*.05;o+=(q-o)*.05;var a=(n-v)/r*5;var b=-(o-w)/s*5;for(var e=0;e<d.length;e++){var f=d[e].node;var g=f;var h=0;var k=0;var l=d[e].z;f.style[i]=x-h+"px "+(y-k)+"px";f.style[j]="rotateY("+a+"deg) rotateX("+b+"deg)translate3d(0px,0px, "+l*c.zDepth+"px)"}}function C(){var a;for(var b=0;b<d.length;b++){d[b].node.style[j]="none"}delete d;d=[];A(g,0);d.push({node:g,z:0});d.sort(function h(a,b){return a.z-b.z});var c=0;var e=[c];d[0].z=c;for(var b=1;b<d.length;b++){e.push(c=d[b].z==d[b-1].z?c:c+1)}var f=e[e.length-1];for(var b=0;b<d.length;b++){d[b].z=e[b]/f}}function B(a){c.perspective=a;k[h+"Perspective"]=c.perspective+"px"}function A(a,b,e){if(d.length>=c.maxElems-1)return;if(!e&&a.tagName=="DIV"&&a.childNodes.length>0){d.push({node:a,z:b})}for(var f=0;f<a.childNodes.length;f++){A(a.childNodes[f],b+1,a.childNodes.length<2)}}function z(a){f=a;g=f.body;h="webkitTransform"in g.style?"webkit":"MozTransform"in g.style?"Moz":null;i=h+"TransformOrigin";j=h+"Transform";l=f.documentElement;k=l.style;m=e.getComputedStyle;t=g.scrollLeft;u=g.scrollTop;k[h+"Perspective"]=c.perspective+"px";k.backgroundImage=m(g).getPropertyValue("background-image");k.backgroundColor=m(g).getPropertyValue("background-color");C();if(!c.initialized){E();n=p;o=q;e.addEventListener("resize",E);e.addEventListener("scroll",F);f.addEventListener("mousemove",G);setInterval(D,1e3/60)}c.initialized=true}var c={zDepth:300,maxElems:100,perspective:500,initialized:false};var d=[];var e=a;var f=b;var g;var h;var i;var j;var k;var l;var m;var n;var o;var p;var q;var r;var s;var t;var u;var v;var w;var x;var y;c.init=z;c.recollectElems=C;c.render=D;c.changePerspective=B;return c}(window,document);ThreeDit.init(document);}else{ThreeDit.recollectElems();}

The JavaScript equivalent of PHP strpos()

// JS-specific strpos()
function strpos(haystack, needle, offset) {
    var i = (haystack + '').indexOf(needle, (offset || 0));

    return i === -1 ? false : i;

Check scroll depth

This function checks after each scroll event to see if a visitor has achieved certain scroll depth milestones. In the case of this example, custom events will be fired off when a visitor scrolls 25%, 50%, 75%, and 100% of the way down the page.

 * This function fires custom events at different scroll depth milestones.

// Variables to prevent continuous firing of custom events

var scrollTwentyFive = true;
var scrollFifty = true;
var scrollSeventyFive = true;
var scrollOneHundred = true;

// Create the scrollPercentage

$(window).bind('scroll', function() {
    window.scrollPercent = ($(window).scrollTop() / ($(document).height() - $(window).height())) * 100;

    // Conditional code we'll use to fire events based on scrollPercentage.
    if (window.scrollPercent >= 25 && scrollTwentyFive) {
        // Do something for 25% scroll
        scrollTwentyFive = false;
    if (window.scrollPercent >= 50 && scrollFifty) {
        // Do something for 50% scroll
        scrollFifty = false;
    if (window.scrollPercent >= 75 && scrollSeventyFive) {
        // Do something for 75% scroll
        scrollSeventyFive = false;
    if (window.scrollPercent >= 100 && scrollOneHundred) {
        // Do something for 100% scroll (bottom of page)
        scrollOneHundred = false;

Target visitors based on screen size

The first condition is the screen width is greater than 1400 pixels and the height is greater than 800 pixels. The second condition is the viewport width is between 320 and 480 pixels and the height is less than or equal to 640 pixels.

// Target desktop viewports
// Matches CSS media queries for height/width or max/min-height or -width
window.innerWidth > 1400 && window.innerHeight > 800

// Target mobile phones
// Matches CSS media queries using device-height and device-width
screen.width >= 320 && screen.width <= 480 && screen.height <= 640

Execute code for X visits

This JavaScript will let you execute code a certain number of times. For example, you might want to only show a pop up to visitors on their first 3 visits.

 * The following allows you to set a limit on the number of times a function will execute for any given visitor.

// the number of times the code should execute for a given visitor,
// the number of days the evaluation limit should last,
// and name of the cookie we use as the counter
var limit = 3,
    days = 180;
    cookieName = 'counterCookie';

// function to fetch cookie values
var getCookie = function(name) {
    var match = document.cookie.match(name+'=([^;]*)');

    return match ? match[1] : undefined;

// function to create cookies
var setCookie = function(c_name,value,exdays,c_domain) {
    c_domain = (typeof c_domain === "undefined") ? "" : "domain=" + c_domain + ";";
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
    document.cookie=c_name + "=" + c_value + ";" + c_domain + "path=/";

// logic that counts and limits number of times code can evaluate for given visitor
if (!getCookie(cookieName)) {
    setCookie(cookieName, 1, days, window.location.hostname);
} else {
    var numberPops = parseInt(getCookie(cookieName)) + 1;
    setCookie(cookieName, numberPops, days, window.location.hostname);

if (getCookie(cookieName) <= limit) {
    // Function to be evaluated here

How to Change Page Title Using JavaScript

This JavaScript will modify the text of the browser tab when a visitor focuses or un-focuses the tab. You can display one title when a visitor is focused on the tab and a different title when they toggle to a different tab or window.

How to track and measure phone number views with JavaScript

As phone numbers are clickable (and work) only on mobile devices, there’s no way to track how many users copy them or write them down. Well, unless they’re hidden and require user access.

How to show an outdated browser alert on Internet Explorer 11

Also, here’s a nice overview on why Internet Explorer 11 should be phased out and users blocked from viewing the site content when using the aforementioned browser.

Native JavaScript hasClass()

These JavaScript snippets implement a native hasClass() function (inspired by jQuery and dubbed elementHasClass()), which checks if an element has a certain class.

How to extract a value from an element and, optionally, round it

This JavaScript snippet will extract a price from a DOM element, remove all alphanumeric characters, such as currency or symbols or other words, optionally round it, and return it.

How to hide an element using JavaScript

Here are three methods to hide an element using JavaScript. Additionally, there’s a collection of helper functions to automate showing and hiding elements.

Client-Side JavaScript Pagination

For small result sets – less than 1000 – and when the query is optimised, this is how you can use client-side navigation (i.e. JavaScript pagination).

How to Implement jQuery slideToggle() in Vanilla JavaScript

Here’s a quick JavaScript replacement for jQuery slideToggle(). With small changes, it can be adapted to replace fadeToggle() or simply toggle().

Experiment: JavaScript Boxed Carousel with Progress Indicator

Here’s an awesome JavaScript carousel built for a client project, but then scrapped. It definitely has potential for unlimited items. Currently it has a 5 second delay between slides and a neat progress indicator.


Very relevant links and references

This is a book about JavaScript, programming, and the wonders of the digital.

A book series on JavaScript. @YDKJS on Twitter.

A book about functional programming in JavaScript. @FLJSBook on Twitter.

How to manage HTML DOM with vanilla JavaScript only, for modern browsers and IE 11+.

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

Added by Ciprian on Thursday, May 20, 2021 in Blog, JavaScript

Leave a Reply

You have to agree to the comment policy.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Privacy Policy