How can I access the function which inside different js file in JQUERY?

And here is the struct of the HTML as below: 

$(function () {    
    function WhiteNav() {
        $("#LOGO>img").attr('src', '/images/LOGOWhite.svg');
        $("#NavUL a").css("color", "#cecece");
    }    
});

And here is the struct of the HTML as below: 


However, after the browser(Chrome) ran the WhiteNav function in the script, it reported this error and the WhiteNav failed: 


3 JavaScript libraries to replace jQuery

3 JavaScript libraries to replace jQuery

Ubiquitous jQuery has been outmoded by JavaScript and browser advances. Cash, Zepto, and Syncfusion are three JavaScript libraries picking up where jQuery left off

Simplifying tasks such as HTML document traversal, animation, and event handling, the stalwart jQuery JavaScript library changed the face of web development. As of May 2019, **jQuery **is still being used in 74 percent of known websites, according to web technology surveyor W3Techs. Nevertheless, the jQuery library, which debuted in August 2006, is now being viewed by some developers as an older technology whose time has passed.

Alternatives to **jQuery **have emerged in recent years, such as the Cash library or even just modern, vanilla JavaScript, now that web browsers all handle **JavaScript libraries **the same way and jQuery is no longer needed to solve compatibility issues. Arguments on Reddit and videos on YouTube make the case that jQuery has become obsolete, or at least is not as essential as it once was.

Why jQuery is no longer needed

In one YouTube presentation, “Is jQuery still relevant in 2018?,” web development educator Brad Traversy acknowledges that jQuery is probably the best generalized JavaScript library ever created. It is easy to learn, cross-browser compatible, more concise than older vanilla JavaScript, and rich in plug-ins offering specific functionality. But JavaScript has advanced far since ECMAScript 6, and jQuery is no longer needed in many situations, Traversy concludes.

In another video, coding educator Kenneth Lowrey argues that becoming fluent in jQuery is a waste of time. In the current web development landscape, modern browsers handle JavaScript the same, for the most part. In most cases, native JavaScript code is better than a “bloated legacy library like jQuery,” he says.

While jQuery had been the choice for making HTTP requests, for example, ECMAScript 6 brought forth Fetch, a promised-based API that makes HTTP requests easier. And the advancement does not stop with HTTP. Where jQuery has utilities for tasks such as manipulating arrays, vanilla JavaScript now has improved accommodations for these operations, too.

Animations are still more difficult with vanilla JavaScript than jQuery, but there are other options such as CSS transitions or keyframes, Traversy points out. The third-party GreenSock library also can be used for animations. For DOM manipulation, a task once ruled by jQuery, native browser APIs have closed the gap.

For tasks that cannot be done in vanilla JavaScript, Traversy recommends specialized libraries, instead of a generalized library like jQuery. Traversy also recommends using JavaScript frameworks such as React, Angular, or Vue for mid-size and large applications. Traversy still recommends jQuery for use on simple sites with no framework.

jQuery alternatives

What should you use instead of jQuery? Besides modern, vanilla JavaScript, a short list of jQuery alternatives includes Cash, Zepto, and Syncfusion Essential JS 2. Cash and Zepto are open source JavaScript libraries available under an MIT license. Syncfusion Essential JS 2 is a commercial product.

Cash

Cash has more than 3,570 stars on GitHub. Billed as an “absurdly small jQuery alternative” for modern browsers, Cash has a jQuery-style syntax for manipulating the DOM and takes up 32KB of space, uncompressed. Cash supports capabilities including namespaced events, TypeScript types, and modern builds. You can download Cash from GitHub.

Zepto

Zepto is described as “a minimalist **JavaScript library **with a largely jQuery-compatible API.” Developers who know jQuery already know how to use Zepto, its makers go on to say. Zepto purports to be much smaller and faster-loading than jQuery, and can work with the PhoneGap toolset for mobile and desktop browsers. You can download Zepto from the project website.

Syncfusion Essential JS 2

Syncfusion Essential JS 2 is a commercially licensed JavaScript UI controls library written in TypeScript. Serving as an alternative to the jQuery UI library, Syncfusion is designed to be a low-overhead, lightweight, and modular library to improve web applications. Syncfusion supports frameworks including Angular, React, and Vue. You can purchase Syncfusion Essential JS 2 or download a free trial from the Syncfusion website. Complete source code, unit test files, test scripts, and live demos are available on GitHub.

How to read XML in JavaScript using jQuery|Ajax

How to read XML in JavaScript using jQuery|Ajax

How to read XML in JavaScript using jQuery|Ajax- The jQuery JavaScript library is best known for its use working with HTML, but you can also use it to process XML. This article shows how to use jQuery to process a data store in XML format.

How to read XML in JavaScript using jQuery|Ajax- The jQuery JavaScript library is best known for its use working with HTML, but you can also use it to process XML. This article shows how to use jQuery to process a data store in XML format.

I’m going to share some tricks about XML file and APIs processing. I will also demonstrate how a web page can fetch information from an XML file in JavaScript using JQuery AJAX.

Assumptions: for the purpose of this article, I’m going to assume that you have good understanding and knowledge of JavaScript, the XML file format, and jQuery. If not please find documentation here to learn more details about it.

The project I worked on recently consisted of processing XML data resulting from an API call. The resulting **XML data **file was very large and its content is private data that I can’t share. *So in this post, I will show you how to process an ****XML demo ***file.

Below is the sample XML file from w3chools that I’ll be using for the demo:

<?xml version="1.0" encoding="UTF-8"?>
	

	<breakfast_menu> 
	   
	   <food> 
	       <name>Belgian Waffles</name> 
	       <price>$5.95</price> 
	       <description>Two of our famous Belgian Waffles with plenty of real maple syrup</description> 
	       <calories>650</calories> 
	   </food> 
	   
	   <food> 
	       <name>Strawberry Belgian Waffles</name> 
	       <price>$7.95</price> 
	       <description>Light Belgian waffles covered with strawberries and whipped cream</description> 
	       <calories>900</calories> 
	   </food> 
	   
	   <food> 
	       <name>Berry-Berry Belgian Waffles</name> 
	       <price>$8.95</price> 
	       <description>Light Belgian waffles covered with an assortment of fresh berries and whipped cream</description> 
	       <calories>900</calories> 
	   </food> 
	   
	   <food> 
	       <name>French Toast</name> 
	       <price>$4.50</price> 
	       <description>Thick slices made from our homemade sourdough bread</description> 
	       <calories>600</calories> 
	   </food> 
	   
	   <food> 
	       <name>Homestyle Breakfast</name> 
	       <price>$6.95</price> 
	       <description>Two eggs, bacon or sausage, toast, and our ever-popular hash browns</description> 
	       <calories>950</calories> 
	   </food> 
	   
	</breakfast_menu>

Now, create a folder for the demo project and save the demo.xml file in it. I named mine “XML-demo”. Inside your project folder, create a JavaScript file and HTML file that will display the data (index.html and main.js). I’m not using a separate CSS file for styling.

I recommend using Visual Studio Code IDE for this demo and in your VS Code install Live Server extension.
The following is a screenshot of my demo folder opened in VS code:

VS Code IDE Screenshot — shows files

Next step is adding your script and jquery-UI references in your index.html and define how you would like to display data. I’m simply displaying data in a “ul” element. Here’s how my index.html looks like:

<!DOCTYPE html>
	<html lang="en">
	

	    <head>
	        <meta charset="UTF-8">
	        <meta name="viewport" content="width=device-width, initial-scale=1.0">
	        <meta http-equiv="X-UA-Compatible" content="ie=edge">
	        <title>XML-Jquery</title>
	        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
	

	        <!-- **************************************************************************************** 
	        !   connect your main.js script to hmtl                                                     *
	        !   add version of jquery                                                                   *
	        ! *************************************************************************************** -->
	        <script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.min.js"></script>
	        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
	        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
	

	        <!-- javascript reference -->
	        <script type="text/javascript" src="./main.js"></script>
	    </head>
	

	    <body>
	        <div class="container">
	            <div class="jumbotron" style="text-align: center;">
	                <h1 id="headerTitle">Food Menu List</h1>
	            </div>
	

	            <ul></ul>
	

	        </div>
	    </body>
	

	</html>
	

	<!-- ****************************************** END **********************

Reading XML

So the basic method for doing asynchronous calls in jQuery is the AJAX() function, documented here. That documentation has a lot going on but that should get you started and help you walk through my main.js script to understand how the XML file is processed through AJAX:

// Do some stuff when page hmtl page is launched
	$(document).ready(function () {
	

	    $("#headerTitle").hide(300).show(1500);
	    // calling show food menu function
	    showFoodMenu();
	    
	    // If you want to fetch data from the file 
	    // call fetch data function instead of showFoodMenu
	    // fetchData()
	});
	

	// ***************************************************************************************
	// this function calls showfoodmenu 3000 milisecond to get new changes                   *
	// made on demo.xml                                                                      *
	// ***************************************************************************************
	function fetchData() {
	    setTimeout(function () {
	        showFoodMenu();
	        // recursive call
	        fetchData();
	    }, 3000);
	}
	

	// **************************************************************************************
	// read data from demo.xml using Jquery | AJAX                                          *
	// **************************************************************************************
	function showFoodMenu() {
	

	    $.ajax({
	        type: "GET",
	        url: "./demo.xml",
	        dataType: "xml",
	

	        error: function (e) {
	            alert("An error occurred while processing XML file");
	            console.log("XML reading Failed: ", e);
	        },
	

	        success: function (response) {
	

	            // make sure the ul is empty
	            // before appending data inot it
	            $("ul").children().remove();
	

	            $(response).find("food").each(function () {
	                var _name = 'Name: ' + $(this).find('name').text();
	                console.log(_name);
	                
	                var _price = 'Price: ' + $(this).find('price').text();
	                var _calories = 'Calories: ' + $(this).find('calories').text();
	                var _description = 'Description: ' + $(this).find('description').text();
	

	                // add content to the HTML          
	                $("ul").append('<li>' + _name + '</li>');
	                $("ul").append('<li>' + _price + '</li>');
	                $("ul").append('<li>' + _calories + '</li>');
	                $("ul").append('<li>' + _description + '</li>');
	            });
	        }
	    });
     }

You should have the icon for Go live on your VScode IDE if you successfully install [***Live Server***](https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer "***Live Server***") extension. Clicked to Go Live icon on the right bottom of your VS code IDE or simply right click on HTML file and select “open with Live Server”. if you followed exactly and correctly what I did, you should get this:

Final result — Displaying XML data on HTML

Tips

Do not put the script reference to jquery-UI before the jquery script itself on your HTML otherwise you’ll get this error: ***Uncaught ReferenceError: $ is not defined. ***Make sure your script is referenced after you have referenced jquery-UI as I did in my main.js script.

Frequently used acronyms* API: Application programming interface

  • Ajax: Asynchronous JavaScript
  • CSS: Cascading Stylesheets
  • DOM: Document Object Model
  • HTML: Hypertext Markup Language
  • RSS: Really Simple Syndication
  • SGML: Standard Generalized Markup Language
  • SVG: Scalable Vector Graphics
  • URI: Uniform Resource Identifier
  • URL: Uniform Resource Locator
  • W3C: World Wide Web Consortium
  • XHTML: Extensible Hypertext Markup Language

If you enjoyed this story, you might also like “How to Set Up the Development Environment

What is JavaScript – All You Need To Know About JavaScript

What is JavaScript – All You Need To Know About JavaScript

In this article on what is JavaScript, we will learn the basic concepts of JavaScript.

After decades of improvement, JavaScript has become one of the most popular programming languages of all time. It all started in the year 1995 when Brendan Eich created JavaScript in a span of 10 days. Since then, it has seen multiple versions, updates and has grown to the next level.

Here’s a list of topics that I’ll be covering in this blog:

  1. What is JavaScript
  2. What can JavaScript do?
  3. JavaScript Frameworks
  4. The Big Picture: HTML, CSS & JavaScript
  5. Benefits of JavaScript
  6. Fundamentals of JavaScript
    VariablesConstantsData TypesObjectsArraysFunctionsConditional statementsLoopsSwitch case
What is JavaScript?

JavaScript is a high level, interpreted, programming language used to make web pages more interactive.

Have you ever thought that your website is missing something? Maybe it’s not engaging enough or it’s not as creative as you want it to be. JavaScript is that missing piece which can be used to enhance web pages, applications, etc to provide a more user-friendly experience.

What is JavaScript?

JavaScript is the language of the web, it is used to make the web look alive by adding motion to it. To be more precise, it’s a programming language that let’s you implement complex and beautiful things/design on web pages. When you notice a web page doing more than just sit there and gawk at you, you can bet that the web page is using JavaScript.

Feature of JavaScript

Scripting language and not Java: In fact, JavaScript has nothing to do with Java. Then why is it called “Java” Script? When JavaScript was first released it was called Mocha, it was later renamed to LiveScript and then to JavaScript when Netscape (founded JavaScript) and Sun did a license agreement. Object-based scripting language which supports polymorphism, encapsulation and to some extent inheritance as well.**Interpreted language: **It doesn’t have to be compiled like Java and C which require a compiler.JavaScript runs in a browser: You can run it on Google Chrome, Internet Explorer, Safari, etc. JavaScript can execute not only in the browser but also on the server and any device which has a JavaScript Engine.

What is JavaScript – Stackoverflow stats

Currently, we have 100s of programming languages and every day new languages are being created. Among these are few powerful languages that bring about big changes in the market and JavaScript is one of them.

JavaScript has always been on the list of popular programming languages. According to StackOverflow, for the 6th year in a row, JavaScript has remained the most popular and commonly used programming language.

What can JavaScript do?

JavaScript is mainly known for creating beautiful web pages & applications. An example of this is Google Maps. If you want to explore a specific map, all you have to do is click and drag with the mouse. And what sort of language could do that? You guessed it! It’s JavaScript.JavaScript can also be used in smart watches. An example of this is the popular smartwatch maker called Pebble. Pebble has created Pebble.js which is a small JavaScript Framework that allows a developer to create an application for the Pebble line of watches in JavaScript.

What is JavaScript – Applications of JavaScript
Most popular websites like Google, Facebook, Netflix, Amazon, etc make use of JavaScript to build their websites.Among things like mobile applications, digital art, web servers and server applications, JavaScript is also used to make Games. A lot of developers are building small-scale games and apps using JavaScript.## JavaScript Frameworks

One major reason for the popularity of JavaScript is the JavaScript Frameworks. Here’s a brief introduction of the most trending JavaScript frameworks :

  1. AngularJS is Google’s web development framework which provides a set of modern development and design features for rapid application development.

  2. ReactJS is another top JavaScript framework mainly maintained by Facebook and it’s behind the User Interface of Facebook and Instagram, showing off its efficiency in maintaining such high traffic applications.

What is JavaScript – JavaScript Frameworks

  1. MeteorJS is mainly used for providing back-end development. Using JavaScript on the back-end to save time and build expertise is one of the major ideas behind Meteor.

  2. jQuery can be used when you want to extend your website and make it more interactive. Companies like Google, WordPress and IBM rely on jQuery.

The Big Picture: HTML, CSS & JavaScript

Anyone familiar with JavaScript knows that it has something to do with HTML and CSS. But what is the relationship between these three? Let me explain this with an analogy.

What is JavaScript – HTML, CSS and JavaScript

Think of HTML (HyperText Markup Language) as the skeleton of the web. It is used for displaying the web.

On the other hand, CSS is like our clothes. We put on fashionable clothes to look better. Similarly, the web is quite stylish as well. It uses CSS which stands for Cascading Style Sheets for styling purpose.

Then there is JavaScript which puts life into a web page. Just like how kids move around using the skateboard, the web also motions with the help of JavaScript.

Benefits of JavaScript

There has to be a reason why so many developers love working on JavaScript. Well, there are several benefits of using JavaScript for developing web applications, here’s a few benefits:

It’s easy to learn and simple to implement. It is a weak-type programming language unlike the strong-type programming languages like Java and C++, which have strict rules for coding.

It’s all about being fast in today’s world and since JavaScript is mainly a client-side programming language, it is very fast because any code can run immediately instead of having to contact the server and wait for an answer.

Rich set of frameworks like AngularJS, ReactJS are used to build web applications and perform different tasks.

**Builds interactive websites: **We all get attracted to beautifully designed websites and JavaScript is the reason behind such attractive websites and applications.

JavaScript is an interpreted language that does not require a compiler because the web interprets JavaScript. All you need is a browser like Google Chrome or Internet Explorer and you can do all sorts of stuff in the browser.

JavaScript is platform independent and it is supported by all major browsers like Internet Explorer, Google Chrome, Mozilla Firefox, Safari, etc.

JavaScript Fundamentals

In this What is JavaScript blog, we’ll cover the following basic fundamentals of JavaScript
VariablesConstantsData TypesObjectsArraysFunctionsConditional statementsLoopsSwitch case## Variables

Variable is a name given to a memory location which acts as a container for storing data temporarily. They are nothing but reserved memory locations to store values.

What is JavaScript – Variables

To declare a variable in JavaScript use the ‘let’ keyword. For example:

let age;
age=22;

In the above example, I’ve declared a variable ‘age’ by using the ‘let’ keyword and then I’ve stored a value (22) in it. So here a memory location is assigned to the ‘age’ variable and it contains a value i.e. ’22’.

Constants

Constants are fixed values that don’t change during execution time.

To declare a constant in JavaScript use the ‘const’ keyword. For example:

const mybirthday;
mybirthday='3rd August'; 

Data types

You can assign different types of values to a variable such as a number or a string. In JavaScript, there are two categories of data types :

What is JavaScript – Data Types

Objects

An object is a standalone entity with properties and types and it is a lot like an object in real life. For example, consider a girl, whose name is Emily, age is 22 and eye-color is brown. In this example the object is the girl and her name, age and eye-color are her properties.

What is JavaScript – Objects example

Objects are variables too, but they contain many values, so instead of declaring different variables for each property, you can declare an object which stores all these properties.

To declare an object in JavaScript use the ‘let’ keyword and make sure to use curly brackets in such a way that all property-value pairs are defined within the curly brackets. For example:

let girl= {
name: 'Emily',
age: 22,
eyeColour: 'Brown'
};

In the above example, I’ve declared an object called ‘girl’ and it has 3 properties (name, age, eye colour) with values (Emily, 22, Brown).

Arrays

An array is a data structure that contains a list of elements which store multiple values in a single variable.

For example, let’s consider a scenario where you went shopping to buy art supplies. The list of items you bought can be put into an array.

What is JavaScript – Arrays example

To declare an array in JavaScript use the ‘let’ keyword with square brackets and all the array elements must be enclosed within them. For example:

let shopping=[];
shopping=['paintBrush','sprayPaint','waterColours','canvas'];

In the above example I’ve declared an array called ‘shopping’ and I’ve added four elements in it.

Also, array elements are numbered from zero. For example this is how you access the first array element:

shopping[0];		

Functions

A function is a block of organised, reusable code that is used to perform single, related action.

Let’s create a function that calculates the product of two numbers.

To declare a function in JavaScript use the ‘function’ keyword. For example:

function product(a, b) {
return a*b;
}

In the above example, I’ve declared a function called ‘product’ and I’ve passed 2 parameters to this function, ‘a’ and ‘b’ which are variables whose product is returned by this function. Now, in order to call a function and pass a value to these parameters you’ll have to follow the below syntax:

product(8,2);

In the above code snippet I’m calling the product function with a set of values (8 & 2). These are values of the variables ‘a’ and ‘b’ and they’re called as arguments to the function.

Conditional statements – if

Conditional statement is a set of rules performed if a certain condition is met. The ‘if’ statement is used to execute a block of code, only if the condition specified holds true.

What is JavaScript – if flowchart

To declare an if statement in JavaScript use the ‘if’ keyword. The syntax is:

if(condition) {
statement;
}

Now let’s look at an example:

let numbers=[1,2,1,2,3,2,3,1];
if(numbers[0]==numbers[2]) {
console.log('Correct!');
}

In the above example I’ve defined an array of numbers and then I’ve defined an if block. Within this block is a condition and a statement. The condition is ‘(numbers[0]==numbers[2])’ and the statement is ‘console.log(‘Correct!’)’. If the condition is met, only then the statement will be executed.

Conditional statements- Else if

Else statement is used to execute a block of code if the same condition is false.

What is JavaScript – Else-if flowchart

The syntax is:

if(condition) {
statement a;
}
else (condition) {
statement b;
}

Now let’s look at an example:

let numbers=[1,2,1,2,3,2,3,1];
if(numbers[0]==numbers[4] {
console.log("Correct!");
}
else {
console.log("Wrong, please try again");
}

In the above example, I’ve defined an if block as well as an else block. So if the conditions within the if block holds false then the else block gets executed. Try this for yourself and see what you get!

**Loops **

Loops are used to repeat a specific block until some end condition is met. There are three categories of loops in JavaScript :

  1. while loop
  2. do while loop
  3. for loop
While loop

While the condition is true, the code within the loop is executed.

What is JavaScript – while loop flowchart

The syntax is:

while(condition) {
loop code;
}

Now let’s look at an example:

let i=0;
while(i < 5) {
console.log("The number is " +i);
i++;
}

In the above example, I’ve defined a while loop wherein I’ve set a condition. As long as the condition holds true, the while loop is executed. Try this for yourself and see what you get!

Do while loop

This loop will first execute the code, then check the condition and while the condition holds true, execute repeatedly.

What is JavaScript – Do while loop flowchart

Refer the syntax to better understand it:

do {
loop code;
} while(condition);

This loop executes the code block once before checking if the condition is true, then it will repeat the loop as long as the condition holds true.

Now let’s look at an example:

do {
console.log("The number is " +i);
i++;
}
while(i > 5);

The above code is similar to the while loop code except, the code block within the do loop is first executed and only then the condition within the while loop is checked. If the condition holds true then the do loop is executed again.

For loop

The for loop repeatedly executes the loop code while a given condition is TRUE. It tests the condition before executing the loop body.

What is JavaScript – for loop flowchart

The syntax is:

for(begin; condition; step) {
loop code;
}

In the above syntax:

  • begin statement is executed one time before the execution of the loop code
  • condition defines the condition for executing the loop code
  • step statement is executed every time after the code block has been executed

For example:

for (i=0;i<5;i++) {
console.log("The number is " +i);
}

In the above example, I’ve defined a for loop within which I’ve defined the begin, condition and step statements. The begin statement is that ‘i=0’. After executing the begin statement the code within the for loop is executed one time. Next, the condition is checked, if ‘i<5’ then, the code within the loop is executed. After this, the last step statement (i++) is executed. Try this and see what you get!

Switch Case

The switch statement is used to perform different actions based on different conditions.

What is JavaScript – Switch case flowchart

Let’s look at the syntax for switch case:

switch(expression) {
case 1:
code block 1
break;
case 2:
code block 2
break;
default:
code block 3
break;
}

How does it work?

  • Switch expression gets evaluated once
  • Value of the expression is compared with the values of each case
  • If there is a match, the associated block of code is executed

Let’s try this with an example:

let games='football';
switch(games) {
case "throwball":
console.log("I dislike throwball!");
break;
case "football":
console.log("I love football!");
break;
case "cricket":
console.log("I'm a huge cricket fan!");
break;
default:
console.log("I like other games");
break;
}

In the above example the switch expression is ‘games’ and the value of games is ‘football’. The value of ‘games’ is compared with the value of each case. In this example it is compared to ‘throwball’, ‘cricket’ and ‘football’. The value of ‘games’ matches with the case ‘football’, therefore the code within the ‘football’ case is executed. Try this for yourself and see what you get!

With this, we come to the end of this blog. I hope you found this blog informative and I hope you have a basic understanding of JavaScript. In my next blog on JavaScript I’ll be covering in-depth concepts, so stay tuned.

Also, check out our video on JavaScript Fundamentals if you want to get started as soon as possible and don’t forget to leave a comment if you have any doubt and also, let us know whether you’d want us to create more content on JavaScript. We are listening!