Calculate remaining time in days, hours, minutes and seconds – Javascript, PHP

Demo

Convert time to different timezones

Today, we will learn to calculate remaining time till future date in days, hours, minutes and seconds. Either you are receiving values in PHP variable from MySQL database, or you are calling an AJAX request, this tutorial will help you in both situations. We will also display the hours, minutes and seconds in leading zeroes.

So you will not see time as “7:9:3” but you will see that as “07:09:03” using leading zeroes. We already uploaded 1 more tutorial on creating a countdown timer using libraries. If you are comfortable to use third party libraries in your project, you can follow our tutorial on that as well.

Using third party library

Basically, we are going to get the difference between current date and the date in future. Then we will extract the days, hours, minutes and hours from that difference. Difference will be in seconds so we have to apply some math on it. First we assume that you are already receiving the value from your MySQL database in PHP variable. We have set the PHP variable below but you can use your own database value:

<?php
	$date = "2020-06-07 23:39:00";
?>

Then we will create a <div> where we will display the remaining time and a hidden input field to get the PHP variable value in Javascript.

<div id="data"></div>

<input type="hidden" id="date" value="<?php echo $date; ?>">

JS function when page loads

Then create a Javascript function which will be called once simply when the page loads. And then in a setInterval function which will be called each second, so we will display the remaining time in seconds as well. We will get 2 date objects, first will be current date and second will be date in future which we are getting from PHP variable.

Then we will get the timestamp from both dates in milliseconds using getTime() function. Dividing that by 1000 will convert that in seconds. But we will also get the floating numbers when dividing, we can prevent the floating number by calling toFixed(0) function.

Convert string to double – Javascript

Since toFixed() function returns a string which will not be helpful in getting the difference between 2 dates, so we have to convert that in double or float. We can do that by calling Math.abs() function, it will return the absolute value. Then we subtract the current timestamp from future timestamp and save that in a variable diff as difference.

This diff variable is also in seconds, now we have to convert that value into days, hours, minutes and seconds. We know that there are 86400 seconds in each day, so dividing the difference by 86400 will return the number of days remaining. And since dividing also cause floating number, so we can prevent that by calling Math.floor() function. It will round the value to the previous number.

For example, if the value is 23.7 then it will return as 23. Time to get the remaining hours, we know that there are 3600 seconds in each hour, so we will divide that difference by 3600, round the value to floor. And since there are 24 hours in each day, so we have to take the modulus by 24. Taking modulus will divide the value and return the remainder.

Get seconds from timestamp – Javascript

To get the minutes, we know that there are 60 seconds in each minute and 60 minutes in each hour. So we divide the difference by 60, round the value by floor, then take the modulus by 60. That will return the number of minutes remaining till date. To get the seconds, is the simplest among all.

We know the limit for seconds is 60, so we simply take the modulus of difference by 60 and it will return the seconds. If you want to show the leading zeros i.e. zeroes on left if value is less than 10, then you can also put a condition on days, hours, minutes and seconds. Check if the value is less than 10, then prepend the “0” with value. And finally display that in our <div id=”data”></div>

Make sure to call the function in setInterval to update the value each second. Following function will calculate the remaining time.

<script>
    function func() {
        var dateValue = document.getElementById("date").value;

        var date = Math.abs((new Date().getTime() / 1000).toFixed(0));
        var date2 = Math.abs((new Date(dateValue).getTime() / 1000).toFixed(0));

        var diff = date2 - date;

        var days = Math.floor(diff / 86400);
        var hours = Math.floor(diff / 3600) % 24;
        var minutes = Math.floor(diff / 60) % 60;
        var seconds = diff % 60;

        var daysStr = days;
        if (days < 10) {
            daysStr = "0" + days;
        }
 
        var hoursStr = hours;
        if (hours < 10) {
            hoursStr = "0" + hours;
        }
 
        var minutesStr = minutes;
        if (minutes < 10) {
            minutesStr = "0" + minutes;
        }
 
        var secondsStr = seconds;
        if (seconds < 10) {
            secondsStr = "0" + seconds;
        }

        if (days < 0 && hours < 0 && minutes < 0 && seconds < 0) {
            daysStr = "00";
            hoursStr = "00";
            minutesStr = "00";
            secondsStr = "00";

            console.log("close");
            if (typeof interval !== "undefined") {
                clearInterval(interval);
            }
        }

        document.getElementById("data").innerHTML = daysStr + " days, " + hoursStr + ":" + minutesStr + ":" + secondsStr;
    }

    func();
    var interval = setInterval(func, 1000);
</script>

That’s how you can calculate the remaining time till date in Javascript.

[wpdm_package id=’421′]

Load content when scrolled – AJAX, Javascript, PHP & MySQL

In this tutorial, we are going to teach you how you can load the content of div only when user scrolled to that section. For example, you have a lot of dynamic sections in your website, loading them all using PHP is very costly since server has to get a lot of data from database and it will make your website load slower.

Get data using AJAX

Second option was to load all data using AJAX, this will solve the first problem because the website will be loaded instantly and all the sections where dynamic data needs to be displayed will send an AJAX request to get that data and display in relevant section using Javascript.

However, take this example, if your website has 10 sections and users mostly use the first 3 sections. This means that the server is serving 7 extra requests which are not commonly being used by client. It will slowdown the server, possibly crash your website if you have a lot of users. What if we find a way of optimization such that the relevant section will only be loaded when required by user.

How it works

Simply means, request of section will be sent to server only when asked by client to get that data. If user is on first 3 sections, then the ajax will be called only 3 times and server will be serving only 3 requests. Request for section 4 will only be served if user moved or scrolled to that section, otherwise it will not be loaded. It will greatly optimize your website and make it load faster and more responsive.

This tutorial is written in pure Javascript, no jQuery or any other external library has been used. So you can use this tutorial under all Javascript and PHP frameworks.

We have created a sample database called “classicmodels” from where we are going to load the data from 4 tables:

  1. customers
  2. employees
  3. offices
  4. products

The important question here is “How am I going to know when user has scrolled to some div ? And how can I tell the server to get data required in that div ? And how to display it in relevant div ?”. For this, we are going to use Javascript built-in IntersectionObserver object, basically it observes all the nodes in the intersection.

Intersection Observer

Intersection is a visible area in browser, when you open any website, the content which is visible to you is in Intersection. So we are going to add all divs which needs to be loaded dynamically under observation. Once that div intersects, we are going to send a simple AJAX request using Javascript (no jQuery), telling the server what type of data we need and then display the data in that div.

Server side (PHP)

Paste the following code in your server side or back-end PHP file, we have named it “Http.php“. Make sure to change the database credentials.

<?php
	// File name = Http.php

	// Get data from database

	if (isset($_GET["type"]))
	{
		// Connecting with database
		$conn = mysqli_connect("localhost", "root", "", "classicmodels");

		// Just for testing, set a delay for 2 seconds
		sleep(2);

		// Getting all results from relevant table
		// you can perform different queries for each div using $_GET['type'] variable

		$type = $_GET["type"];

		$result = mysqli_query($conn, "SELECT * FROM " . $type);
		$data = array();

		while ($row = mysqli_fetch_object($result))
		{
			array_push($data, $row);
		}

		// Sending response back
		// we also need to send the type back
		echo json_encode(array(
			"data" => $data,
			"type" => $type
		));
		exit();
	}
?>

Client side

Paste the following code in your client side or front-end. Make sure to change the IDs of divs as per your project. Also set server file name as per yours at line 13.

<!-- Create divs which needs to be loaded by ajax -->
<div id="customers" class="loaded-by-ajax"></div>

<div id="employees" class="loaded-by-ajax"></div>

<div id="offices" class="loaded-by-ajax"></div>

<div id="products" class="loaded-by-ajax"></div>
<script>
	// Create observer
	var ajaxObserver = new IntersectionObserver(function (items, self) {
		// Loop through all items in visible area
		for (var a = 0; a < items.length; a++) {
			// Check if div under observation is in visiable area
			if (items[a].isIntersecting) {
				// Get ID
				var id = items[a].target.id;
				
				// Call ajax to get data
				var ajax = new XMLHttpRequest();
				ajax.open("GET", "Http.php?type=" + id, true);

				// Show loading in relevant div before ajax
				document.getElementById(id).innerHTML = "Loading..." + id;

				// This event will be called for each request change status
				ajax.onreadystatechange = function () {
					// Response is received when ready state is 4 and status is 200
					if (this.readyState == 4 && this.status == 200) {
						// Convert JSON string into arrays and objects
						var response = JSON.parse(this.responseText);

						var data = response.data;
						var type = response.type;

						var html = "";
						// Each div might have different layout

						if (type == "customers") {
							html += "<h1>Customers</h1>";

							// Loop through all items
							for (var b = 0; b < data.length; b++) {
								html += "<p>" + data[b].customerName + "</p>";
							}
						} else if (type == "employees") {
							html += "<h1>employees</h1>";

							// Loop through all items
							for (var b = 0; b < data.length; b++) {
								html += "<p>" + data[b].firstName + " " + data[b].lastName + "</p>";
							}
						} else if (type == "offices") {
							html += "<h1>offices</h1>";

							// Loop through all items
							for (var b = 0; b < data.length; b++) {
								html += "<p>" + data[b].city + "</p>";
							}
						} else if (type == "products") {
							html += "<h1>products</h1>";

							// Loop through all items
							for (var b = 0; b < data.length; b++) {
								html += "<p>" + data[b].productName + "</p>";
							}
						}

						// Render the relevant div
						document.getElementById(type).innerHTML = html;
					}
				};

				// Sending the ajax request
				ajax.send();

				// Prevent the div from being observed again
				self.unobserve(items[a].target);
			}
		}
	});

	// Add all loaded-by-ajax divs in observation list
	var loadedByAjax = document.getElementsByClassName("loaded-by-ajax");
	for (var a = 0; a < loadedByAjax.length; a++) {
		ajaxObserver.observe(loadedByAjax[a]);
	}
</script>

That’s how you can load content only when scrolled using Javascript’s “IntersectionObserver”.

Learn how to do the same for images.

Lazy load images – Javascript

[wpdm_package id=’251′]

Disable scroll on input type number – Javascript

Ever come across a problem where you enter some value in input type number and while you scroll down or up, you will see that the value of that input field is changed. It is because of the default behavior of the browser, it increments or decrements the value of input fields having “type” attribute valued as “number” as long as the user is scrolling inside that input field. So, let’s learn how to disable scroll on input type number for these situations.

However, there are multiple ways to prevent this behavior. But the simplest solution we came across is by removing the focus from that input field as long as the user is scrolling inside that input field. We are calling it “simplest” because it does not even need jQuery.

yes NO JQUERY !!!

Just paste the following code at the end of the file where you want to disable this scrolling behavior:

var inputTypeNumbers = document.querySelectorAll("input[type=number]");
for (var a = 0; a < inputTypeNumbers.length; a++) {
	inputTypeNumbers[a].onwheel = function (event) {
		event.target.blur();
	};
}

Explanation

querySelectorAll will return all the nodes that matches the selector passed in as an argument. We are selecting all input fields which have a field attribute having value as “number”. This will return an array which we can use to loop through all nodes.

Next, we are looping through all input type numbers and inside this loop. We can perform a specific action on each node. We are overriding onwheel event, which is called whenever we move the mouse wheel inside the input field. In this event, we are receiving a variable from parameter named as “event”. It contains all the functions and attributes of this event.

We have an object named “target” in this event object which holds the actual input field node. Although we can use the “inputTypeNumbers[a]” inside the function event, it is better to use the event.target object. All input fields in HTML5 have a function named “blur()” which removes the focus from that input field. Calling this function will remove the focus from that input field and thus the scrolling of numbers will not occur.

That’s how you can disable scroll on input type number using Javascript’s “onwheel” event.

Detect page leave – HTML & Javascript

Preview image from input type file before upload – Javascript

In this article, we will learn how to preview image before upload from input type file using Javascript. A FileReader object is used.

The following code will display an input type file from where the user can select an image file. As soon as he selects the image, it’s preview will be displayed in an image tag. This is useful when you want to show the user the image he selected, before saving it in the database. So the user must know that he has picked the correct image.

<script>
	function previewImage() {
		var file = document.getElementById("file").files
		if (file.length > 0) {
			var fileReader = new FileReader()

			fileReader.onload = function (event) {
				document.getElementById("preview").setAttribute("src", event.target.result)
			}

			fileReader.readAsDataURL(file[0])
		}
	}
</script>

<form method="POST" action="/" enctype="multipart/form-data">
	<input type="file" name="file" id="file" accept="image/*" onchange="previewImage();">

	<img id="preview">
</form>

Explanation

Form encoding type will be used to upload the file on the server-side (PHP). Give your input type file a unique ID so it can be accessed in Javascript. We have created an image tag where a preview of the selected file will be displayed. Give a unique ID to this image tag too. A function on onchange event on input type file will be called whenever user select some file from dialog. We are also adding an attribute accept=”image/*” that will make sure that the user selects only the image files like JPEG, PNG etc.

In this function, first we are checking if the user has selected any file. We are creating a FileReader object, it is used to read the file. With this file reader object, we are calling a function named readAsDataURL, it will read the content of a file as URL. That URL will be used to set the “src” attribute of our image tag.

onload event will be called when the file is fully read by file reader object. In this function, we are simply setting the “src” attribute of our image tag. event.target refers to the original file reader object and “result” is the actual URL of selected file.

Since you have learned how you can preview an image before upload from input type file using Javascript. Learn also how to upload, download and delete files in PHP.

[wpdm_package id=’247′]

Custom auto complete view – Vanilla Javascript

Learn how to create a custom auto complete view in vanilla Javascript. Auto complete view is a feature in which an input field predicts the rest of a word a user is typing. In most frequently fields like city names, users can typically enter some words. And wait for seeing the suggestions to accept one of several cities.

Auto complete view speeds up human-computer interactions. It correctly predicts the word a user intends to enter after only a few characters have been typed into a text input field. It works best in domains with a limited number of possible words (such as in command-line interpreters). When some words are much more common (such as when addressing an e-mail), or writing structured and predictable text (as in source code editors).

Google

In search engines like Google, auto complete view provide users with suggested queries or results as they type their query in the search box. This is also commonly called autosuggest or incremental search. This type of search often relies on matching algorithms that forgive entry errors. Such as phonetic Soundex algorithms or the language-independent Levenshtein algorithm. The challenge remains to search large indices or popular query lists in under a few milliseconds. So, that the user sees results pop up while typing.

Nothing gives you more control than writing code by yourself.

Unknown

Auto complete view can have an adverse effect on individuals and businesses when negative search terms are suggested. Autocomplete has now become a part of reputation management as companies linked to negative search terms such as scam, complaints and fraud seek to alter the results. Google in particular have listed some of the aspects that affect how their algorithm works. But this is an area that is open to manipulation.

Example

Suppose you have a list of values that you want to populate in an input field as user types. Give users an ability to select an item from that list and store the data. For example, if you have a list of products, you can display product title. But once any value is selected, you can send the product ID in database. Although there are many libraries on the internet to do this job. But they are limited in customizations and you have to remember their function names and parameters and options etc.

Lets get started

First we are going to create an input field that will have an ability to call a Javascript function as soon as user types something in it. We are attaching the “onkeyup” attribute on that field which will be called for every key pressed by the user. We are also giving this field an ID and name attribute:

  • ID will be use in Javascript to populate suggestions based on this field value.
  • Name will be use in PHP where form data will be sent. You can handle this as per your project.

Form’s method and action attribute depends on your project, you can adjust them as per your needs. We have also created a hidden field which will set the ID of selected product. So we will be displaying product title in suggestions. Also, when user select one product, it’s ID will be put in this hidden field. Lastly, we have a div where all suggested products will be displayed.

<form method="POST" action="send-data.php">
    <input type="text" id="product" name="product" onkeyup="onKeyUp();">
    <input type="hidden" id="productCode" name="productCode">
    <div id="products-list"></div>
</form>

Send HTTP request

First we will create a function for “onkeyup” event that we attached on previous step. In this function, we are getting value from product’s input field. We will get the suggested products only if the input field has at-least 3 words in it. Because sending HTTP request on each word would be very costly and it does not make sense at all. When you search for some product you already know first 4 or 5 characters of it. Even in case of cities, most people know at-least 3-4 characters of what they want to search. Displaying suggestions on each word would be really annoying for users.

Then in div where we wanted to show the suggested products, we will first show a loading message. So that the user knows that it is searching for products and the location where suggested products will be displayed. Then we are sending an AJAX request, the request method is GE. So it does not require any headers in the request.

URL of AJAX request

Second parameter in open function is the name of file, we will create that file in next step. In same parameter, we are sending user entered words in the URL so we can get them in that PHP file. At the end of this function we are sending the request. But before sending, we are attaching an event which will be called when the response is successfully received from server.

From get-products.php file which we will create in next step, we will receive all the suggested products based on value of input field. The response sent from PHP to Javascript will be in JSON string format, so we have to convert (parse) that string to Javascript objects and arrays. Then we will loop through all the suggested products and display them in paragraph. A separate variable is created which will store all the HTML content of the autocomplete view. Finally, we are setting this HTML variable value to div using its unique ID.

<script>
    function onKeyUp() {
        var product = document.getElementById("product");

        if (product.value.length >= 3) {
            document.getElementById("products-list").innerHTML = "Loading...";

            var ajax = new XMLHttpRequest();
            ajax.open("GET", "get-products.php?product=" + product.value, true);

            ajax.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) {
                    var data = JSON.parse(this.responseText);
                    var html = "";

                    for (var a = 0; a < data.length; a++) {
                        html += "<p>" + data[a].productName + "</p>";
                    }

                    document.getElementById("products-list").innerHTML = html;
                }
            };

            ajax.send();
        }
    }
</script>

Get suggested products

So we are sending HTTP request after 3 words entered by the user. And sending those 3 words to the server to fetch suggested products that match their title with those 3 words. Now we need to create a file that will match the product’s title with those words and return them all as an array. So we are first connecting with the database, get the user input field from URL.

Search that value in the database based on the products table’s title field (it might be different as per your need). Executing that query will return a $result object. It will have all pieces of information about the result which is received from the database. For example, number of rows, columns in each row, each row’s content, etc.

mysqli_fetch_all

You can use the mysqli_fetch_all function to return all rows at once. But this function does not work in some PHP versions. So what we are going to do, is to loop through each record and push them in our created array one-by-one. We will be using while loop to continue loop until all rows are fetched. At the end, we will have a PHP array will all the suggested products.

But we need them in Javascript, so we need to convert that array into JSON string format and in Javascript we are already converting that string back to Javascript arrays and objects.

get-products.php

<?php

	$conn = mysqli_connect("localhost", "root", "root", "classicmodels");
	$product = $_GET["product"];

	$sql = "SELECT * FROM products WHERE productName LIKE '%" . $product . "%'";
	$result = mysqli_query($conn, $sql);

	$data = array();
	while ($row = mysqli_fetch_object($result))
	{
		array_push($data, $row);
	}
	echo json_encode($data);

?>

Select product from suggestions

At this point, as the user starts typing the input field, after 3 words a list of suggested products will be displayed. Now we need to give the user an ability to select a product from this suggested list. First, we need to attach on “onclick” listener to the product’s title in a suggestions list that will call a Javascript function whenever the user selects a product from the list.

In that function we are going to need a selected product ID, so we are adding a custom attribute data-id whose value will be the product ID that should be set in the hidden input field. In that function, we are getting the selected product ID and setting this in the hidden product code field. Also, we are emptying the div so the suggestions will be removed once an item is selected from the list.

Lastly, in input field we are setting product’s title as a value because the user has only entered 3 words, once he selects some item from the list, that value will be set in his input field.

function selectProduct(self) {
	var productCode = self.getAttribute("data-id");
	document.getElementById("productCode").value = productCode;
	document.getElementById("products-list").innerHTML = "";
	document.getElementById("product").value = self.innerHTML;
}

// Inside AJAX response
for (var a = 0; a < data.length; a++) {
	html += "<p onclick='selectProduct(this);' data-id='" + data[a].productCode + "'>" + data[a].productName + "</p>";
}

Applying styles

Although this part has nothing to do with functionality, but it is always good to do some work on the design and make it look good. Add a CSS class to suggested products single paragraph, and create a <style> tag anywhere in your file and use that CSS class to applying styles as per your needs.

// Inside the loop in AJAX response, give CSS class
html += "<p class='product-list-item' onclick='selectProduct(this);' data-id='" + data[a].productCode + "'>" + data[a].productName + "</p>";

<style>
    .product-list-item {
        background: darkgray;
        color: white;
        width: 200px;
        padding: 15px;
        border-radius: 5px;
        cursor: pointer;
    }
</style>

That’s how you can create a customized auto complete view in HTML and Javascript.

[wpdm_package id=’235′]

Custom sort – jQuery UI, AJAX, PHP & MySQL

We are going to implement a custom sort using jQuery UI, which helps you to customize the order of data being displayed on your website. First, add CDN for jquery and jquery UI. Goto cdnjs.com to get CDN link for jQuery and visit this link to get CDN link for jQuery UI. Copy the JS link for jQuery, and CSS and JS links for jQuery UI. Create 2 script tags for jQuery and jQuery UI JS and one link tag for jQuery UI CSS.

index.php

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js">
</script>

First you need to show all data from database. Here we are connecting with our sample database and displaying all products based on their product code.

<?php

    $conn = mysqli_connect("localhost", "root", "", "classicmodels");
    $result = mysqli_query($conn, "SELECT * FROM products ORDER BY productCode DESC");

?>
  1. Create a div container which will enclose all data.
  2. Create a while loop to run through all records in database.
  3. Inside this loop, create a div tag which will represent each product separately.
  4. Give it a class so it will group each product under same class.
  5. and give it a unique ID, now ID will be the value which will tell the order of all products in an array. In our database, unique ID of product is productCode, so we will use that. But you must use as per your database table.
<div id="myData">
    <?php while ($row = mysqli_fetch_object($result)) { ?>

        <div 
            class="item"
            id="<?php echo $row->productCode; ?>"
            style="margin-top: 0px; margin-bottom: 0px;">
                
            <img
                src="<?php echo $row->image; ?>"
                style="width: 200px;">

            <h3><?php echo $row->productName; ?></h3>

        </div>
    <?php } ?>
</div>

Now we need to find a way to able to drag them so we can move them. So,

  1. Create a script tag.
  2. Attach a listener which will be called when the page is fully loaded.
  3. Select the div container using ID.
  4. Call sortable function, it exists in jquery UI. Its constructor will receive an object where you can specify options.
<script>

    window.products = [];
    
    $(function () {
        $("#myData").sortable({
            "items": ".item",
            "opacity": 0.6,
            "cursor": "move",
            "update": function (event, ui) {
                var data = $("#myData").sortable("toArray");
                
                // if using table
                // data = data.filter( n => n );

                window.products = data;
            }
        });
    });
</script>

jQuery UI sortable options

  1. “items”: Selector of each individual item. So we will use the div inside loop having class class=”item”.
  2. “opacity”: Give it an opacity, so when we select some product it will be highlighted among others.
  3. “cursor”: A cursor which will be displayed on div only during dragging an item.
  4. “update”: A function which will be called when you finish dragging some item from one place to another.

The update function has 2 parameters, events and UI (although we are not going to use any of them but you might need them in your case). Inside this function, we will get the new order of items in a variable. Select the main div container tag using its ID selector and call sortable function same as above. And inside it pass the argument “toArray”. It will return all items unique ID in a sorted array.

If you are using tables instead of divs, you might receive first element of array as empty string. You can prevent this by calling filter function to this array. Passing n means to remove null or empty strings.

Save custom sequence in database

Now we will create a button which when clicked will save this data in selected sequence.

<button type="button" onclick="saveData();">Save</button>

Create a function inside script tag:

function saveData() {
    var ajax = new XMLHttpRequest();
    ajax.open("POST", "save.php", true);
    ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    ajax.send("data=" + JSON.stringify(window.products));

    ajax.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            console.log(this.responseText);
        }
    };
}
  1. First create an AJAX object.
  2. Call open method and set the request method to “POST”.
  3. Second parameter will be the name of file where data needs to be sent.
  4. Since this is a post request, so we also need to attach a header for content type.
  5. And send the data will be in name value pair separated by ampersand sign.
  6. Since we want to send an array so we need to convert that into JSON string.
  7. onreadystatechange event will be fired when the response has been received from server.

save.php

Create a new file named “save.php” which will handle the request. First make a connection with database. Create a new table in database which will hold the sequence of products, its structure will be as below:

Table name: product_order, columns:

id integer auto increment
product_id integer
order_number integer
Then in “save.php” paste the following code:

<?php

    $conn = mysqli_connect("localhost", "root", "", "classicmodels");

    $data = json_decode($_POST["data"]);

    mysqli_query($conn, "DELETE FROM product_order");

    $sql = "INSERT INTO product_order(product_id, order_number) VALUES";

    for ($a = 0; $a < count($data); $a++)
    {
        $sql .= " ('" . $data[$a] . "', '" . ($a + 1) . "')";

        if ($a < count($data) - 1)
        {
            $sql .= ",";
        }
    }

    mysqli_query($conn, $sql);
    echo "Done";

?>

First get all data that we are receiving in a separate variable, and since we are sending JSON string so we need to decode that JSON back in PHP array. First of all, whenever the sequence of products changes, we have to remove all the previous sequence from database. Then we will prepare an SQL query to insert the new sequence in product order table. So loop through each product ID. Product ID will be what we are receiving from AJAX. Order number must be starting from 1, to 2 3 and so on, that is why we are incrementing in variable $a.

Display data by custom sort

Now go back to index.php and change the SQL query to following:

<?php

$conn = mysqli_connect("localhost", "root", "", "classicmodels");

$result = mysqli_query($conn, "SELECT * FROM products INNER JOIN product_order ON products.productCode = product_order.product_id ORDER BY product_order.order_number ASC");

?>

So we just need to change this query to display products based on order number from product_order table. Inner join with product_order, based on productID. And order by order_number from product_order table. Ascending order will make it start from 1 to 2 and 3 and so on.

That’s how you can implement a custom sort in jQuery UI using AJAX, PHP and MySQL.

[wpdm_package id=’219′]

Emoji ratings feedback – Javascript

Learn how to get feedback from your website users using emoji ratings. We will be using plain Javascript. No external library has been used in this tutorial.

Below is a list of all possible emojis at the time of writing this. You can found any new emoji missing, please do inform us in the comments section below.

SmileyHTML code
๐Ÿ˜€&#x1F600;
๐Ÿ˜&#x1F601;
๐Ÿ˜‚&#x1F602;
๐Ÿ˜ƒ&#x1F603;
๐Ÿ˜„&#x1F604;
๐Ÿ˜…&#x1F605;
๐Ÿ˜†&#x1F606;
๐Ÿ˜‡&#x1F607;
๐Ÿ˜ˆ&#x1F608;
๐Ÿ˜‰&#x1F609;
๐Ÿ˜Š&#x1F60A;
๐Ÿ˜‹&#x1F60B;
๐Ÿ˜Œ&#x1F60C;
๐Ÿ˜&#x1F60D;
๐Ÿ˜Ž&#x1F60E;
๐Ÿ˜&#x1F60F;
๐Ÿ˜&#x1F610;
๐Ÿ˜‘&#x1F611;
๐Ÿ˜’&#x1F612;
๐Ÿ˜“&#x1F613;
๐Ÿ˜”&#x1F614;
๐Ÿ˜•&#x1F615;
๐Ÿ˜–&#x1F616;
๐Ÿ˜—&#x1F617;
๐Ÿ˜˜&#x1F618;
๐Ÿ˜™&#x1F619;
๐Ÿ˜š&#x1F61A;
๐Ÿ˜›&#x1F61B;
๐Ÿ˜œ&#x1F61C;
๐Ÿ˜&#x1F61D;
๐Ÿ˜ž&#x1F61E;
๐Ÿ˜Ÿ&#x1F61F;
๐Ÿ˜ &#x1F620;
๐Ÿ˜ก&#x1F621;
๐Ÿ˜ข&#x1F622;
๐Ÿ˜ฃ&#x1F623;
๐Ÿ˜ค&#x1F624;
๐Ÿ˜ฅ&#x1F625;
๐Ÿ˜ฆ&#x1F626;
๐Ÿ˜ง&#x1F627;
๐Ÿ˜จ&#x1F628;
๐Ÿ˜ฉ&#x1F629;
๐Ÿ˜ช&#x1F62A;
๐Ÿ˜ซ&#x1F62B;
๐Ÿ˜ฌ&#x1F62C;
๐Ÿ˜ญ&#x1F62D;
๐Ÿ˜ฎ&#x1F62E;
๐Ÿ˜ฏ&#x1F62F;
๐Ÿ˜ฐ&#x1F630;
๐Ÿ˜ฑ&#x1F631;
๐Ÿ˜ฒ&#x1F632;
๐Ÿ˜ณ&#x1F633;
๐Ÿ˜ด&#x1F634;
๐Ÿ˜ต&#x1F635;
๐Ÿ˜ถ&#x1F636;
๐Ÿ˜ท&#x1F637;
๐Ÿ™&#x1F641;
๐Ÿ™‚&#x1F642;
๐Ÿ™ƒ&#x1F643;
๐Ÿ™„&#x1F644;
๐Ÿค&#x1F910;
๐Ÿค‘&#x1F911;
๐Ÿค’&#x1F912;
๐Ÿค“&#x1F913;
๐Ÿค”&#x1F914;
๐Ÿค•&#x1F915;
๐Ÿค &#x1F920;
๐Ÿคก&#x1F921;
๐Ÿคข&#x1F922;
๐Ÿคฃ&#x1F923;
๐Ÿคค&#x1F924;
๐Ÿคฅ&#x1F925;
๐Ÿคง&#x1F927;
๐Ÿคจ&#x1F928;
๐Ÿคฉ&#x1F929;
๐Ÿคช&#x1F92A;
๐Ÿคซ&#x1F92B;
๐Ÿคฌ&#x1F92C;
๐Ÿคญ&#x1F92D;
๐Ÿคฎ&#x1F92E;
๐Ÿคฏ&#x1F92F;
๐Ÿง&#x1F9D0;

Create input slider range

Create a div to display default emoji ratings, for example if you want the default feedback about communication to be “satisfied” then display the following emoji:

<div class="emoji-container">

<h3>Communication</h3>

<div class="emoji">
	๐Ÿ™‚
</div>

<p class="emoji-text">Satisfied</p>

<input type="range" name="status[communication]" min="0" max="4" step="1">
</div>

To view the emoji in large size, simply change the font size of emoji class. If you want to show the horizontal arrows for input type range, just change the cursor CSS property.

<style>
	.emoji {
		font-size: 60px;
	}
	input[type="range"] {
		cursor: ew-resize;
	}
</style>

Change emoji ratings with slider

Now create an array to store all type of emojis you want to display with your slider, and the meaning of each emoji in array of objects. Then we need to loop through all input type ranges and attach onmousemove listener to each slider.

Whenever the value of slider changes, we will get the emoji object using value of slider, and display it in emoji-container. This will replace emoji and its meaning text to whatever the value of current slider is.

If you are using only one slider in your document, you can use simply document.querySelector(“.emoji-container”) to get the container div of that emoji.

<script>
	var emojis = [
		{ emoji: "&#x1F621", text: "Hate it"},
		{ emoji: "&#x1F613", text: "Difficult to understand"},
		{ emoji: "&#x1F642", text: "Satisfied"},
		{ emoji: "&#x1F600", text: "Very happy"},
		{ emoji: "&#x1F618", text: "Loved it"}
	];

	var range = document.querySelectorAll("input[type='range']");
	for (var a = 0; a < range.length; a++) {
		range[a].onmousemove = function (event) {
			var index = this.value;
			var emojiContainer = this.closest(".emoji-container");

			emojiContainer.querySelector(".emoji").innerHTML = emojis[index].emoji;
			emojiContainer.querySelector(".emoji-text").innerHTML = emojis[index].text;
		};
	}
</script>

To save these feedback in database, enclose all your emoji-container divs in form tag and specify method as POST, and action to the file which will process this form data. If you sending input type file too, you also need to add an attribute enctype=”multipart/form-data” to form tag.

<form method="POST" action="save-feedback.php">
	<!-- All above emoji containers here -->
	<input type="submit">
</form>

Save data in database

We have created a simple database named tutorials and a table named feedback. It just has three columns, communicationservice and support. The data type of these columns will be INTEGER as in database we just be saving ratings on a scale of 1 to 5. First parameter in $_POST array will be name of input type range, and second will be the associative index we have set. Here we are receiving 3 types of feedback from user. The insert query is pretty basic.

save-feedback.php

<?php

$conn = mysqli_connect("localhost", "root", "", "tutorials");

$communication = $_POST["status"]["communication"];
$service = $_POST["status"]["service"];
$support = $_POST["status"]["support"];

$sql = "INSERT INTO feedback(communication, service, support) VALUES('$communication', '$service', '$support')";
mysqli_query($conn, $sql);

echo "Done";

?>

Change the emoji using slider and hit the submit button. You will see a new row will be inserted in database with integer value in respective columns. These integer values will tell the user feedback on a scale of 1 to 5.

Display on admin side

Now you might have an admin panel where you want to see the ratings given by user. So we will call a simple AJAX request to fetch those feedbacks from database. Our emojis array will remain same, and we can display the respective emoji based on database column value. First create an API page that will return all feedbacks in JSON format.

get-feedback.php

<?php

$conn = mysqli_connect("localhost", "root", "", "tutorials");

$sql = "SELECT * FROM feedback";
$result = mysqli_query($conn, $sql);

$data = array();
while ($row = mysqli_fetch_object($result))
{
	array_push($data, $row);
}
echo json_encode($data);

?>

Now back in index.php, we will send a simple AJAX request which will return all feedbacks in JSON string. We will parse that JSON into javascript arrays and objects. Create a div where all emojis needs to be displayed and display them using simple for loop.

<div id="feedback"></div>
var ajax = new XMLHttpRequest();
ajax.open("GET", "get-feedback.php", true);
ajax.send();

ajax.onreadystatechange = function () {
	if (this.readyState == 4 && this.status == 200) {
		var data = JSON.parse(this.responseText);
		var html = "";

		for (var a = 0; a < data.length; a++) {
			var communicationIndex = data[a].communication;
			var communication = emojis[communicationIndex];

			var serviceIndex = data[a].service;
			var service = emojis[serviceIndex];

			var supportIndex = data[a].support;
			var support = emojis[supportIndex];
				
			html += "<p>Communication: <span class='emoji'>" + communication.emoji + "</span>" + communication.text + "";

			html += "<p>Service: <span class='emoji'>" + service.emoji + "</span>" + service.text + "</p>";

			html += "<p>Support: <span class='emoji'>" + support.emoji + "</span>" + support.text + "</p>";
		}

		document.getElementById("feedback").innerHTML = html;
	}
};

Run this script on your admin panel and you will be able to view the user added feedback in emoji ratings and their meaning.

Learn how to calculate average ratings from here.

[wpdm_package id=’216′]

Multiple file upload in bootstrap modal – PHP & MySQL

We will teach you how you can create a bootstrap modal that handles multiple file upload and save them in MySQL database.

Download Bootstrap FileDialog

You are going to need a library called Bootstrap FD, you can get it from here. After downloading the library, extract the ZIP file and goto “dist” folder. Here you will find CSS and JS files, copy them in your project and include them in your header or footer. This library requires bootstrap and jQuery to be included in your project. If you have setup the bootstrap and jQuery, you can just use their CDN links rather than downloading.

<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>

<link rel="stylesheet" href="bootstrap.fd.css">
<script src="bootstrap.fd.js"></script>

First we have included the bootstrap CSS file, then jQuery and then bootstrap JS file. Because bootstrap JS also requires jQuery so you must include the jQuery before bootstrap JS. You can change the version number of CDN links if there is new version available.

Show multiple file upload dialog

Create a button which when clicked will call a function in Javascript. To open the bootstrap modal, we have to use the function $.FileDialog() and this will open the pop-up where you can drag and drop your files. For multiple file upload, we will not be using an input type file. But we will be using a library called FileDialog. You can also set options for this dialog, for example, whether you want the user to select only images files or all type of files etc.

<form>
	<button type="button" onclick="selectFiles();">
		Select files
	</button>

	<input type="submit">
</form>
<script>
	function selectFiles() {
		$.FileDialog({
			"accept": "image/*"
		})
	}
</script>

To preview the image files selected by user, just add a div tag and give it a unique ID.

<div id="selected-images"></div>

Preview selected images

And change your $.FileDialog function to the following. “files.bs.filedialog” function will be called when user select the files and press “OK”. Create a global array which will hold all images. All selected images will be received in “event.files” array, so loop through it and push in that global array. Create a string variable which will hold the img tag HTML. In the same loop, we are creating an img tag and each object of “event.files” array contains a variable named “content” while contains the content of image. This can be used.

window.selectedImages = [];

$.FileDialog({
	"accept": "image/*"
}).on("files.bs.filedialog", function (event) {
	var html = "";
	for (var a = 0; a < event.files.length; a++) {
		selectedImages.push(event.files[a]);
		html += "<img src='" + event.files[a].content + "'>";
	}
	document.getElementById("selected-images").innerHTML += html;
});

To save these images on server, give your form a unique ID and attach an onsubmit event with it. We will be using FormData object to send all images and other form fields via AJAX. And onsubmit event will prevent the default behaviour of form. This will prevent the form from submitting and will call your javascript function.

Call AJAX to upload file

This function will create a new FormData object and append all images in it. Make sure to add brackets “[]” with images key so it will send all images as array. Otherwise, only the last selected image will be processed by server. Then it sends a neat AJAX request in Vanilla JS and attach the form data in it.

After the server processed the files and send the response back to client, you will need to show some text to user or wants to redirect to different page. So in “onreadystatechange” event you can put all your code which needs to be executed once response is received from server.

<form id="form" onsubmit="return submitForm();">
function submitForm() {
	var form = document.getElementById("form");
	var formData = new FormData(form);

	for (var a = 0; a < selectedImages.length; a++) {
		formData.append("images[]", selectedImages[a]);
	}

	var ajax = new XMLHttpRequest();
	ajax.open("POST", "Http.php", true);
	ajax.send(formData);

	ajax.onreadystatechange = function () {
		if (this.readyState == 4 && this.status == 200) {
			console.log(this.responseText);
		}
	};

	return false;
}

Http.php

In this file, create a connection with your database (you might have already set up). Create a separate table where path of each image will be saved. Loop through all the images, insert them in database, and finally save the image file in your server. Create a new folder named “images” or any other of your choice, where all images will be stored. Timestamp is prepended with each image name just to make it unique. As you might have seen, if you download some image from facebook or whatsapp, it always has a different name no matter if that image is uploaded by another person.

<?php

$conn = mysqli_connect("localhost", "root", "", "tutorials");

for ($a = 0; $a < count($_FILES["images"]["name"]); $a++)
{
	$path = "images/" . time() . "-" . $_FILES["images"]["name"][$a];

	$sql = "INSERT INTO images(image_path) VALUES('$path')";
	mysqli_query($conn, $sql);

	move_uploaded_file($_FILES["images"]["tmp_name"][$a], $path);
}

echo "Done";

That’s how you can create a bootstrap modal that handles multiple file upload and save them in MySQL database in PHP.

Learn how to show progress bar while uploading the file.

[wpdm_package id=’213′]

Show progress of download with remaining time – Javascript

Convert time to different timezones

Learn how to show progress of download with remaining time in Javascript. We will be creating a simple bootstrap progress bar.

There are multiple ways to download a file from some website. The easiest way is to simply put an anchor tag with a text “Download”. And give the download attribute. Set the hypertext reference to the file which needs to be download. When the user clicks on it, the file will be downloaded using default browser download manager or via IDM.

However, there are some scenarios where that technique will not help. Take an example of a file with a very large size i.e. 1GB or greater, or a user running on a slow internet connection. The chances are the file may get interrupted during the download. In this case, user might have to re-download the file again. Even if he is using IDM, if the link gets expired then IDM will not resume the file. Instead it will download the file again from start.

Download file inside the browser

The second approach is to download the file inside the browser, show progress of download using a progress bar to the user. When the file is completely downloaded, then show a button which when clicked, will save the file in the selected destination on his computer. In this way, the file will be saved in the computer in just a couple of seconds. Because the file was already been downloaded inside the browser.

There are many other reasons for implementing this technique. For example, you can show advertisements to users until the file gets downloaded. This will help you monetize your website as well.

Get file from server

First we are going to get the file from the server and make it available for download. So, create a button that when clicked when send an AJAX request and get the file from the server. Also, an anchor tag must be created which will give the hypertext reference to the file when completely download in the browser. Lastly, we will add a progress bar which will show the progress of download.

<button id="download-button">Download</button>

<a id="save-file">Save File</a>

<progress id="progress" value="0"></progress>

Now in javascript, first we attach an onclick listener to the button. And call an AJAX request to the file which needs to be downloaded.

<script>
    var fileName = "Archive.zip";

	document.querySelector('#download-button')
		.addEventListener('click', function() {
			request = new XMLHttpRequest();
			request.responseType = 'blob';
			request.open('get', fileName, true);
			request.send();

			request.onreadystatechange = function() {
				if(this.readyState == 4 && this.status == 200) {
					var obj = window.URL.createObjectURL(this.response);
					document.getElementById('save-file').setAttribute('href', obj);

					document.getElementById('save-file').setAttribute('download', fileName);
					setTimeout(function() {
						window.URL.revokeObjectURL(obj);
					}, 60 * 1000);
				}
			};
	});
</script>

First we are creating an AJAX object. Note that the response type must be “blob”. By default, AJAX response type is text but since we wanted the download-able file to be returned from AJAX so we must set the response type to “blob”. In open function, first set the method of ajax which will be GET, then the second parameter should be the complete path of file which needs to be downloaded. We have created a variable where you can place your dynamic value. The first parameter will tell that the request must be asynchronous.

send() in AJAX

send() function will send the request to download the file and onreadystatechange will be called multiple times whenever the state of request changes. For example, when the request sent, when the request received and when the response is sent from the server. Here the readyState having value 4 and status having value 200 indicates the completion of request.

When the response is successfully received, we know that the response will be a downloadable file. Basically it will return the URL from where the user can save the file in his computer. So we will create an object using that URL, we will be using Javascript built-in URL object and call the function createObjectURL and pass the response received from ajax. Note that this response is not a responseText variable which is a string.

When the object is created using that URL, we will simply assign that as hypertext reference to our anchor tag. We are also setting the download attribute to anchor tag which tells the browser that the hypertext link to this anchor tag should be made downloadable.

revokeObjectURL

Since the object is created inside the browser, so it is also occupying some space. We can free it’s allocated resources after a few seconds. For example, the average size of file is 1GB and the user downloads 6 or 7 files, but if you do not free the object resources, then it might end up taking a lot of space in memory of your browser. So we are freeing the resources after 60 seconds, and we need to call the revokeObjectURL function and pass the object variable in it.

Display download progress

Now we need to create a progress bar and a text which will show the download percentage in textual format. In the above step, you can see that we have already created a progress tag, now we also need to create a span tag which shows the progress in percentage.

<span id="progress-text"></span>

<script>
	var progress = document.getElementById("progress");
	var progressText = document.getElementById("progress-text");

	request.onprogress = function(e) {
		progress.max = e.total;
        progress.value = e.loaded;

        var percent_complete = (e.loaded / e.total) * 100;
    	percent_complete = Math.floor(percent_complete);

    	progressText.innerHTML = percent_complete + "%";
	};
</script>

In javascript, first we are getting both nodes (progress & span) in separate variables. AJAX also provides us a method to track progress in an event called onprogress, it will have an argument and it tells the total amount of data that needs to be transferred (the size of file) and the which is currently been transferred so far.

We will set the total amount of data as the maximum value for the progress bar. And it continually changes the value of progress bar to the amount of data being transferred. So you will see the progress bar gradually moves from left to right as the file gets downloaded. The speed of progress bar depends on the size of the file and your internet connection.

File download percentage

So the progress bar has been set, now we display the percentage of the file downloaded in numbers. As we have already created a span tag in HTML and a variable for it in javascript. So we just need to calculate the percentage and display in span tag. We can calculate the percentage of the file downloaded by dividing the file currently downloaded by total size of file. That will return the value in between 0 and 1, for example 0.841. Multiplying this by 100 will return in 84.1 which means that 84.1 percent file has been downloaded.

If you do not want to display the decimal points with it, you can call the floor method and it will return the integer value. Then we simply set this percentage in span tag and add the percentage sign with it too.

Display transfer rate

At this point, if you were downloading that file via IDM or browsers default download manager, you will be able to view the downloading speed of your file. So our next step is to show downloading speed too. Create a simple span tag and get it in javascript as we did earlier. To get the downloading speed, we have to apply some math on it.

<span id="download-progress-text"></span>

<script>
    var downloadProgressText = document.getElementById("download-progress-text");

document.querySelector('#download-button')
		.addEventListener('click', function() {
    var startTime = new Date().getTime();
//// previous code in download button click listener
});

    request.onprogress = function(e) {
        var duration = ( new Date().getTime() - startTime ) / 1000;
    	var bps = e.loaded / duration;
        var kbps = bps / 1024;
        kbps = Math.floor(kbps);

        downloadProgressText.innerHTML = kbps + " KB / s";
    };
</script>

Getting the download speed means we need to know how much KB of data is transferred in one second. Since we are getting downloaded data in bytes so we can convert that in kilo bytes by simply dividing by 1024. First we will get the duration since the file started downloading till now. We can get it by getting the difference between current time and start time. That will return the time in milliseconds, so we can convert that into seconds by dividing with 1000.

When we get the total duration of AJAX then we can get the bytes transferred per second by dividing the data currently transferred by this duration. Now we have the Bytes per second, we can simply convert that to KB by dividing with 1024. Since there are 1024 bytes in one KB. This value may also be in decimal points, so we will convert that into integer too by using the same Math.floor() function. Lastly, we have set this variable in span tag and also display KB/s as string in it.

Get remaining time of download

The algorithm to calculate the remaining time is pretty simple. We get the difference between total size of file and the file currently being downloaded, and divide that by amount of data downloaded in bytes per second. This gives the time in seconds. But we need to show it in minutes too. For example, if this returns 90 seconds, then we need to display it as 1 minute and 30 seconds.

request.onprogress = function(e) {
        ...

        var time = (e.total - e.loaded) / bps;
        var seconds = time % 60;
        var minutes = time / 60;

        seconds = Math.floor(seconds);
        minutes = Math.floor(minutes);

        progress.setAttribute("aria-valuemax", e.total);
        progress.setAttribute("aria-valuenow", e.loaded);
        progress.style.width = percent_complete + "%";
        progress.innerHTML = percent_complete + "%";

        downloadProgressText.innerHTML = kbps + " KB / s" + "<br>" + minutes + " min " + seconds + " sec remaining";
};

No need to create another span tag for it, we will display this data inside span we created for displaying transfer rate. We use the modulus operator to get the remaining seconds, and we apply that to 60 since there are 60 seconds in 1 minute. Similarly, we can divide the time to 60 and it returns the time in minutes since 60 seconds composed of 1 minute.

These seconds and minutes may also be in decimal points, so we convert them to an integer using Math.floor() function as above. Lastly, we are appending that along with KB/s and prepending a line break (<br>) for readability.

Abort ajax request

We can abort any AJAX request using simple abort() function from ajax object. So we are simply creating a button which when clicked will abort the ajax request and you will see that progress of download, text, seconds and minutes will be stopped.

<button onclick="request.abort();" type="button">Abort</button>

Conclusion

This tutorial does not include any external library like jQuery. So you should be able to apply this in your project without having to include any library. It only contains Vanilla JS.

Though we could have use the NetworkInformation API to check transfer rate but it does not support all browsers at the time of writing this. So we do not want you to implement this in your website. Then later find out that your users are having problem downloading the file ๐Ÿ™‚

We have tried to create this tutorial as simple and accurate as we can. But if you still find any problem on our side, please do not hesitate to get in touch with us.

[wpdm_package id=’209′]

Lazy load images – Javascript

Lazy load images means loading images on websites asynchronously. Lazy loading is technique that defers loading of non-critical resources at page load time. Instead, these non-critical resources are loaded at the moment of need. Where images are concerned, “non-critical” is often synonymous with “off-screen”. If you’ve used Lighthouse and examined some opportunities for improvement, you may have seen some guidance in this realm in the form of the Offscreen Images audit.

Intersection observer API

The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document’s viewport.

We are going to use 2 images. One will be displayed on top and second will be at the bottom of page. You have to scroll a lot to see the second image. Now you will see that the second image will only be loaded once the user scrolled to the second one. So this will decrease the page load time and hence improves the performance of your website.

First create 2 image tags and give class attribute to access it in Javascript and data-src attribute. It is a custom attribute which we can use to get the actual path of image. DO NOT use src attribute as it will actually load the image, which we do not want. Give both images width as 100% so they will be completely visible inside the browser window.

<!-- Displaying first image -->
<img data-src="image-1.jpg" class="image" alt="1"><br>

<!-- Displaying second image but at bottom -->
<img data-src="image-2.jpg" class="image" alt="2" style="margin-top: 1000px;">

<!-- Image should not overflow the window -->
<style>
	.image {
		width: 100%;
	}
</style>

Load image when scrolled

Then we create a built-in intersection observer which will be called automatically when page is scrolled and will return the items which are visible. We can check if each item is intersection (inside the browser window). We will get the data-src attribute and place it as src attribute, so in this way it will be loaded asynchronously. Once an image is loaded we do not want it to be loaded again, so we will disable it from observing again by calling the unobserve(item) method.

<script>
	// IntersectionObserver is a built-in javascript object
	var observer = new IntersectionObserver(function (items, self) {

		// Loop through all visible items
		for (var a = 0; a < items.length; a++) {

			// Check if item is in visible area of browser
			if (items[a].isIntersecting) {

				// Debug the img tag
				console.log(items[a].target);

				// Get image data-src (custom) attribute
				var src = items[a].target.getAttribute("data-src");

				// Load the image
				items[a].target.setAttribute("src", src);

				// Should not call this function for same image again
				self.unobserve(items[a].target);
			}
		}
	});
</script>

At this point if you run the script, nothing happens. Because we havn’t tell it which items needs to be observed. Since we have given a class attribute to images so we can get all images having that class. Loop through each image and set it to be observed by observer using it’s instance.

<script>
	// Get all images
	var image = document.getElementsByClassName("image");

	// Loop through each image
	for (var a = 0; a < image.length; a++) {
		// Make it observable
		observer.observe(image[a]);
	}
</script>

Conclusion

There are also many libraries available which can do the lazy loading for you. But nothing gives more control than writing your own code. So using this Vanilla JS way you can use intersection observers to lazy load images you want as per required.

[wpdm_package id=’197′]