Javascript's Articles

JavaScript, often abbreviated as JS, is a programming language that conforms to the ECMAScript specification. JavaScript is high-level, often just-in-time compiled, and multi-paradigm. It has curly-bracket syntax, dynamic typing, prototype-based object-orientation, and first-class functions.

Convert Json Data to HTML Table Using json2html Javascript Library
json2html is a easy and fast javascript HTML template library used to transform JSON objects into HTML using a another user specified JSON template, which we call transforms. json2html can be used with Native Javascript using core library jQuery using jQuery and core library to include jquery events Node.js using Node.js on server side Usage First download json2html package from the GitHub and include the json2html.js file in <head> tag. Instead, you can also use json2html CDN file if you do not want to download and include in your project. <script src=""></script> Then include one <script> tag before </body> tag close. Create a variable of template which defines how you want to render Json in your HTML page. let template =      {"<>": "li", "id":"${id}", "html":[         {"<>": "span", "text": "${name} (${year})"}     ]}; <> specifies the type of DOM element you want to render like div, li, span etc.. html specifies the innerHTML DOM element will contain inlcuding all DOM children or title of tag Then includes json data in data variable. let data = [     {"title":"Heat","year":"1995"},     {"title":"Snatch","year":"2000"},     {"title":"Up","year":"2009"},     {"title":"Unforgiven","year":"1992"},     {"title":"Amadeus","year":"1984"} ]; Inludes HTML tag in <body> tag where you want to render the table. <ul id="result"></ul> Lastly render the HTML table using json2html.transform method. document.getElementById('result').innerHTML = json2html.transform(data, template); This will generate bellow HTML code: <ul id="result">     <li>         <span>Heat 1995</span>     </li>     <li>         <span>Snatch 2000</span>     </li>     <li>         <span>Up 2009</span>     </li>     <li>         <span>Unforgiven 1992</span>     </li>     <li>         <span>Amadeus 1984</span>     </li> </ul> You can also use jQuery plugin to include jquery events. For that, first include jQuery CDN in <head> tag. <script src=""></script> In the last step, render HTML using json2html method. $('#result').json2html(data, template); Events While using with jQuery library, you can also embed jQuery events whithin a transform. This events will trigger when transform is applied to the DOM element. Here is some supported events: onclick onblur ondblclick ondie onerror onchange onhover onfocus etc.. {'<>':'button','onclick':function(e) {     //e.event : the jQuery event     //  : user specified data from the the json2html options variable eventData (see Usage)     //e.index : the index of the array in which the source object was found     //e.obj   : the source object that we are transforming     console.log(e.obj); }} You can also access the source jQuery element that called the event using $(this). {'<>':'span','onclick':function(){ $(this).hide(); } Server side render For server side, we will use Node.js. First download json2html package by npm. npm install node-json2html Then define json2html constant and template variable. Also define json data variable. const json2html = require('node-json2html');   let template = {'<>':'div','html':'${title} ${year}'};      let data = [     {"title":"Heat","year":"1995"},     {"title":"Snatch","year":"2000"},     {"title":"Up","year":"2009"},     {"title":"Unforgiven","year":"1992"},     {"title":"Amadeus","year":"1984"} ]; Then render json data to HTML table.   let html = json2html.transform(data,template); Conclusion This way, you can easily create HTML table from the json data. I hope it will help you.
jQuery and JavaScript Code Examples
In the previous article, we have discussed on what is Javascript and JQuery. We have also discussed on main differences between them. In this article we will go through code comparision between Javascript and JQuery with example. JavaScript and jQuery code examples Here is the bellow examples, so let's check bellow examples: Writing Javascript and JQuery code in HTML document Javascript is directly written between <script> tags. Javascript external file can also be included in HTML document. <script src="path/to/external/javascript-file.js"></script> <script>     document.getElementById("myid").innerHTML = "Hello World"; </script> JQuery code is dependant on JQuery library. So you have to include JQuery library file or CDN file before JQuery code in HTML document. <head>     <script src="jquery-3.5.0.min.js"></script> </head> HTML tag selection and manipulation To select HTML tag in Javascript, use document.querySelector() method or other methods as per tag. document.querySelector('#id'); or document.getElementById('idname'); or select by class document.getElementsByClassName('classname'); or select by element document.getElementsByTagName('p'); In JQuery $ sign used with selector in bracket. $(selector) or $('#idname') or $('.classname') or $('p') Event handling To handle event in Javascript, write addEventListener() method with event name. document.getElementById('idname').addEventListener('click', function() {     alert('Hello World'); }); In JQuery all event has defined method to handle. $('.classname').click(function() {    // here comes acion }); or submit form $('#idname').submit(function() {    // here comes acion }); or to use multiple event with on() method $('#input').on ('click change', function() {    // here comes acion }); Change CSS property To change the style of an HTML element in Javascript, use: document.getElementById('idname').style.color = '#f2f2f2'; in JQuery, change CSS with css() method: $('#idname').css('color', '#f2f2f2'); Changing or adding value of an Attribute To change the value of HTML element attribute in Javascript, use: document.getElementById('idname').href = "/new-url"; To change value in JQuery, use attr() method: $('#idname').attr('href', '/new-url'); Create Ajax request Creating Ajax request in Javascript with new XMLHttpRequest object and send request to server. There is open('methodType', 'URL', async) method with parameters and send() method with data creates Ajax request. Create get method request: var xhttp = new XMLHttpRequest();'GET', 'request-url', true); xhttp.send(); Or create post method request: var xhttp = new XMLHttpRequest();'POST', 'request-url', true); xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhttp.send('id=5&name=javascript'); To create Ajax request, there are many syntax in JQuery. Bellow are main methods which are widely used: $.ajax({     type: "post",     url: 'request-url',     data: data,     success: function(response) {         // what to do after ajax complete     } }); Or shorthand method: $.get('request-url', function(response) {     $('#result').html(response); }); or more simply: $('#result').load('request-url'); Create animation Creating animation is also difficult and requires many lines of code. JavaScript use the setInterval(), clearInterval(), setTimeout() and clearTimeout() methods and CSS transform, translate or animate properties to create animation. Here is the simple animation in Javascript: setInterval(myAnimation, 5);     function myAnimation(){     document.getElementById ("#idname").style.transform=‘translate(100px, 100px)’;     document.getElementById ("#idname").style.transform=‘rotate(30deg)’; } In JQuery there are several direct methods which are used to create fast and easy animation: Css animation $('#idname').animate({height: '100px'}); Hide/Show animation $('.hide-class').hide(); $('show-class').show(); or toggle() to hide/show respectively. $('show-class').toggle(); Create fade effect with fadeIn() or fadeOut() method: $('#idname').fadeIn(); $('#idname').fadeOut(); There are many functions in JQuery to create animations. But it is also noted that Javascript can also work in graphic animations like on <canvas> tag while JQuery only works in HTML dom elements: Which one you liked? Javascipt is difficult compared to JQuery, so most of us use JQuery for most of work. While Javascript is language and has widly use with other technologies while Jquery is Javascript library for HTML dom manipulation. So it mostly used in web development. In the conclusion, both have its own usage in software development. I hope you will like this article.
Check if Array is Empty or null in Javascript
When working in Javascript, many times you need to check if array is empty or undefined. This needs to check when you want to loop the array, so it doesn't return error. There are lot of ways to check if Javascript array is empty or not. Here are some examples: Checking by array length The first way to check is to get array length. If the array length is 0, then it empty array. <script type="text/javascript">     var newArray = [1];     if (newArray && newArray.length > 0) {         // newArray is not empty     } else {         // newArray is empty     } </script> Checking if array is not undefined Sometimes you also want to check that array should not be undefined object and has at least one element. This can be also check with typeof. <script type="text/javascript">      var undefinedAray = undefined;     if (typeof undefinedAray !== "undefined" && undefinedAray.length > 0) {         // undefinedAray is not empty     } else {         // undefinedAray is empty or undefined     } </script> Using JQuery isEmptyObject() method We can also use JQuery isEmptyObject method to check whether array is empty or contains elements. This is reliable method. <script src=""></script> <script type="text/javascript">     var newArray1 = [1, 2, 3];     var newArray2 = [];     console.log(jQuery.isEmptyObject(newArray1)); // returns false     console.log(jQuery.isEmptyObject(newArray2)); // returns true </script> This way you can check wether array contains element or is empty. I hope this article will help you a little.
Add Lazy Loading in Your Website for Better Website Performance
Lazy loading is a web development technique that loads images on a page to a later point when the images are actually needed, instead of loading them up front. This techniques helps in improving website performance, reducing loading time and utilization of costs. There are many benefits for adding Lazy loading in the websites. 1. Lazy loading loads page faster than normal loading, and only loads content when user needed. 2. It helps in reducing resource waste. For example, if an entire photo gallery is loaded on webpage but the user only wants to view first image, then the rest images are wasted in momory. 3. In Lazy loading, content only loads when user scrolls down to the page, so it will provide smooth scroll and better user experience. Installation and use of Lazy loading There are many open source library available to implement Lazy loading. blazy.js is easy and light-weight Lazy loading library. There is also jQuery Lazy plugin available. We will discuss that plugin in other article. For now, we will implement blazy.js plugin. blazy is written in pure JavaScript, so you don't have to include 3rd-party libraries such as jQuery. bLazy works on all modern browsers. You can use blazy in just 3 simple step. 1. Download the blazy from GitHub and add to your website. <script src="blazy.js"></script> Or alternativaly use CDN file. <script src=""></script> 2. Add 'b-lazy' class to img tag. Add real image source to data-src. <img class="b-lazy" data-src="/path/to/image.jpg" /> 3. Write below Javascript to load images Lazy way. <script type="text/javascript">     // Initialize     var bLazy = new Blazy({         // Options     }); </script> You can also add few options with bLazy. Selector You can change the selector if you don’t want to add the ‘b-lazy’ class or if you need to have multiple. // example var bLazy = new Blazy({      selector: 'img' // all images }); Offset The offset controls how early you want the elements to be loaded before they’re visible. Default is 100, so 100px before an element is visible it’ll start loading. // Example var bLazy = new Blazy({      offset: 100 // Loads images 100px before they're visible }); Images inside a container You can also lazy load images inside a scrolling container, just define the selector of the container: var bLazy = new Blazy({      container: '#scrolling-container' // Default is window }); Callback If you need to do anything when an image has loaded or fails you can pass a callback function: var bLazy = new Blazy({      success: function(res) {         // image has loaded     },     error: function(ele, msg){         if(msg === 'missing') {             // data-src is missing         }         else if(msg === 'invalid') {             // data-src is invalid         }     } }); You can also use more options here. Conclusion Loading content is important part in view of user’s browsing experience. Dynamically loading content gives user smooth experience. Lazy loading will provide smooth and easy touch to load website faster and ultimately gives better user experience.
JavaScript vs jQuery Differences
When new developer starts learning in Web development, the first thing they want to know is which is best to learn for web development between Javascript and jQuery. With more and more learning, they become curious to know about Javascript and jQuery. The most common point is both are used for the same purpose, then why need to do seperate concept? and which is best suitable language for web development. These are the main questions of the most newcomers in web development. In this article, we will discuss on main differences between Javascript and JQuery. We will also discuss on which one should you use. To differentiate between them, first let's see what is Javascript and Jquery? What is Javascript? Javascript is dynamic scripting programming language used to add dynamic effects in the webpages. It is the one of the core technology language used in website along with HTML and CSS. It is most commonly used in creating dynamic effects like, moving objects, flashing or changing elements. Javascript is supported by all major web browsers    and mostly installed Javaascript engine in all browsers. That's why Javascript is mostly used as client-side language. But today it is also used for server-side using Ajax technology. So, we have discuss on what is Javascript, now let's move on what is jQuery. What is JQuery? Most of the new developers still don't know that jQuery is not programming language. jQuery is a Javascript library, which includes simple javascript code. In fact, JQuery is the short code of Javascript, which has optimized for better performance using Javascript functions. JQuery is most popular framework used for web development due to easiness and fast handling data. To write the JQuery code, first you need to include JQuery library file. You can also use JQuery CDN file instead. <script src=""></script> One thing should be noted that JQuery is the Javascript library, so all JQuery code is Javascript code, but not all Javascript code doesn't include in JQuery. Difference between Javascript and JQuery So we have discussed about what is Javascript and JQuery. Now let's discuss on main point: What is the main differences between Javascript? Here is the bellow: 1. Language type Javascript is the independent programming language written in C, while JQuery is Javascript library for DOM manipulation. It is based on Javascript. 2. Simplicity in Code JQuery is Write Less, Do More type Javascript library. Dom selection, many actions like animate, fade requires less code in JQuery, while Javascript need more lines of code for the same effects. For example, if we want to select all elements with same class, bellow code needs to do in Javascript. document.getElementsById("id-name"); In JQuery you only need to write: $('#id-name') 3. Start writing To add Javascript code, You don't need to include any script file or any CDN. Just create <script> tags in HTML code and start writing. On the other hand, to write JQuery code, you need to inclde JQuery library file. JQuery code also writing between <script> tags. 4. Compatibility To write the Javascript code, one must need to handle browser compatibilities, while JQuery is multi browser compatible so don't need to take into consideration. 5. Size Javascript is a language, so it is heavy in size and slow in other than JQuery while JQuery is a library so it is light-weight. 6. Client-Side/Server Side Javascript is commonly used in client-side, but some Javascript libraries like Node can be used as server side. JQuery is purely used in client side. 7. Reusability Javascript code is to lenghthy so it can be difficult to maintain reusability while with JQuery with few lines of code it can be maintain and can also be reuse. Which one you should use? What web developer needs to do is make a decision on what is the best for their client. Someone first starts web development does need some exposure to both technologies. Just using only JQuery all the time is not recommended and also need to know about JavaScript and how it handles the DOM while using JavaScript all the time slows down projects. Which is the best JavaScript or JQuery is a still a continous discussion, and the answer is neither is best. They both have their own advantage.In the online applications where JQuery is not the right tool and what the application needed was straight JavaScript development while in most websites JQuery is all that is needed. I hope you will liked this article.
Create Autocomplete Search using Typeahead Js
Typeahead.js is simple javascript library developed and used by Twitter for simple user search experice. Typeahead.js predicts words input by user and returns results from the data. Typeahead.js uses the data prefetched from javascript array as well as from remove server. You can also use multiple remove source to get results. In this article, we will go through on how to implement Typeahead.js in simple way. Typeahead.js also uses jQuery library, so we will also use jQuery CDN file. Now download library from github or use the link as CDN file. Add these html tags before </body> tag. <script src=""></script> <script src=""></script>  Add input tag where you want to implement Typehead.js <input class="typeahead" id="search" type="text" placeholder="States of USA"> Now put the below script code after the typehead.js loaded. <script type="text/javascript">     var matchString = function(data) {          return function findMatches(q, cb) {                var matches, substringRegex;                matches = [];             substrRegex = new RegExp(q, 'i');             $.each(data, function(i, str) {                  if (substrRegex.test(str)) {                     matches.push(str);                   }             });             cb(matches);           };     };     var states = [         'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California',         'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii',         'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana',         'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota',         'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire',         'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota',         'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island',         'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont',         'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'     ];     $('#state').typeahead({          hint: true,          highlight: true,          minLength: 1     },{           name: 'states',           source: matchString(states)     }); </script> In the above code state variable is the data and matchString() function returns the predicted data. Here is the full code how to implement Typehead.js with bootstrap. <!DOCTYPE html> <html>     <head>         <title>State search</title>         <link rel="stylesheet" type="text/css" href="">     </head>     <body>         <div class="container text-center">           <h1>State search</h1>             <div class="form-group" id="remote">                 <input type="text" class="form-control typeahead" id="state" name="state">             </div>         </div>         <script src=""></script>         <script src=""></script>         <script type="text/javascript">             var matchString = function(data) {                  return function findMatches(q, cb) {                        var matches, substringRegex;                        matches = [];                     substrRegex = new RegExp(q, 'i');                     $.each(data, function(i, str) {                          if (substrRegex.test(str)) {                             matches.push(str);                           }                     });                     cb(matches);                   };             };             var states = [                 'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California',                 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii',                 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana',                 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota',                 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire',                 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota',                 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island',                 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont',                 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'             ];             $('#state').typeahead({                  hint: true,                  highlight: true,                  minLength: 1             },{                   name: 'states',                   source: matchString(states)             });         </script>     </body> </html> Remote server To use remote server data, you need to use Bloodhound, the typeahead.js suggestion engine. Bloodhound is also used when more complex data handling with functionalities like prefetching, caching, fast response and remote data. Here is the example how to fetch data from remote server using query. Below is the example of predict serach from remote server. <!DOCTYPE html> <html>     <head>         <title>Film search</title>         <link rel="stylesheet" type="text/css" href="">     </head>     <body>         <div class="container text-center">           <h1>Film search</h1>             <div class="form-group" id="remote">                 <input type="text" class="form-control typeahead" id="film" name="film">             </div>         </div>         <script src=""></script>         <script src=""></script>         <script type="text/javascript">             var users = new Bloodhound({                 datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),                 queryTokenizer: Bloodhound.tokenizers.whitespace,                 prefetch: '',                 remote: {                     url: '',                     wildcard: '%QUERY%'                 }             });             $('#film').typeahead(null, {                  name: 'best-pictures',                  display: 'value',                  source: users,                   templates: {                     empty: [                         '<div class="list-group search-results-dropdown"><div class="list-group-item">No records found.</div></div>'                     ],                     header: [                         '<div class="list-group search-results-dropdown">'                     ],                     suggestion: function (data) {                         return '<a target="_blank" href="' + data.value + '" class="list-group-item">' + data.value + '</a>'                     }                 }             });         </script>     </body> </html> Note: If you want to pass input string through get query, then you can set it something like below. remote: {     url: '',     wildcard: '%QUERY%' } This way, you can simply add autopredict search box to improve user experience. I hope you will like this article.          
Javascript beautiful sweetalert2 plugin
Sweetalert2 is opensource simple and standalone javascript plugin which provides responsive and beautiful popup modal boxes. With the help of sweetalert2, you can improve your web applcation UI. Sweetalert2 is written in pure Javascript, so you don't need to add any dependencies to use Sweetalert2 plugin. You can use sweetalert2 to display success or error message or if you need user confirmation. In this article, we will discuss how to use sweetalert2 plugin in web application. Installation First download plugin from Github. And initialise by adding below tags in <head> section. <script src="sweetalert2/dist/sweetalert2.min.js"></script> <link rel="stylesheet" href="sweetalert2/dist/sweetalert2.min.css"> Or you can simply add files from CDN providers. <link rel="stylesheet" href=""/> <script src=""></script> Basic usage Now use method to launch sweetalert2 box.'Welcome to the  Hello World!'); Bind with button You can also popup message on event like click or response to Ajax response. <!DOCTYPE html> <html> <head>     <link href="" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">     <link rel="stylesheet" href=""/>     <script src=""></script> </head> <body>     <div class="container mt-3 text-center">         <button type="button" class="btn btn-info" onclick="showMessage()">Show Message!</button>     </div>     <script type="text/javascript">         function showMessage() {   {                 icon: 'error',                 title: 'Oops...',                 text: 'Something went wrong!',                 footer: '<a href="">Why do I have this issue?</a>'             });         }     </script> </body> </html> Sweetalert provides variety of options to pass as object to configure. Option Description title The title of the popup box. titleText The title of the popup, as text. html A HTML code of description for the popup box. text A description for the popup. icon The icon of the popup. SweetAlert2 provides animated icons for: warning, error, success, info, and question iconColor Use this to change the color of the icon. footer The footer of the popup box. backdrop Whether or not SweetAlert2 should show a full screen click-to-dismiss backdrop. input Input field like text, email, password, number, tel, range, textarea, select, radio, checkbox, file and url. width Popup window width, including paddings. padding Popup padding. background Popup window background. Popup window background Popup window position, can be 'top', 'top-start', 'top-end', 'center', 'center-start', 'center-end', 'bottom', 'bottom-start', or 'bottom-end'. timer Auto close timer of the popup. Set in milliseconds. width Popup window width, including paddings. padding Popup padding. showConfirmButton If set to false, a "Confirm"-button will not be shown. showDenyButton If set to true, a "Deny"-button will be shown. showCancelButton If set to true, a "Cancel"-button will be shown which will dismiss the modal. Sweetalert2 also provides handling button. Option Description isConfirmed The "Confirm" button was clicked, the value will contain the result. isDenied The "Deny" button was clicked. isDismissed The "Cancel" button was clicked. value The value from the popup, possible values: true for simple confirmed false for denied popups dismiss The dismissal reason. You can also change sweetalert2 theme also. For more configurations and details, check the official website.
Remove a Property from a JavaScript Object
Javascript object is pair of key/value. If you want to access any value from the Javscript object, you can access using object.key or object['key'] syntax. In this article we will share how you can remove any property from the Javscript object.  Here is below code to remove property from the Javscript object. var person = {     firstName: "John",     lastName: "Doe",     email: "^" }; delete; // or another way delete person['email']; console.log(person); This way you can remove property from Javascript object. Thank you for giving time to read the article. I hope you like this article.