JavaScript Basics

From Grundy
Jump to navigation Jump to search

JavaScript is a dynamic computer programming language. It is lightweight and most commonly used as a part of web pages, whose implementations allow client-side script to interact with the user and make dynamic pages. It is an interpreted programming language with object-oriented capabilities. JavaScript is one of the 3 languages all web developers are recommended to learn:

1. HTML to define the content of web pages

2. CSS to specify the layout of web pages

3. JavaScript to program the behaviour of web pages


Web pages are not the only place where JavaScript is used. Many desktop and server programs use JavaScript. Some databases, like MongoDB and CouchDB, also use JavaScript as their programming language.

Prerequisite

Although there is no prerequisite for learning JavaScript as it is standalone language. But for practising JavaScript in webpages, it is highly recommended to have knowledge of HTML and CSS. To revise/learn HTML or CSS, click on respective link above.

Is JavaScript your first programming language?

Don’t worry, you can start learning JavaScript from basics, and it does not require much programming knowledge. You can gather this knowledge from JavaScript and can use this to learn other programming languages as well!! Here are some good sources which will help you learn about JavaScript from basics -

P.S. If you want to learn other programming languages, then please give sufficient time to this part and learn variables, operators, if-else and loop and other basic syntax very clearly. Happy Learning!!

Installation

You need not to install anything to run a JavaScript enabled web page as most of the web browser supports JavaScript by default. You can make your JavaScript file (in Notepad if you don’t have any Code Editors), save it with extension ‘.js’ and can attach it to your HTML file or can run it on browser console. But notepad is not much user friendly and that’s why most programmers install code editor for the same.

The following are some famous code editors that can be used:

Node.js is an application used by many programmers for Advance JavaScript programming and other backend works. We will talk more about it later. You can download node.js form here.

Learn JavaScript - Tutorials and Exercises

These are some good source which can help you learn and practice JavaScript.

Example

Q) To input two numbers and add them to show the result in Alert box.

Solution >

HTML file
<html>
  <head>
    <title>
      Textbox Add Numbers Demo
    </title>
    <script src="add1.js"></script>
  </head>
  <body>
    <form onsubmit="return add();">
      VAR X = <input type="text" id="varX" required value="3"/>
      <br>
      VAR Y = <input type="text" id="varY" required value="5"/>
      <br>
      <input type="submit" value="Add Them!"/>
    </form>
  </body>
</html>


JavaScript file(add1.js)
function add () {
  // Get the value of the text boxes
  let x = document.getElementById("varX").value;
  let y = document.getElementById("varY").value;

  // Add them together
  let z = x + y;
  alert(z); // !! 35 !!

  // This will stop the form from being submitted.
  // * Stop the page from refreshing.
  return false;
}

But, what will happen is the answer returned will be 35. So what's the problem? The problem is it considers 3 and 5 both as text and concatenate them.

Now that you know the mystery behind the “hiccup”, there are 2 ways that we can fix it:

  • By using <input type="number"/> instead, to enforce a number input.
  • By “converting” the string to integer or float in Javascript.

Correct Solution >

HTML file
<!DOCTYPE html>
<html>
  <head>
    <title>
      Textbox Add Numbers Demo
    </title>
    <script src="add2.js"></script>
  </head>
  <body>
    <form onsubmit="return add();">
      VAR X = <input type="number" id="varX" required value="3"/>
      <br>
      VAR Y = <input type="number" id="varY" required value="5"/>
      <!-- You can use the step attribute to allow decimals 
      VAR Y = <input type="number" id="varY" required value="5" step="0.1"/>
      -->
      <br>
      <input type="submit" value="Add Them!"/>
    </form>
  </body>
</html>
JavaScript file(add2.js)
function add () {
  // Get the value of the text boxes
  let x = document.getElementById("varX").value;
  let y = document.getElementById("varY").value;

  // "Convert" string to integer
  x = parseInt(x);
  y = parseInt(y);
  // Alternatively, use parseFloat if you want decimals
  // x = parseFloat(x);

  // This is correct now
  let z = x + y;
  alert(z); // 8
  return false;
}

Projects

These are some cool projects which will help you practice JavaScript with HTML and CSS and will thrill you with real time web coding

Node.js

Node.js is an open source, cross-platform runtime environment for developing server-side and networking applications. Node.js applications are written in JavaScript, and can be run within the Node.js runtime on OS X, Microsoft Windows, and Linux. Node.js also provides a rich library of various JavaScript modules which simplifies the development of web applications using Node.js to a great extent. To know more about Node.js, head to our wiki article node.js

Javascript Frameworks

A software framework is an abstraction in which software providing generic functionality can be selectively changed by additional user-written code. JavaScript framework is an application framework written in JavaScript where the programmers can manipulate the functions and use them for their convenience. They provide an easy and convenient way for HTML document traversal and manipulation (DOM), event handling, animation, and Ajax. It is a programming script that runs in the web browser. Some popular JS frameworks are Angular, Vue.js, React, jQuery etc. Among these, jQuery is one of the most easiest to learn and implememnt in a webpage.

jQuery

jQuery is a fast, small, and feature-rich JavaScript library. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript. Mastering jQuery is quite an easy task and can be done in a few hours, depending on your expertise in JavaScript.

Getting Started

Head over to the downloads page of jQuery and download the latest version of the script. Once you have downloaded jQuery, place the jquery.js in the scripts folder of your website and get started with customizing the interactions in the website with the tools that jQuery provides.

For beginners here is a list of websites:

Examples

Q1) Setting CSS properties

Change_background_colour.html
<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    
  </head>
  
  <body>

    <h2>This is a heading</h2>

    <p style="background-color:#ff0000">This is a paragraph.</p>
    <p style="background-color:#00ff00">This is a paragraph.</p>
    <p style="background-color:#0000ff">This is a paragraph.</p>

    <p>This is a paragraph.</p>

    <button>Set background-color of p</button>

    <script>
      $(document).ready(function(){
        $("button").click(function(){
          $("p").css("background-color", "yellow");
        });
      });
    </script>

    <!--
     The $ indicates a jQuery function
     document.ready() will be triggered when the webpage finishes loading
     button.click() is triggered by clicking the button
     p.css changes the css attributes for the p elements
      -->

  </body>
</html>

Q2) Simple animation

Animate_Hello_World.html
<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    
  </head>

  <body>

    <button id="start">Start</button>
    <button id="stop">Stop</button>
    <button id="stop2">Stop all</button>
    <button id="stop3">Stop but finish</button>

    <p>The "Start" button starts the animation.</p>
    <p>The "Stop" button stops the current active animation, but allows the queued animations to be performed afterwards.</p>
    <p>The "Stop all" button stops the current active animation and clears the 
      animation queue; so all animations on the element is stopped.</p>
    <p>The "Stop but finish" rushes through the current active animation, then it stops.</p> 

    <div style="background:#98bf21;height:100px;width:300px;position:absolute;"> Hello, World!</div>

    <script> 
      $(document).ready(function(){
        $("#start").click(function(){
          $("div").animate({left: '100px'}, 5000);
          $("div").animate({fontSize: '3em'}, 5000);
        });
  
        $("#stop").click(function(){
          $("div").stop();
        });

        $("#stop2").click(function(){
          $("div").stop(true);
        });

        $("#stop3").click(function(){
          $("div").stop(true, true);
        }); 
      });
    </script> 

    <!--
    #start means id=start
    element.animate is used for quickly adding animations to webpage
    element.stop is used to stop the current animation, adding parameters gives more control over other animations as well
     -->

  </body>
</html>

Q3) Ajax load method

Ajax_load_with_callback.html
<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> 
  </head>

  <body>

    <div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>

    <button>Get External Content</button>

    <script>
    $(document).ready(function(){
      $("button").click(function(){
        $("#div1").load("demo_test.txt", function(responseTxt, statusTxt, xhr){
          if(statusTxt == "success")
            alert("External content loaded successfully!");
          if(statusTxt == "error")
            alert("Error: " + xhr.status + ": " + xhr.statusText);
        });
      });
    });
    </script>

    <!--
    The load button is used for Ajax
    -->

  </body>
</html>

Practice

Here is a list of exercices to practice what you have learnt in jQuery.

Once you have a decent working knowledge on jQuery and JavaScript in general, you can also try some complex and interesting applications

Useful Links