Fundamentals of jQuery

Overview

JavaScript is primarily a regular computer language. To complement it with ways to easily and quickly perform some operations, a library named jQuery was created. It provides a short way to write JavaScript code. You can use jQuery to add functionality to your ASP.NET project.

Practical LearningPractical Learning: Introducing jQuery

  1. Start Microsoft Visual Studio
  2. To create new website, on the main menu of , click File -> New -> Project ...
  3. In the New Project dialog box, in the left frame, under Visual C#, click Web
  4. In the middle frame, click ASP.NET Web Application (.NET Framework)
  5. Change the project Name to Exercise1
  6. Press Enter
  7. In the New ASP.NET Wep Application dialog box, click the MVC icon
  8. Click OK

Introduction to the jQuery Script

jQuery is a library. It is provided as one or more files. The files have the extension .js as JavaScript files. To use jQuery, you must provide a reference to the library. If you are regularly creating a webpage (or a website), you must first download the library from jquery.com. Normally, if you are working in Microsoft Visual Studio, the jQuery library has already been installed.

Practical LearningPractical Learning: Introducing the jQuery Script

Using jQuery in a Web Page

To use jQuery, you must indicate where its library is located. This means that you must add a reference to the file that contains the primary functionality you want. You have various options. As seen with JavaScript, you can include the file by creating a <script></script> section. In the start tag, add a src attribute. Assign the path and the name of the file you want to use. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Exercise</title>
<script src="Scripts/jquery-3.3.1.js"></script>
</head>
<body>

</body>
</html>

You can also put the library reference in the body of the webpage. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Exercise</title>
</head>
<body>

<script src="Scripts/jquery-3.3.1.js"></script>

</body>
</html>

To write jQuery code in the same file that needs it, create a <script></script> section. Here are examples:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Exercise</title>
<script src="Scripts/jquery-3.3.1.js"></script>
</head>
<body>
<h1>Exercise</h1>

<script>
    
</script>

</body>
</html>

Between <script> and </script>, you can write the code you want. As an option, in the <script> start tag, you can add the TYPE attribute and specify its value as text/javascript.

A File for jQuery Code

If you want, you can create a JavaScript file in which you want to define your jQuery functionality. To do this, start a text-based file. In the document, write the necessary jQuery code. Save the file with the .js extension.

Minified Versions of Files

Some of the library files are provided in various versions, one regular and one minified versions. The minified version contains .min in its name. As a result, jQuery comes in a file named jquery-1.10.2.js. The minified version is named jquery-1.10.2.min.js. AngularJS comes in a file named angular.js. The minified version is named angular.min.js.

jQuery and ASP.NET Projects

If you create an ASP.NET MVC project in Microsoft Visual Studio, the studio creates a file named BundleConfig.cs. That file contains a class of the same name. That class contains a static method named RegisterBundles. In that method, the BundleCollection class is used to create a list of the libraries and CSS formats that your project needs. As a result, that class adds a reference to the jQuery library. If necessary, you can add more libraries through that method.

Practical LearningPractical Learning: Checking jQuery Reference

  1. In the Solution Explorer, expand App_Start and double-click BundleConfig.cs to see the references to jQuery:
    using System.Web;
    using System.Web.Optimization;
    
    namespace Exercises
    {
        public class BundleConfig
        {
            // For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862
            public static void RegisterBundles(BundleCollection bundles)
            {
                bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                            "~/Scripts/jquery-{version}.js"));
    
                bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                            "~/Scripts/jquery.validate*"));
    
                // Use the development version of Modernizr to develop with and learn from. Then, when you're
                // ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
                bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                            "~/Scripts/modernizr-*"));
    
                bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                          "~/Scripts/bootstrap.js"));
    
                bundles.Add(new StyleBundle("~/Content/css").Include(
                          "~/Content/bootstrap.css",
                          "~/Content/site.css"));
            }
        }
    }
  2. In the Solution Explorer, expand Controllers and double-click HomeController.cs
  3. To create a left outer join, change the SQL statement as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace Exercise1.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                return View();
            }
    
            public ActionResult About()
            {
                ViewBag.Message = "Your application description page.";
    
                return View();
            }
    
            public ActionResult Contact()
            {
                ViewBag.Message = "Your contact page.";
    
                return View();
            }
    
            public ActionResult Exercise()
            {
                return View();
            }
        }
    }
  4. Right-click the public ActionResult Exercise() line and click Add View...
  5. In the Add View dialog box, make sure the View Name text box is displaying Exercise.
    Click Add

Accessing jQuery in a Web Page

To access jQuery in an ASP.NET MVC view, call the Render() method of the Scripts class and pass the path to the jQuery library.

Practical LearningPractical Learning: Checking jQuery Reference

Introduction to jQuery Code

The $ Namespace

jQuery supports functions as they are used in JavaScript. jQuery also supports JavaScript built-in functions. To give you access to many functions you can directly use in your code, jQuery provides a special namespace named $. It works like a static class. This means that you don't declare a variable of it. To use one of the multiple members of this namespace, type $. followed by the desired member.

A jQuery Object

To support a way to create objects adapted for jQuery code, the library provides a special object created as $(). As you can see, the jQuery object appears as a function named $ or rather a constructor. This object takes two arguments. The first is required and the second is optional.

Selecting an HTML Element in jQuery

While JavaScript supports the ability to locate and select an element in a webpage, jQuery provides its own $() object. The primary formula to follow is:

$(...)

As mentioned in the previous section, the $() jQuery object takes some type of argument. In some cases, the parentheses will contain the whole code you want to use. In some other cases, you will add some necessary behavior after the parentheses.

To access a DOM object in jQuery, you can pass that object in the parentheses of $(). For example, to access a webpage document in jQuery, you can use $(document). To access the Window object of a browser in jQuery, you can use $(window).

An Object for an Element

As you may be aware, a webpage is created by using HTML tags. Each tag has a name and some tags have one or more attributes. To let you represent a tag as an object in jQuery, a tag can be passed by its name as a string in the parentheses of $(). For example, to use a paragraph as an object in jQuery, use $("p"). To use a link as an object in jQuery, use $("a"), and so on.

Introduction to DOM Events in jQuery

Overview

After specifying the object you want to access from a webpage, you can attach the event it will fire. jQuery supports the same events of JavaScript and the same names.

To attach a JavaScript (a DOM) event to a selected element, after the parentheses of $(...), type a period and on() in a formula as follows:

$(object).on(event-name, function-definition);

In the parentheses of $(), you will include an object. The on() method takes two arguments. The first is the DOM name of the event you want to use. The name is passed as a string. The second argument is the function that will carry the event, that is, the job you want to do when the event fires. You can first define the function and then pass its name as the second argument to the on() method. As an alternative, you can define the function directly in the second argument placeholder.

Once the Document is Ready

As you may be aware, just before a webpage displays, the browser fires the onload event. To apply this event, you can use the following formula:

$(object).on("load", function-definition);

The object can be window. To let you catch the load event, jQuery provides a method named ready. To use it, apply it to $(...) to which you would pass a document object as in $(document).ready(). Pass a function to the ready() method. The formula to follow is:

$( document ).ready(function-definition);

As mentioned earlier, you can first define a function and then pass it as argument. The formula to follow is:

function doSomething(){
}

$( document ).ready(doSomething);

Otherwise, you can define the function directly in the parentheses of the ready() method. Either way, in the body of the function, create the behavior you want.

As a shortcut to the ready() event, jQuery allows you to omit the (document).ready section. As a result, simply include the function definiton in the parentheses of $().

Practical LearningPractical Learning: Introducing jQuery Code

Clicking an Element

One of the most regular operations performed on an object of a webpage is to click. This action causes the control to fire an event named click. To apply this event, you can attach it to an element selected through $(). As you may know already, events are carried by functions. Like most events, the click() method takes one argument which is a function. You can first define a function and then pass its name as argument to click(), or you can define the function directly in the parentheses of click(). This would be done as follows:

$(document).ready(function () {
    $("something").click(function (event) {
    });
});

As an alternative, attach a method named on. It uses two values. The first is the name of the event, in this case "click". The second value is the function that will carry the event. An example is:

@{
    ViewBag.Title = "Exercise";
}

<h2>Exercise</h2>

@Scripts.Render("~/bundles/jquery")

<script type="text/javascript">
    $(document).ready(function () {
        $("Something").on("click", function (event) {
           
        });
    });
</script>

Practical LearningPractical Learning: Clicking an Element

  1. Change the code as follows:
    @{
        ViewBag.Title = "Exercise";
    }
    
    <h2>Exercise</h2>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript" language="JavaScript">
        $(document).ready(function () {
            $("h2").click(function (event) {
                alert("Welcome to the wonderful world of jQuery");
            });
        });
    </script>
  2. To execute, on the main menu, click Debug -> Start Without Debugging
  3. In the webpage, click Exercise
  4. Read the message box and click OK
  5. Close the browser and return to your programming environment

Introduction to jQuery Code

Variables

jQuery supports variables exactly as they are declared and used in JavaScript. Here is an example:

@{
    ViewBag.Title = "Exercise";
}

<h2>Exercise</h2>

@Scripts.Render("~/bundles/jquery")

<script type="text/javascript" language="JavaScript">
    $(document).ready(function () {
        $("h2").click(function (event) {
            var msg = "Welcome to the wonderful world of jQuery";

            alert(msg);
        });
    });
</script>

jQuery Operators

jQuery supports the same operators as the JavaScript language.

Comments

Because jQuery is primarily a library, it supports the comments as they are used in JavaScript.

Introduction to JavaScript Built-In Objects

jQuery is primarily just a JavaScript library. JQuery supports and recognizes the objects used in JavaScript such as the window, the document, etc. As a result, you can access the members of the window object directly in your jQuery code. For example, to display a message box, simply call the alert() function and pass the desired string to it.

Primary Characteristics of an Element

The HTML Markup of a Selected Element

As we will see in the next sections, one of the types of items you can select on a webpage is the name of an HTML tag. After making such a selection, to let you specify the text of the element, jQuery provides a method named html. To call this method, attach it to $("tag-name"). An example is $("p").html(). In the parentheses of the html() method, pass the text as string. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Quotes</title>
<script src="Scripts/jquery-3.3.1.js"></script>
</head>
<body>
<h1>Nixon Quotes</h1>

<p>Quotes</p>

<script>
    $(document).ready(function () {
        $("p").html("If you take no risks, you will suffer no defeats. But if you take no risks, you win no victories.");
    });
</script>

</body>
</html>

One of the valuable features of the html() method is that it takes and recognizes both HTML attributes and CSS formatting if you include them appropriately in the argument of the method. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Quotes</title>
<script src="Scripts/jquery-3.3.1.js"></script>
</head>
<body>
<h1>Saying</h1>

<p>Quotes</p>

<script>
    $(document).ready(function () {
        $("p").html("When the President does it, that means that it&#039s not illegal. - <b>Richard M. Nixon</b>");
        $("h1").html("<span style='font-weight: bold; color: #800000'>President Nixon Quotes</span>");
    });
</script>

</body>
</html>public

The Value of an Element

As you may know already, to represent the value of a web control, the DOM provides the val() method. After selecting an element, you can apply this method to it and pass the string you want to display. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Employee Record</title>
<script src="Scripts/jquery-3.3.1.js"></script>
</head>
<body>
<h1 class="empl-rec">Employee Record</h1>

<p>Full Name: <input type="text" /></p>  

<script>
    $(document).ready(function () {
        $("input").val("Antoine Mayer");
    });
</script>

</body>
</html>

The Text of an Element

If the element whose value you want to display is not a webcontrol but another type of HTML tag, to let you display such a value, the DOM provides a method named text. Here is an example:

@{
    ViewBag.Title = "Exercise";
}

<p><b>President:</b> <span id="fullName"></span></p>

@Scripts.Render("~/bundles/jquery")

<script type="text/javascript">
    $(document).ready(function () {
        $("span").text("Richard Nixon");
    });
</script>

Practical LearningPractical Learning: Ending the Lesson


Home Copyright © 2017-2019, FunctionX Next