In this tutorial, we are going to teach you how you can count the number of words in textarea as user type in it. The first thing you need to do is to attach an onkeyup listener to your textarea tag. This function will be called whenever user pressed the key. Specifically, when the user’s finger is moving upwards after pressing the key, then this event is called. In this function, we are passing a parameter this means current node, which is textarea tag.
1
2
<textareaonkeyup="countWords(this);"></textarea>
<spanid="words-counter"></span>
Then we created a span tag, you can create a div or paragraph as well. Give that span tag a unique ID so it can be accessible in Javascript. We will be displaying the number of words in this span tag.
Then we create this function in Javascript, first, we are getting the current text inside textarea field using the value attribute. Then we are applying a regular expression which states that:
Count the number of words separated by spaces.
This will return an array, we simply have to calculate the length of that array. We are using a ternary operator to get value as 0 if the spaces array is null. Finally, we are displaying that length in the span tag using plain Javascript.
1
2
3
4
5
6
functioncountWords(self) {
varspaces = self.value.match(/\S+/g);
varwords = spaces ? spaces.length : 0;
document.getElementById("words-counter").innerHTML = words + " words";
}
That’s how you can count the number of words as user type in an input field using plain HTML and Javascript.Specifically in a <textarea> tag.
To shuffle an array of objects or single values in Javascript, use the following function:
1
2
3
4
5
6
for(vara = 0; a < data.length; a++) {
varx = data[a];
vary = Math.floor(Math.random() * (a + 1));
data[a] = data[y];
data[y] = x;
}
First, we are looping through all array elements. data is our array of objects. First, we are saving the current array element in a separate variable named x. Then we are generating a random number. Math.random() will return a random number between 0.0 and 0.9. As our loop start from 0, so we are multiplying that random number by loop iteration number + 1. Since the number will be in floating points, so we can convert that into an integer by calling Math.floor() function. The floor function will round the number downwards and return it as an integer. That is now the index of the random element in the array.
Then we are replacing the current array element with this random array element. And finally, replace this random array element with the current element of loop.
This is the simplest way to shuffle an array of objects using vanilla Javascript. For more Javascript tutorials, please follow here.
In this tutorial, we are going to teach you how you can show a confirmation dialog before deleting any data using Javascript. Suppose you are displaying a lot of data in tabular form in the admin panel, and you have a delete button at the end of each row. Now when someone clicks on it, you may be submitting a form with POST request or redirecting to a page where that data will be deleted. But what if someone accidentally clicks on any row, or clicks the wrong row? Then that row will be deleted from the database.
Alternative
One alternative thing you can do is to put the deleted data in the trash. That will add extra work on the developer side as well as on the user side. Because you have to create a table where trashed data will be stored, then create another page on the admin panel to display trashed data and also the ability to delete or restore the trashed data. You can see that there are 6 or 7 more functions that you have to write. Moreover, there will be extra work for users too, they also have to delete the trashed data regularly.
A simple approach
A simple approach displays a confirmation dialog when the delete button is clicked. Show simple 2 buttons, “Cancel”, “Delete”. When the delete button is clicked from confirmation dialog, then send the request to delete that data from the database. You may encounter yourself in 2 minor problems in this approach. First is “how can I display a confirmation dialog ?”, you can either display javascript native function confirm() but it may not look good with your website design.
People want a more personal look, whenever you are displaying a dialog box, whether it is alert dialog or confirmation dialog, make sure that it goes with the look and feel of your website design. Or you can use external libraries like “Sweetalert“, so you have to download that library, include in your project, and use their functions. But sometimes you do not have your project flooded with external libraries. You may ask yourself “why to include an external library when I can do it in my design framework ?”
As we know that today almost every website is using Bootstrap and your project will also be using a large portion of the Bootstrap framework. So we are going to use Bootstrap to display a confirmation dialog. In Bootstrap, they are called “modal”.
Bootstrap modal
Bootstrap modal can be created by creating a <div> tag and give it a unique ID, also a class named “modal”. There will be 2 inner nested divs, one with class “modal-dialog” and second having class “modal-content”. Modal content div will have 3 sections:
modal-header
modal-body
modal-footer
What we are going to do is to show heading in modal-header div, and create a form in modal-body div, in this form we will create a hidden input field which will be the unique ID of row which needs to be deleted from database. Set the form action attribute to the page where you will handle to perform the delete action. In modal-footer, we will simply create a submit button which will be linked with that form using form attribute. Make sure the form attribute on submit button will be same as form id attribute.
Now create a delete button (or change if you already have one) such that it has an attribute data-id and its value must be the unique ID of that row. Attach an onclick listener which will be called whenever that button is clicked. In this event, we are calling a function named confirmDelete. You can create this delete button inside your table row where you are displaying all data from the database (typically in while() loop).
Now when the button is clicked, we want to set the value of the hidden input field inside the bootstrap modal form to the id of the selected row. Then we will show the confirmation modal. Create the following function in <script> tag:
Make sure you have given a name attribute to the hidden input field. It will help you to set the value using Javascript before displaying the confirmation dialog. Also, the name attribute is used at the server-side to get the values. Now you will be asked for confirmation before deleting any data from the database WITHOUT USING ANY EXTERNAL LIBRARY other than Bootstrap.
If you are developing backend in PHP, then you can get this value using $_POST[“id”].
Today, we will learn to calculate the time passed since 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 calculating the time remaining. If you want to caclulate the remaining time in future date, you can follow our tutorial on that as well:
Calculate remaining time
Calculate time passed
Basically, we are going to get the difference between future date and current date. 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:
1
2
3
<?php
$date= "2020-06-07 23:39:00";
?>
Then we will create a <div> where we will display the time passed and a hidden input field to get the PHP variable value in Javascript.
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 time passed 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.
Get difference in timestamps
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. 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 future timestamp from current 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 difference in minutes
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 passed since 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.
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:
1
2
3
<?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.
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.
In this article, we will teach you how you can change the hashed password of a user in PHP.
Before you proceed, make sure you have PHP version 5 or greater than 5 till 5.5.0 (PHP 5 >= 5.5.0) or PHP 7. You can check your server’s PHP version by creating a new PHP file and write the following code in it:
1
2
3
<?php
phpinfo();
?>
This tutorial uses PHP password_hash and password_verify functions that allows you to save passwords in MySQL database as hashed strings, so even if your database gets hacked or someone tries to read it, he will still not be able to find the actual passwords of users. For the sake of simplicity, we are going to use a sample table named “users” in MySQL database and it will have just 4 columns:
ID (int, auto increment primary key)
name (text)
email (text)
password (text)
Create an HTML form
Our form will contain 3 fields:
Current password: to check if user has entered its current password correctly.
New password
Confirm password
Paste the following code in page where you want to allow user to change their password (make sure to change the form action attribute to your desired filename):
When you submit the form above, it will send the data to “index.php” page. If you have written any other filename in “action” attribute, paste the following code in that PHP file:
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:
customers
employees
offices
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.
// 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
echojson_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.
1
2
3
4
5
6
7
8
<!-- Create divs which needs to be loaded by ajax -->
When it comes to deploy Node JS app, Heroku is by far the most feasible choice for beginners and startups. In this tutorial, we are going to teach you how you can deploy your Node JS application on Heroku and make it accessible from everywhere.
It is very common when we start building our Node JS apps, we mostly work on our localhost for faster testing. But when there is a time to make it live or connect it with your android or iOS application, you definitely need to publish it on some hosting provider. Heroku in this regard will help us to publish our Node JS app on their server.
Let’s get started
We are going to create a simple “Hello world” app in Node JS and publish it on Heroku.
First create a new folder where we will place all our Node JS files. If you are already working on some Node JS project, then you can use your existing folder too. Create a file named “server.js”, this will be our main server file. Open the command prompt in your project and initialize NPM in it, make sure you have Node JS installed in your computer. You can download Node JS from here:
cd "your_project_root_folder"
npm init
Install modules
Install express and Http modules in your project, they will be used to start the server at a specific port. After installation, we are going to start the server using nodemon command. If you do not have nodemon, you can install it by running “npm i nodemon” in your terminal. Run the following command in your terminal to install express & Http modules and start the server:
npm install express http
nodemon server.js
Now we will create instances of express and Http modules and start the server at port 3000. Specifying the port will work on the localhost, but when we deploy any app on Heroku, Heroku automatically assigns some port number from itself and save that port number in the “process” object’s “env” object. So we will add an OR operator to set port number if it is being received from Heroku, otherwise (if in localhost) start at 3000. Paste the following code in your server.js file:
If you test the app now at URL “http://localhost:3000/” you will see a “Hello world !” message. Now we need to deploy on Heroku, goto Heroku and login or signup if you have’nt already created an account.
Deploy Node JS on Heroku
Now download and install the Heroku CLI. Run the following command in your terminal to login, it will open the browser, just hit “Login” in opened web page. Also make sure that you have Git installed too, you can download it from here:
heroku login
// Initialize a Git repository
git init
// Point remote address towards your Heroku app
heroku git:remote -a your-app-name
// Add all files in Git
git add .
// Commit all files
git commit -am "Initial commit"
// Deploy all files on Heroku
git push heroku master
After the final command, you will see a link of your app which you can use to run directly in the browser. Moreover, in your Heroku dashboard, you can click on “Open app” button and it will take you to your app’s home page.
Learn how to deploy Node JS app with Mongo DB and Vue JS from here.
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:
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.
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.
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.