Add or update URL query parameter in Javascript

Create the following function in Javascript to add or update URL query parameter.

function addOrUpdateURLParam (key, value) {
    const searchParams = new URLSearchParams(window.location.search)
    searchParams.set(key, value)
    const newRelativePathQuery = window.location.pathname + "?" + searchParams.toString()
    history.pushState(null, "", newRelativePathQuery)
}

Now, whenever you want to add or update the URL, simply call the function in the following way:

addOrUpdateURLParam("name", "adnan-tech.com")

The first parameter will be the key of the parameter, and the second will be the value.

window.location.search: will return all the query parameters starting from “?”.

URLSearchParams: This will create an instance of URLSearchParams that will be used to manipulate URL query parameters.

searchParams.set(key, value): This will set the key value provided in arguments, but will not display yet in the URL.

window.location.pathname: It returns the relative path starting from “/your_website”. It DOES NOT include the query parameters starting from “?”.

searchParams.toString(): Will convert all the key-value pairs to a string. If there will multiple parameters set, then they will be separated by the “&” sign.

history.pushState: Will actually display the query parameters in the URL.

The first parameter to the “history.pushState” function is the “state”. It can be a push, pop, or null. The second parameter is not used anymore but not removed either, passing an empty string is safe. The third parameter is the new URL, here we are passing our new string variable to set the new URL with query parameters. More information can be found here.

Video tutorial:

Following this tutorial, I hope you will be able to add or update query parameter in your website’s URL using Javascript. If it helps, check out our tutorials on Javascript.

Ecommerce website in MEVN stack

It is a single-page ecommerce website developed in Vue JS. Vue JS is an open-source Javascript framework specifically built to design user interfaces and is widely used for creating single-page applications.

Node JS is a Javascript run-time environment developed for creating the backend of applications. Its framework Express is widely used for creating APIs. It is built to create scalable applications.

Mongo DB is a no-SQL database. It is a non-relational database system. It is easily scalable because the data is loosely coupled.

FeaturesFreePremium $100
Product management (admin panel)YesYes
Product listingYesYes
Product detailYesYes
Shopping cartYesYes
Checkout (PayPal & Stripe)YesYes
Order management (admin panel)YesYes
Order detailYesYes
Product specificationsYesYes
Stock managementYesYes
Search and sortYesYes
New order emailYesYes
Product reviewsNoYes
Shipping charges by countryNoYes
Product image compressionNoYes
Realtime chat between users and adminNoYes

Following is the feature list of this project:

  • Product management (admin panel)
  • Product listing
  • Product detail
  • Shopping cart
  • Checkout (PayPal & Stripe)
  • Order management (admin panel)
  • Order detail
  • Product specifications
  • Stock management
  • Product reviews
  • Search and sort
  • Shipping charges by country
  • Email to admin whenever a new order is placed
  • Product image compression
  • Realtime chat between users and admin

Add product

Admin will be able to add products. He will enter the name of the product. Add a little description of the product. And set the price of the product. The price will be in dollars. Along with them, the admin can upload one or more images of the product.

Product listing

Users will see the products added by the admin on their home page. The latest products are displayed first. Along with each product, a button will be displayed to view the detail of the product.

Product detail

Users can view the detail of the product. If the product contains more than one image, then it will be displayed as a beautiful slider. From this page, users will also be able to add products to the cart. If the product is already added to the cart, then he will be able to remove it from the cart.

Shopping cart

Users can add the product to the cart. From the cart’s page, he will be able to adjust the quantity of the product. There will be multiple products in the cart and you can set the quantity of each product separately. You will also see your total bill as soon as you change the quantity of any product added to the cart.

Checkout (Stripe & PayPal)

After adding the products to the cart and setting each product’s quantity, the user can go to the checkout page. Here, he can either pay via Stripe or PayPal. Both payment methods accept debit and master cards securely. When the user made the payment, his payment is verified from the server. If verified, then a new order will be created in the database.

Order management

Whenever a user made a payment via Stripe or PayPal, an order will be created. All orders will be displayed on the admin panel ordered by latest to oldest. By default, the status of the order is “Processing”. But admin can change the status of the order to “Completed” when the product is delivered to the customer.

Admin will also be able to view the total amount of the order, the payment method customer has used, and the user’s shipping details.

Order detail

Admin can view all the products that were included in each order. He can manually verify the payment by clicking the payment method. If he clicks “Stripe”, he will be redirected to the Stripe payments page. If he clicks “PayPal”, then he will be redirected to the PayPal business page. Admin can check the name, email, and phone of the user and also his shipping address.

Product specifications

Admin can add the specifications of each product and the user will be able to see it on the product detail page.

Stock management

Admin can set the number of units in stock for each product. When the user makes an order, then the number of units he has selected will be subtracted.

Product reviews

User can give reviews on a product and it will be displayed to all users who visit that product. Admin will have the ability to remove any review, for example, spamming, etc.

Search and sort

Users can search by product by its name, description, category, or specifications. Users can also sort the products by date or by price.

Shipping charges by country

Admin can set the shipping charges by each country because, in a global eCommerce website, users place orders from all over the world. For example, if your store is located in USA and someone places an order from the UK. Then you charge the shipping fee differently than other countries.

Email to admin whenever a new order is placed

Admin will receive an email whenever a new order has been placed by the user.

Product image compression

Now you can compress the product images from the admin panel. The 3 MB image can be reduced to just 182 KB and the image will still be of great quality.

Realtime chat between users and admin

Users will be able to have a chat with the admin to know more about a product before placing an order. I believe every eCommerce website should have this feature.

We are constantly updating this project and adding more features and enhancements to it. Following are all the builds that are released till today.

  • In the very first release, we build the basic E-commerce version where the admin can add products and users can see them. Add them to carts and order them. We also added Stripe and PayPal payment methods.
  • In the second release, we added more features. Allowing users to give reviews about a product. Allowing admin to charge a different shipping fee for each country and many more.
  • In the third release, we added functionality to compress product images and to have real-time chat between users and admin.

Free version

https://github.com/adnanafzal565/ecommerce-mevn-stack

Share local storage between websites – Javascript

In this article, we are going to teach you, how you can share local storage between websites using Javascript. Local storage is not accessible even within subdomains. So if I set the value in one subdomain, it will not be accessible in another subdomain.

Video tutorial:

To share the local storage value between websites, first, we need to create an iframe tag in the source website.

<iframe src="http://destination-website.com/saveLocalStorage.php" style="display: none;"></iframe>

The value of src attribute will be the path of the destination website. And we will hide the iframe using the CSS property display: none; so it will not be visible on the source website.

Then we will create a script tag and call a function that will be called when the page is loaded. You can also call it on any function you want, for example, when the user is logged in, you want to share the user’s authentication token to another website. In that case, you can write the below code inside your login function, but for the sake of simplicity, we are calling it inside the page load function.

<script>
    window.addEventListener("load", function () {
        // [code goes here]
    })
</script>

The following code will go inside the section. First, we will get the iframe DOM object.

const iframe = document.querySelector("iframe")

Then we will get the iframe content window.

const wind = iframe.contentWindow

Then we will set the data that needs to be sent.

const data = {
    name: "adnan-tech.com"
}

After that, we will call the postMessage function from the iframe content window object i.e. wind. The second parameter of the postMessage will be * in double quotes which means there is no preference for target origin.

wind.postMessage(JSON.stringify(data), "*")

You can learn more about it here.

Now we will come to the destination website, the file name will be saveLocalStorage.php. Create a script tag and attach a listener that will be called when the message is received. The second parameter will be a function and it will have an argument event (e).

<script>
    window.addEventListener("message", function (e) {
        // [destination code goes here]
    })
</script>

The following code goes in the [destination code goes here] section. First, we will check if the origin of the message is our source website because otherwise, any other website can also send post messages as well. If the origin of the message is not from our source website, then we will do nothing and stop the function.

if (e.origin !== "http://source-website.com") {
    return
}

// [parse data object]

If the message is from our source website, then we will first parse the data from a JSON string to a javascript object. Write the code in the [parse data object] section.

const data = JSON.parse(e.data)

Then we will check if the message has a name field.

if (typeof data.name !== "undefined") {
    // [save in local storage]
}

If it has, then we will set it in the destination website's local storage. Also, we will log the message that will be displayed in the source website's console tab. The following code goes in the [save in local storage] section:

localStorage.setItem("name", data.name)
console.log("Name is set: " + data.name)

Save the destination website file and refresh the source website. The name will be set, and you will see that message in your source's browser console. If you open your destination website's browser console and type localStorage.getItem("name"), you will see the name that you can send from the source website. Then you can use that value in the destination website in any way you like.

Complete code: Share local storage between websites in Javascript

<!-- source.php -->

<iframe src="http://destination-website.com/saveLocalStorage.php" style="display: none;"></iframe>

<script>
    window.addEventListener("load", function () {
        const iframe = document.querySelector("iframe")
        const wind = iframe.contentWindow
        
        const data = {
            name: "adnan-tech.com"
        }
        
        wind.postMessage(JSON.stringify(data), "*")
    })
</script>
<!-- http://destination-website.com/saveLocalStorage.php -->

<script>
    window.addEventListener("message", function (e) {
        if (e.origin !== "http://source-website.com") {
            return
        }
        
        const data = JSON.parse(e.data)
        
        if (typeof data.name !== "undefined") {
            localStorage.setItem("name", data.name)
            console.log("Name is set: " + data.name)
        }
    })
</script>

So that's how you can share local storage value from one website to another using Javascript. If you face any problems in following this, kindly do let me know. Check out our more tutorials on Javascript.

[wpdm_package id='1801']

Promise and async await in Javascript

Promises are created in Javascript to prevent the callback hell. But it came with its own problems and complexities. To deal with them, we were introduced to async and await commands. So today, we are going to teach you, how you can create a promise in Javascript, and how to call it using async/await command.

Video tutorial

Basic example of promise with async await

Let’s start with a basic example. We are going to create a simple Javascript function that will return a promise. The promise will call the callback function with a string value.

function doSomething() {
	return new Promise(function (callBack) {
		callBack("Response")
	})
}

To use the async and await commands, we need to create another function that will use these commands.

async function callDoSomething() {
	const response = await doSomething()
	console.log(response)
}

The function name will be prepended with async and the function that returns a promise i.e. doSomething() will be prepended with await command. In this case, the response variable should print “Response” that was called at line 3 of previous code.

Finally, we simply need to call the callDoSomething() to run the code.

callDoSomething()

Run the code now, and you will see “Response” in your browser console. Try change the string value of callBack parameter and you will see that it will be reflected in response variable in callDoSomething() function.

Practical example

Let’s move to a more practical example. Let’s say you want to call an AJAX request from the promise. And instead of receiving the response in a callback, you want to receive it using async/await command.

So go ahead and change the doSomething() function to the following:

function doSomething() {
	return new Promise(function (callBack) {
		const ajax = new XMLHttpRequest()
		ajax.open("POST", "server.php", true)

		ajax.onreadystatechange = function () {
			if (this.readyState == 4) {
				if (this.status == 200) {
					callBack(this.responseText)
				}
			}
		}

		const formData = new FormData()
		ajax.send(formData)
	})
}

The code is self-explanatory but if you want to know more about the XMLHttpRequest, we have created a separate detailed tutorial on this.

Then we will create a simple PHP file that will return a simple string as response. Create a new file named server.php and write the following code in it:

<?php

sleep(1);

echo "Response from server";
exit();

We are calling the sleep() function just to give it 1 second delay. If you run the code now, you will start seeing “Response from server” in the browser console.

[wpdm_package id=’1720′]

Single page application in MEVN stack – Realtime chat

In this article, we are going to provide you with a free course to develop a full-fledged real-time chat app in MEVN (MongoDB, Express, Vue JS, and Node JS) Stack. Here M stands for MongoDB which we have used as a database. E stands for Express which is a Node JS framework. V stands for Vue JS which will be our front end. We will be creating a single-page application in Vue JS. And N stands for Node JS which will be our backend.

You can download Node JS from here. And Mongo DB from their official site.

FeaturesFreePremium $100
Sign upYesYes
Login/logoutYesYes
Add contactsYesYes
Private chatYesYes
Message encryptionYesYes
Chat with attachmentYesYes
Realtime chatYesYes
Email verificationNoYes
Reset passwordNoYes
User profileNoYes
Chat with emojisNoYes
Bookmark messagesNoYes
Copy messageNoYes
Archive chat with passwordNoYes
Group chatNoYes
Notifications pageNoYes
Customer supportNoYes

We will do the deployment of this app on live servers. You can find the link to all the tutorials of this series here. Following are the topics we have covered in this series.

Installation of Node JS server

In the very first tutorial, we have done the installation of the Node JS server. We also connect our Node JS server with MongoDB. You can find the tutorial here.

Setup Vue JS CLI – A single page application

Then we set up our Vue JS app using CLI. We used Vue JS CLI because we will be creating a single page application. We will be using Vue 3. Right now, we will be using the app on the local server. But once it is done, we will teach you how you can create a production build of it. And also how you can make it live on your website. This tutorial can be found here.

Routing for single page application

As this is a single page application, so we will be doing routing using Vue components. You can learn how to implement routing in a single page Vue JS app from this tutorial.

Hello world

In this part, we will learn how to integrate Bootstrap into your Vue app. So you can design the theme as per your choice. We also show you how you can create header and footer layouts in Vue JS. The header and footer will be displayed on each page. For the header, we will be creating a simple Bootstrap navbar. And for the footer, we will simply be displaying copyright text and the current year dynamically.

Registration

You will learn how to display a form using Vue JS. Sends the form values to the Node JS server. And how Node JS can save the data in the MongoDB database. You will also learn how to check if certain data exists in MongoDB or not. Moreover, you will also learn how to encrypt the passwords before saving them in MongoDB. So even if your database gets stolen, your user’s passwords will remain unknown to the hacker.

One more thing you will learn in this part is how to deal with CORS (Cross-Origin Resource Sharing) errors in the Node JS server.

Email verification

After successful registration, an email will be sent to the user’s email address. That email will have the verification code. And the user will be redirected to a page where he can enter his verification code.

He will not be able to log in until he verifies his email address.

Login

In this part, we do the authentication. You will learn how to generate JWT (JSON Web Tokens) and how to store them in local storage for future usage. You will also learn how to validate the encrypted passwords saved in MongoDB while authenticating.

Reset Password

If a user forgets his password, he can reset it. He just needs to enter his email address. An email will be sent to him with a link to reset the password. When he clicks that link, he will be redirected to a page where he can enter his new password.

Get logged-in user’s data

We will learn how to call AJAX with headers in Vue JS. How Node JS server read the headers? And how to create middleware in Node JS.

Logout

We will teach you how to log out as a user from MongoDB and from the Vue JS client app. We will remove the JWT token we create in the login part.

Contacts

To chat with people, we need to add them to our contacts. We will be creating separate components in the Vue JS app for adding and displaying all contacts. We will also be creating a new module in the Node JS server. You will learn how to insert data in a nested array in MongoDB.

We will be calling AJAX requests using Axios in Vue JS. While deleting a contact, you will learn how to ask for confirmation using sweet alert dialogs.

You will also learn how to remove an element from a nested array in MongoDB.

Chat with attachments

This is the main module of this app. We advise you to please put more focus on this part. It teaches you how to import CSS in specific Vue components only. How to send input type file from the Vue JS app to the Node JS server. How Node JS saves files on the server.

Encryption and Decryption

We are saving messages in MongoDB in encrypted form. While fetching the messages, we are again decrypting the messages back to their original state. Even if someone has access to your database, he will not be able to read your messages. Because he does not have the key. The key will only be stored on the Node JS server.

You can see the messages are fully encrypted. On the home page, where we are displaying all user’s contacts, we will also be displaying unread messages from each contact.

Attachments uploaded with messages are also protected from direct URL access. So we will show you how you can convert a file in base64 string using Node JS. And download them to your system using the Vue JS app.

Realtime chat using Socket IO

Chat will be real-time. Meaning users do not have to refresh the page to see new messages. He will automatically receive a notification. If the chat is opened, then the incoming message will be appended automatically.

We have “load more” functionality. This means that we will only show 10 messages in each AJAX call. To get the previous 10 messages, the user will click on that button and we will fetch 10 more messages. So you will learn pagination using Node JS and Mongo DB too.

Deploy Node JS, Mongo DB, and Vue JS apps

We will be deploying our Node JS server on Heroku. You can check our Heroku guide here. We will be deploying MongoDB on mongodb.com. And we will be deploying our Vue JS app on any hosting provider we choose. For example, a2hosting, Bluehost, Siteground, etc. We will create a production-ready build of our Vue JS app and upload it on our live server.

However, you might face some problems going live. That’s why we have written a detailed complete tutorial on the deployment on all these 3 platforms.

Search Contact

You can search your contacts by their email address. Searching with their email address points you to the right person. Because multiple people can have the same name. But email is unique in the entire “users” collection in MongoDB.

Group chat

Previously we discussed private chat. In this tutorial series, we also cover the group chat feature. You will be able to create groups. Add members to the groups. You will be sending an invitation to the members to join the group. The other person can accept your request to join the group or can ignore it.

Any member can leave the group anytime he wants. But this is not the case for admins. For the admin to leave the group, he must first assign someone else to the admin of the group. The other person must be a member of the group. After assigning someone else as an admin, he can easily leave the group.

People who are not members or the admin of the group, cannot send or view the messages in the group chat.

The chat in the group is also real-time. All the other members of the group will get a notification when someone sends a message. If they have opened the group, then the new message will automatically get appended at the end of the chat.

Group chat is also end-to-end encrypted.

And same as we did for private chat, we are displaying several unread messages from a group on the page where we are displaying all groups.

Emojis

In chat, you can also send emojis to the recipient. Emojis are also encrypted.

Bookmark message

You can also bookmark your favorite messages. This way, you can always see your bookmarked messages whenever you want. You can bookmark your messages as well.

Copy message

If someone sends you a lengthy message, like an essay. You can copy the whole message with a single click.

Archive chat with password

  • You can archive your private chat with a password.
  • Once archived, no one will be able to view the chat.
  • To view the chat, you must provide the correct password.
  • You can remove the password by simply entering the correct password.
  • Archived chats cannot be deleted. You must first un-archive the chat, then delete it.

Re-designed

I re-designed the website into a beautiful template. That’s how it looks now.

So you will be learning to create a full-stack chat app from scratch using Node JS, Mongo DB, and Vue JS. Again, you can find the tutorial for the complete series here. Enjoy!

Free version

https://github.com/adnanafzal565/spa-chat-app-mevn

Our Trustpilot reviews

Encrypt and Decrypt Strings using Node JS and Mongo DB

In this tutorial, we are going to teach you, how you can encrypt and decrypt the strings using Node JS and Mongo DB. The encrypted strings will be saved in the database and upon retrieval will be decrypted.

Setup the Project

First, create an empty folder and open a command prompt in it. Then run the following commands in it one by one:

npm init
npm install express http mongodb crypto ejs
npm install -g nodemon
nodemon server.js

crypto module will be used to encrypt and decrypt the strings. ejs module will be used to render HTML files. Then create a file named server.js at the root of folder. Open server.js file and write the following code in it:

// initialize express JS
const express = require("express");
const app = express();

// create HTTP server
const http = require("http").createServer(app);

// [include Mongo DB module here]

// start the server
http.listen(process.env.PORT || 3000, function () {
    console.log("Server started running...");

    // [connect with Mongo DB here]
});

Open your terminal and you will see the message that the server has been started. You can access your project at http://localhost:3000/

Setup Mongo DB

Write the following lines in place of [include Mongo DB module here] section in your server.js file:

// include mongo DB
var mongodb = require("mongodb");
var MongoClient = mongodb.MongoClient;

Then connect the database in the [connect with Mongo DB here] section:

// connect with mongo DB server
MongoClient.connect("mongodb://localhost:27017", function (error, client) {
    if (error) {
        console.error(error);
        return;
    }

    // set database
    db = client.db("encrypt_decrypt_string");
    console.log("Database connected");

    // [routes goes here]

});

Save the file and open your terminal, now you will see another message that the database has been connected as well.

Encrypt the String

First, include the crypto module at the top of your server.js file:

// include crypto module
const crypto = require("crypto")

// set encryption algorithm
const algorithm = 'aes-256-cbc'

// private key
const key = "adnan-tech-programming-computers" // must be of 32 characters

// random 16 digit initialization vector
const iv = crypto.randomBytes(16)

The key and initialization vector can be any string of 32 and 16 characters respectively. But it is recommended to keep the key hard-coded and initialization vector to be random. Because IV will be saved in database.

We cannot save the key in the database, because if the database gets hacked then all your encrypted strings will be compromised as well.

After that, create a GET route that will encrypt the string and save in Mongo DB. Write the following code in the [routes goes here] section:

// route to encrypt the message
app.get("/encrypt/:message", async function (request, result) {
    // get message from URL
    const message = request.params.message;

	// random 16 digit initialization vector
	const iv = crypto.randomBytes(16);

    // encrypt the string using encryption algorithm, private key and initialization vector
    const cipher = crypto.createCipheriv(algorithm, key, iv);
    let encryptedData = cipher.update(message, "utf-8", "hex");
    encryptedData += cipher.final("hex");

    // convert the initialization vector to base64 string
    const base64data = Buffer.from(iv, 'binary').toString('base64');
    
    // save encrypted string along wtih initialization vector in database
    await db.collection("strings").insertOne({
        iv: base64data,
        encryptedData: encryptedData
    });

    // show the encrypted message
    result.send(encryptedData);
});

Save the file and try to access the URL: http://localhost:3000/encrypt/This is a test string

You can write any string in the URL and you will see the encrypted text in the browser and also in your Mongo DB.

Show all Encrypted Strings

To show all encrypted strings, we are going to use a module named ejs. Write the following line at the top of your server.js file:

// set templating engine as EJS
app.set("view engine", "ejs");

The create the following GET route to show all encrypted strings:

// route to show all encrypted messages
app.get("/", async function (request, result) {
    // get all data from database
    const data = await db.collection("strings")
        .find({})
        .sort({
            _id: -1
        }).toArray();

    // render index.ejs
    result.render("index", {
        data: data
    });
});

Create a new folder named views and inside it create a file named index.ejs. It will have the following code:

<table>
    <% for (let d in data) { %>
        <tr>
            <td>
                <a href="/decrypt/<%= data[d].encryptedData %>" target="_blank">
                    <%= data[d].encryptedData %>
                </a>
            </td>
        </tr>
    <% } %>
</table>

Access the URL: http://localhost:3000/ and you will see all your encrypted strings in descending order.

Decrypt the String

To decrypt the string, create a GET route and fetch the encrypted string and initialization vector from Mongo DB. Then we can apply the decryption using key.

// route to decrypt the message
app.get("/decrypt/:encrypted", async function (request, result) {
    // get encrypted text from URL
    const encrypted = request.params.encrypted;

    // check if text exists in database
    const obj = await db.collection("strings").findOne({
        encryptedData: encrypted
    });

    if (obj == null) {
        result.status(404).send("Not found");
        return;
    }

    // convert initialize vector from base64 to buffer
    const origionalData = Buffer.from(obj.iv, 'base64') 

    // decrypt the string using encryption algorithm and private key
    const decipher = crypto.createDecipheriv(algorithm, key, origionalData);
    let decryptedData = decipher.update(obj.encryptedData, "hex", "utf-8");
    decryptedData += decipher.final("utf8");

    // display the decrypted string
    result.send(decryptedData);
});

If you click on any string now, you will see the actual string.

[wpdm_package id=’1554′]

Detect page leave – HTML & Javascript

In this article, we are going to teach you, how you can detect page leave event using Javascript. Sometimes we would want some action, like an AJAX call when the user leave the page and move to another tab. Or minimize the browser.

We will create a simple video tag. And we will pause the video as soon as the user leaves the tab using Javascript. Also, we will play the video when the user comes back again on the site.

First, you need to create a video tag.

<video src="media/test.mp4" style="width: 100%;" controls id="video"></video>
  • The src attribute will be the path of the video file.
  • The width is 100% so the video will not overflow the webpage.
  • controls attribute to display play/pause, volume up/down, and other controls.
  • Unique ID so it can be accessible in Javascript.

At this point, you will see a video player on your website. If you play the video and move to another tab, the video will keep playing in the background. So the following Javascript code will make sure the video gets paused as soon as the user leaves the tab, and play the video back when the user re-enters the tab.

const video = document.getElementById("video");

document.addEventListener("visibilitychange", function () {
    if (document["hidden"]) {
        video.pause();
    } else {
        video.play();
    }
});

Refresh the page and play the video again. Now if you move to another tab, you will see that the video automatically gets paused and resumed from the same point where it was left when you re-open the tab.

So that’s how you can detect page leave event on your website using simple and plain Javascript. You can check out our other Javascript tutorials to learn more about Javascript.

[wpdm_package id=’1559′]

Marquee Effect in HTML and Javascript – No library

In this article, we are going to teach you how you can display a custom marquee tag effect on your website without downloading any library. You can check the demo from here.

The problem with the HTML marquee tag

Right now, with the default <marquee> tag, you will notice that its animation is not smooth. This is the default behavior of browsers in how they treat marquee tag. Not having smooth animation is definitely not good for your user’s experience.

Solution

There are several solutions on the internet, but they all require downloading a jQuery library to achieve this. So we have created a more simple solution for this. You just need to give a unique ID or class to the node where you want to add the marquee effect.

<div id="marquee"></div>

Then write the following Javascript code to display the message like a marquee effect.

<script>
    (function () {
        const script = document.createElement("script");
        const s0 = document.getElementsByTagName("script")[0];
        script.async = true;
        script.src = "https://api.adnan-tech.com/public/js/at.js";
        script.setAttribute("crossorigin", "*");
        s0.parentNode.insertBefore(script, s0);

        script.onload = function () {
            at.loadMarquee("#marquee", "Your message goes here", {
                duration: 30, // seconds
                direction: "rtl"
            });
        };
    })();
</script>

at.loadMarquee is the function that does all the magic. It accepts three parameters:

  1. the selector (ID, class, or tag name)
  2. the message that will be displayed
  3. (optional) custom options. It has the following options:
    1. duration: (number) It is the number of seconds that will take to complete the effect.
      • type: number
      • default: 40
    1. direction: Its value can be either “rtl” (right to left) or “ltr” (left to right).
      • type: string
      • default: rtl
      • possible values: “rtl” or “ltr”

So that’s how you can display a custom marquee effect on your website without downloading any third-party library. This code has been tested on 10 websites having different frameworks. But if you are having any problems following this, feel free to contact us.

If this tutorial helps you, you can also check our Custom auto-complete view tutorial as well.

Premium projects bundle

Buy the 14 premium projects bundle for $1000. The bundle contains projects in the following technologies:

  • Node JS and Mongo DB
  • PHP & MySQL, Laravel
  • Vue JS
  • Android apps

Project’s list

  1. Single page chat application – Vue JS, Node JS, Mongo DB
  2. E-commerce single page application – Vue JS, Node JS, Mongo DB
  3. Chat app – Android, Web admin panel
  4. Email marketing tool – Laravel, Vue JS
  5. Financial ledger – Vue JS, Node JS, Mongo DB
  6. Image sharing web app – Node JS, Mongo DB / MySQL
  7. Movie ticket booking site – PHP & MySQL, MVC
  8. Realtime blog in Node JS and Mongo DB
  9. File transfer web app – Node JS + Mongo DB
  10. Realtime customer support chat widget
  11. Video streaming website – Node JS, Mongo DB
  12. Picture competition web app – Node JS, Mongo DB
  13. Questionnaire – Node JS, Mongo DB
  14. Blog website – Laravel, Google Adsense approved

You can buy each project separately too as well. Besides getting all the pro features of all 14 projects, we also provide additional services to them.

Secure payment

We allow users to make payments easily and securely using their bank accounts. You can contact us here and we will send you an invoice to make the payment.

Source code

Complete source code is included in all the projects. You will enjoy the pro version of each project.

Support

If you encounter any problem in installing the project or deployment, our technical support team is here. You can schedule a meeting with them and they will be able to assist you over AnyDesk or TeamViewer.

Use as a college project

If you are a student and are looking to get ready-to-go projects to learn about code and how real projects work, this will be beneficial for you. Also, Node JS projects are good learning points for students in advanced programming.

Customize as you want

Once you download the projects, you can customize them as per your needs. You can change the color theme, add new features to it, etc.

Get help in deployment

Once projects are set up in your local host, we will be here if you needed any help in deployment to the live server. For Node JS projects, we will assist you in deployment to Heroku. And for Mongo DB projects, we will help you with a deployment to mongodb.com.

Price: $1000

Out TrustPilot reviews

TrustPilot-reviews
TrustPilot-reviews

Check internet connection javascript

In this article, we are going to teach you how you can check your internet connection using Javascript. We will be displaying a toast or alert message to the user if their internet gets disconnected. And hide the toast when the internet gets reconnected.

Video tutorial:

First, you need to download a library called Toastify. You can download it from GitHub.

After that, you need to include it in your project like this:

<link rel="stylesheet" type="text/css" href="js/toastify.css" />
<script src="js/toastify.js"></script>

Then you need to download another library called Checknet. You can also download it from GitHub too.

You need to include that library as well:

<script src="js/checknet.min.js"></script>

Javascript code to check internet connection

After that, the following code will show a toast message when the internet is down. And it will keep displaying until the network is restored or the toast is manually closed:

<script>

    // create global toastify instance
    var toastify = null;

    // check when the internet is disconnected
    Checknet.addEventListener('dropped', function() {

        // show a toast message
        toastify = Toastify({
            text: "Internet connection lost.",
            duration: -1,
            newWindow: false,
            close: true,
            gravity: "bottom", // `top` or `bottom`
            position: "center", // `left`, `center` or `right`
            stopOnFocus: true, // Prevents dismissing of toast on hover
            style: {
                background: "red",
            },
            onClick: function() {} // Callback after click
        }).showToast();
    });

    // callback when the connection is restored
    Checknet.addEventListener('restored', function() {

        // hide the toast if it is being displayed
        if (toastify != null) {
            toastify.hideToast();
        }
    });

    // start listening for network connectivity
    Checknet.start();

</script>

Refresh the page now and try to disconnect your laptop from the internet. You will immediately see a toast message saying that the internet connection is lost.

Then re-connect the internet, the toast message will be removed automatically. You do not have to refresh the page.

Hope you find this tutorial helpful. If you did, you also browse our Javascript tutorials.