Client-side development 1 - j Query


ee

 Libraries

A library is an organized collection of useful functionality. A typical library could include functions to handle strings, dates, HTML DOM elements, events, cookies, animations, network requests, and more. Each function returns values to the calling application which can be implemented however you choose. Think of it as a selection of car components: you’re free to use and to help construct a working vehicle but you must build the engine yourself.

Libraries normally provide a higher level of abstraction which smooths over implementation details and inconsistencies. For example, Ajax can be implemented using the XMLHttpRequest API but this requires several lines of code and there are subtle differences across browsers. A library may provide a simpler ajax() function so you’re free to concentrate on higher-level business logic.

A library could cut development time by 20% because you don’t have to worry about the finer details. The downsides:

a bug within a library can be difficult to locate and fix
there’s no guarantee the development team will release a patch quickly
a patch could change the API and incur significant changes to your code.



Frameworks

dd

A framework is an application skeleton. It requires you to approach software design in a specific way and insert your own logic at certain points. Functionality such as events, storage, and data binding are normally provided for you. Using the car analogy, a framework provides a working chassis, body, and engine. You can add, remove or tinker with some components presuming the vehicle remains operational.

A framework normally provides a higher level of abstraction than a library and can help you rapidly build the first 80% of your project. The downsides:

the last 20% can be tough going if your application moves beyond the confines of the framework updates or migrations can be difficult – if not impossible
core framework code and concepts rarely age well. Developers will always discover a better way to do the same thing.

 jQuery

jQuery is a lightweight, "write less, do more", JavaScript library.

The purpose of jQuery is to make it much easier to use JavaScript on your website.

jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish and wraps them into methods that you can call with a single line of code.

jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation.

The jQuery library contains the following features:


  • HTML/DOM manipulation
  • CSS manipulation
  • HTML event methods
  • Effects and animations
  • AJAX
  • Utilities


Tip: In addition, jQuery has plugins for almost any task out there.

There are lots of other JavaScript frameworks out there, but jQuery seems to be the most popular, and also the most expendable.

Many of the biggest companies on the Web use jQuery, such as:


  • Google
  • Microsoft
  • IBM
  • Netflix


Will jQuery work in all browsers


The jQuery team knows all about cross-browser issues, and they have written this knowledge into the jQuery library. jQuery will run exactly the same in all major browsers.

Features of jQuery


- jQuery is a write less and do more javascript library.

- It helps us to make the use of javascript much easier.

- It simplifies the complicated things from javascript like the AJAX calls and the DOM manipulation.

Other Features of jQuery are :

1. Effects and animations.
2. Ajax.
3. Extensibility.
4. DOM element selections functions.
5. Events.
6. CSS manipulation.
7. Utilities - such as browser version and each function.
8. JavaScript Plugins.
9. DOM traversal and modification.


The advantages of jQuery


The main advantage of jQuery is that it is much easier than its competitors. You can add plugins easily, translating this into a substantial saving of time and effort. In fact, one of the main reasons why Resig and his team created jQuery was to buy time (in the web development world, time matters a lot).

The open source license of jQuery allows the library to always have constant and fast support, constantly publishing updates. The jQuery community is active and extremely hardworking.

Another advantage of jQuery over its competitors such as Flash and pure CSS is its excellent integration with AJAX

The disadvantages of jQuery


One of the main disadvantages of jQuery is a large number of published versions in a short time. It does not matter if you are running the latest version of jQuery, you will have to host the library yourself (and update it constantly), or download the library from Google (attractive, but can bring incompatibility problems with the code).

In addition to the problem of the versions, other disadvantages that we can mention:

jQuery is easy to install and learn, initially. But it’s not that easy if we compare it with CSS
If jQuery is improperly implemented as a Framework, the development environment can get out of control.

Revisiting Partial View Rendering in ASP.NET MVC


  • For any browser-based application, it makes sense to load into the web page just the content that is immediately required and avoid whole-page refreshes whenever possible. Ajax technology and JSON makes this partial-rendering easy. It is, however, worth considering ASP.NET's own partial-rendering techniques, returning HTML. It requires less client-logic and is quicker to implement.


  • In the real world, or at least in the section of the real world that I see every day, there are still plenty of classic ASP.NET Web Forms and ASP.NET MVC web sites. By ‘classic web sites’ mean web sites where the vast majority of pages are being served entirely from the web server and fully refreshed after each postback. The full refresh of the page after a postback can be significantly slow and cumbersome for users, especially when the use of graphics of these sites is quite heavy. This is the reason why at some point Ajax and partial rendering of pages became so popular.


  • Today, the Ajax approach is often taken to the limit when single-page applications (SPA) are built. A single-page application (or just a few-pages application) downloads from the web server as an empty DIV element. All the remaining content is inserted dynamically after placing additional HTTP requests for JSON data. In this context, posting a form is merely a JavaScript-driven request. The response of such a request is mostly JSON data that the local script will process as appropriate, updating the user interface. As you can easily appreciate, the performance problem of the full page refresh just doesn’t exist anymore.


  • In between SPAs and classic full page refresh solutions, there are techniques based on plain jQuery calls to HTTP endpoints returning JSON data. Technically speaking, a jQuery solution is not that much different from anything you can do in a SPA; However, it is a technique that you can use just where required and appropriate but not necessarily throughout the entire solution. You can use jQuery to make a GET request and receive JSON data. Such data is then incorporated in the current DOM via HTML templates and libraries such as Knockout or AngularJS. You can also use jQuery to place a POST request and receive back a plain ack message or some JSON data.


  • All this is well-known and, for the most part, it is mainstream practice today. In this article, instead, I’ll discuss a different approach for partial page refreshes that is closer to what in ASP.NET Web Forms and ASP.NET MVC is still referred to as ‘partial rendering’. The idea behind partial rendering is that of placing a jQuery call, having the endpoint perform its command or query and then returning any response as pure HTML. Some SPA purists may dislike this approach because they may say-returning HTML is less efficient than returning plain JSON data. True, but the techniques presented in this article are a lot smoother to implement in coding scenarios where the predominant skills are server-side ASP.NET Web Forms and ASP.NET MVC. Still, a bit of JavaScript is required, but it is limited to using familiar DOM properties such as innerHTML or just a few core jQuery methods.

Setting Up a Sample Project


  • Let’s say you have an ASP.NET MVC project with a Razor view that produces the output of Figure 1. The page contains a list of data elements that users can delete one by one by clicking a button. In classic ASP.NET, you may have an HTML form all around the list and each of the delete buttons is implemented as a submit button. When any button is clicked, the page posts back. On the server, you figure out which button was clicked, and from there you get the ID of the element to delete.


HH


  • Here’s some code that illustrates the behavior of the ASP.NET MVC endpoint reached when any of the buttons in Figure 1 are clicked.

[HttpPost]
[ActionName("delete")]
public ActionResult DeletePost(int id)
{
    _repository.Delete(id);

    // Redirect to generate the subsequent view
    RedirectToAction("index");
}

  • The method DeletePost proceeds with the backend operation and then redirects to the method in charge of refreshing the view. This is an instance of the Post-Redirect-Get (PRG) pattern that keeps commands distinct from queries and also avoids the nasty problem of resending POST data when the user hits F5 from the browser. Here’s some sample code for the Index method.


public ActionResult Index()
{
   var customers = _repository.FindAll();
   var model = new IndexViewModel(customers);
   return View(model);
}

  • The Index method gets the updated list of customers (after the deletion) and refreshes the page. When the PRG pattern is used to implement a POST, the last action repeatable by the browser is always a GET. As a result, users will see the updated list of customers. Even if they press F5 or Refresh within the browser all they obtain is a plain refresh of the page; no additional deletion of data occurs.


  • How can this code be improved to avoid a full page refresh without rewriting the entire application, or large portions of it, like a SPA? A possible approach is based on the HTML Message pattern-one of the most popular Ajax patterns. The HTML Message pattern refers to a situation in which the request carries back ready-to-display markup instead of raw (JSON) data.

The PartialView Method


  • In ASP.NET MVC, a partial view is analogous to user controls in ASP.NET Web Forms. A partial view is a chunk of HTML that can be safely inserted into an existing DOM. Most commonly, partial views are used to componentize Razor views and make them easier to build and update. Partial views can also be returned directly from controller methods. In this case, the browser still receives text/HTML content but not necessarily HTML content that makes up an entire page. As a result, if a URL that returns a partial view is directly invoked from the address bar of a browser, an incomplete page may be displayed. This may be something like a page that misses title, script and style sheets. However, when the same URL is invoked via a script, and the response is used to insert HTML within the existing DOM, then the net effect for the end user may be much better and nicer.


  • With an eye on Figure 1, let’s see what we could do to have users click a delete button and update the list of customers without spinning a full page refresh.


  • The most important point to remember is that an endpoint that returns a partial HTML view should only be called via script. The list of customers of Figure 1, therefore, might be generated from code as below. By the way, the sample code below is based on Bootstrap.


<div class="col-md-6" id="listOfCustomers"> 
<table class="table table-condensed">
    @foreach (var c in Model.Customers)
    {
        <tr>
            <td>@c.Id</td>
            <td>@c.Name</td>
            <td>@c.Address</td>
            <td>
                <button class="btn btn-xs btn-danger" onclick="d(@c.Id)">
                   <span class="glyphicon glyphicon-trash"></span>
                </button>
            </td>
        </tr>
    }
</table>
</div>

  • Clicking the button triggers a JavaScript function. The JavaScript function receives the ID of the customer the user intends to delete and calls the appropriate controller method. When the remote call returns the script grabs the HTML chunk and updates the DIV element container of the customer list.

function d(id) {
    var url = "/home/delete/";
    $.post(url, { id: id })
     .done(function (response) {
            $("#listOfCustomers").html(response);
    });

  •  On the server side, the Delete method on the controller class becomes as shown below:


[HttpPost]
[ActionName("delete")]
public ActionResult DeletePost(int id)
{
    // Executes the command
    _repository.Delete(id);

    // Return HTML to update the view
    return PartialView(Common.Views.ListOfCustomers);
}


  • To make the actual behavior of the method clear to occasional readers of the code from the beginning, you can also change the return type of the controller method from a generic ActionResult to a more specific PartialViewResult type. The actual behavior doesn’t change, but the code is inherently easier to understand.


  • Let’s review the new mechanics of the page. When users click to delete a record, a POST request is made to an HTTP endpoint within a controller. The controller deletes the record and returns a chunk of HTML for the script to use and update the current DOM. The request is sent over as a POST, but at the end of the day there’s no strict requirement for a POST verb; a GET would work anyway. At the same time, because the request is expected to cause a state change on the server side, it’s ideally configured to be a POST. The request is placed using JavaScript and it’s not tracked by the browser. Whether it goes as a GET or POST, it won’t be repeatable if the user hits F5. For the end user, the net effect is that changes become immediately visible without any page flickering.

Limitations of this Technique


  • The amount of script code used for this technique is the bare minimum. This is good and bad news at the same time. It’s good because any line of code is under your strict control: it’s all about jQuery, the DOM and you. It’s bad because dependencies between controller, Razor view and JavaScript code are explicit. If you happen to change, say, the ID of the DIV in the Razor view you may break the script. Likewise, if you modify the script or the code in the controller you may cause unexpected results in the HTML being served to the user. In a nutshell, the three elements (controller, Razor view, script code) must work together in perfect harmony.


SS


  • There’s another drawback, however, in the technique discussed so far. To see what it is, have a look at Figure 2.
  • The drop-down menu in the figure has one item for each customer in the list. This means that when the user clicks a button to delete a customer from the client-side, it is not enough to refresh the list. Also, the contents of the drop-down should be updated. This is not an issue, instead, if the entire page is rebuilt on the server as during a classic postback and a full page refresh. Likewise, this is not an issue if you are in the context of the SPA. In this case, the request brings back raw JSON data that the client-side logic knows how to handle to update all the involved segments of the user interface.


  • More in general, whenever you send a request via JavaScript multiple segments of the user interface may be touched by the effects of that request. And when the request is coded to return ready-to-display markup, multiple chunks of HTML should be returned. Let’s see how to do this.


Combining Multiple Partial Views Together


  • The idea, therefore, is that a controller method (say, Delete) is invoked via JavaScript and returns multiple partial views. By design, a controller method must return a type derived from ActionResult but none of the predefined action result types supports multiple HTML chunks. Hence, a new action result type is in order.

public class MultipleViewResult : ActionResult
{
    public const string ChunkSeparator = "---|||---";
    public IList<PartialViewResult> PartialViewResults { get; private set; }

    public MultipleViewResult(params PartialViewResult[] views)
    {
        if (PartialViewResults == null)
            PartialViewResults = new List<PartialViewResult>();
        foreach(var v in views)
            PartialViewResults.Add(v);
    }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
            throw new ArgumentNullException("context");
        var total = PartialViewResults.Count;
        for (var index = 0; index < total; index++)
        {
            var pv = PartialViewResults[index];
            pv.ExecuteResult(context);
            if (index < total - 1)
                context.HttpContext.Response.Output.Write(ChunkSeparator);
        }
    }
}


  • The constructor of the MultipleViewResult type accepts a list of PartialViewResult types and caches them internally in a read-only collection. An action result type must necessarily override the ExecuteResult method declared as abstract in the base class. ASP.NET MVC requires that implementation of ExecuteResult just writes down any response to the output stream.


  • Because MultipleViewResult contains multiple instances of PartialViewResult, it is sufficient to loop over the collection of PartialViewResult objects and ask each to execute. Finally, a separator must be added so that on the client side the various chunks can be easily detected. In principle, you can use any character (or a combination thereof) to separate HTML chunks. In practice, instead, any character, or combination of characters, that is common in the HTML body can break the script. I usually use a string like “—|||—“, but feel free to adapt it to your own purposes. With the MultipleViewResult class in place, here’s how to rewrite the controller method:


public ActionResult DeleteCustomer(int id)
{
    _repository.Delete(id);
    var customers = _repository.FindAll();

    // Combine multiple partial views 
    var model = new IndexViewModel(customers);
    return new MultipleViewResult(
        PartialView(Common.Views.ListOfCustomers, model),
        PartialView(Common.Views.OnBehalfOfCustomers, model));
}


  • In the example, the two partial views use the same view model. This is not a limitation though. The script code in the client page receives a single string and unpacks it before display.


function d(id) {
    var url = "/home/d/";
    $.post(url, { id: id })
     .done(function (response) {
        var chunkSeparator = "---|||---";
        var chunks = response.split(chunkSeparator);
        $("#listOfCustomers").html(chunks[0]);
        $("#onBehalfMenu").html(chunks[1]);
    });
}


  • Look at Figure 2 again and imagine a user that clicks on the selected customer. Figure 3 shows the final effect. The customer 435 has been removed from the backend database and the view has been updated instantaneously and without full page refresh. For the user, it is definitely a great experience.


AA


jQuery - Selectors


The jQuery library harnesses the power of Cascading Style Sheets (CSS) selectors to let us quickly and easily access elements or groups of elements in the Document Object Model (DOM).

A jQuery Selector is a function which makes use of expressions to find out matching elements from a DOM based on the given criteria. Simply you can say, selectors, are used to selecting one or more HTML elements using jQuery. Once an element is selected then we can perform various operations on that selected element.

The $() factory function

jQuery selectors start with the dollar sign and parentheses − $(). The factory function $() makes use of following three building blocks while selecting elements in a given document −


ddd


All the above items can be used either on their own or in combination with other selectors. All the jQuery selectors are based on the same principle except some tweaking.

NOTE − The factory function $() is a synonym of jQuery() function. So in case you are using any other JavaScript library where a $ sign is conflicting with something else then you can replace $ sign by jQuery name and you can use function jQuery() instead of $().

Example

Following is a simple example which makes use of Tag Selector. This would select all the elements with a tag name p

<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>

      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
            $("p").css("background-color", "yellow");
         });
      </script>
   </head>

   <body>
      <div>
         <p class = "myclass">This is a paragraph.</p>
         <p id = "myid">This is second paragraph.</p>
         <p>This is third paragraph.</p>
      </div>
   </body>
</html>

This will produce the following result −

ll

How to Use Selectors

The selectors are very useful and would be required at every step while using jQuery. They get the exact element that you want from your HTML document.

The following table lists down few basic selectors and explains them with examples.

jj

Selectors Examples

Similar to the above syntax and examples, the following examples would give you an understanding of using a different type of other useful selectors −

Here, you have different type of other useful selectors −
You can use all the above selectors with any HTML/XML element in generic way. For example if selector $("li:first") works for <li> element then $("p:first") would also work for <p> element.

Introducing CSS Selectors

A CSS selector is the part of a CSS rule set that actually selects the content you want to style. Let’s look at all the different kinds of selectors available, with a brief description of each.

Universal Selector

The universal selector works like a wild card character, selecting all elements on a page. Every HTML page is built on content placed within HTML tags. Each set of tags represents an element on the page. Look at the following CSS example, which uses the universal selector:

* {
   color: green;
   font-size: 20px;
   line-height: 25px;
}

The three lines of code inside the curly braces (color, font-size, and line-height) will apply to all elements on the HTML page. As seen here, the universal selector is declared using an asterisk. You can also use the universal selector in combination with other selectors.

Element Type Selector

Also referred to simply as a “type selector,” this selector must match one or more HTML elements of the same name. Thus, a selector of nav would match all HTML nav elements, and a selector of <ul> would match all HTML unordered lists, or <ul> elements.

The following example uses an element type selector to match all <ul> elements:

ul {
   list-style: none;
   border: solid 1px #ccc;
}

To put this in some context, here’s a section of HTML to which we’ll apply the above CSS:

<ul>
  <li>Fish</li>
  <li>Apples</li>
  <li>Cheese</li>
</ul>

<div class="example">
  <p>Example paragraph text.</p>
</div>

<ul>
  <li>Water</li>
  <li>Juice</li>
  <li>Maple Syrup</li>
</ul>


There are three main elements making up this part of the page: Two <ul> elements and a <div>. The CSS will apply only to the two <ul> elements, and not to the <div>. Were we to change the element type selector to use <div> instead of <ul>, then the styles would apply to the <div> and not to the two <ul> elements.

Also note that the styles will not apply to the elements inside the <ul> or <div> elements. That being said, some of the styles may be inherited by those inner elements.

ID Selector

An ID selector is declared using a hash, or pound symbol (#) preceding a string of characters. The string of characters is defined by the developer. This selector matches any HTML element that has an ID attribute with the same value as that of the selector, but minus the hash symbol.

Here’s an example:

#container {
   width: 960px;
   margin: 0 auto;
}

This CSS uses an ID selector to match an HTML element such as:

<div id="container"></div>

In this case, the fact that this is an <div> element doesn’t matter—it could be any kind of HTML element. As long as it has an ID attribute with a value of container, the styles will apply.

An ID element on a web page should be unique. That is, there should only be a single element on any given page with an ID of the container. This makes the ID selector quite inflexible because the styles used in the ID selector rule set can be used only once per page.

If there happens to be more than one element on the page with the same ID, the styles will still apply, but the HTML on such a page would be invalid from a technical standpoint, so you’ll want to avoid doing this.

In addition to the problems of inflexibility, ID selectors also have the problem of very high specificity.

Class Selector

The class selector is the most useful of all CSS selectors. It’s declared with a dot preceding a string of one or more characters. Just as is the case with an ID selector, this string of characters is defined by the developer. The class selector also matches all elements on the page that have their class attribute set to the same value as the class, minus the dot.

Take the following rule set:

.box {
   padding: 20px;
   margin: 10px;
   width: 240px;
}

These styles will apply to the following HTML element:

<div class="box"></div>

The same styles will also apply to any other HTML elements that have a class attribute with a value of the box. Having multiple elements on a single page with the same class attribute is beneficial because it allows you to reuse styles, and avoid needless repetition. In addition to this, class selectors have very low specificity—again, more on this later.

Another reason the class selector is a valuable ally is that HTML allows multiple classes to be added to a single element. This is done by separating the classes in the HTML class attribute using spaces. Here’s an example:

<div class=”box box-more box-extended”></div>

Descendant Combinator

The descendant selector or, more accurately, the descendant combinator lets you combine two or more selectors so you can be more specific in your selection method. For example:

#container .box {
   float: left;
   padding-bottom: 15px;
}

This declaration block will apply to all elements that have a class of box that is inside an element with an ID of the container. It’s worth noting that the .box element doesn’t have to be an immediate child: there could be another element wrapping .box, and the styles would still apply.

Look at the following HTML:

<div id="container">
  <div class="box"></div>

  <div class="box-2"></div>
</div>


<div class="box"></div>

If we apply the CSS in the previous example to this section of HTML, the only element that’ll be affected by those styles is the first <div> element that has a class of box. The <div> element that has a class of box-2 won’t be affected by the styles. Similarly, the second <div> element with a class of box won’t be affected because it’s not inside an element with an ID of the container.

You should be careful when using the descendant combinator in your CSS. This kind of selector, while making your CSS a little easier to read, can unnecessarily restrict your styles to a specific context—in this case, the styles are restricted to boxes inside of #container—which can make your code inflexible.

Child Combinator

A selector that uses the child combinator is similar to a selector that uses a descendant combinator, except it only targets immediate child elements:

#container > .box {
   float: left;
   padding-bottom: 15px;
}

This is the same code from the descendant combinator example, but instead of a space character, we’re using the greater-than symbol (or right angle bracket.)

In this example, the selector will match all elements that have a class of box and that are immediate children of the #container element. That means, unlike the descendant combinator, there can’t be another element wrapping .box—it has to be a direct child element.

Here’s an HTML example:

<div id="container">
  <div class="box"></div>

  <div>
    <div class="box"></div>
  </div>
</div>

In this example, the CSS from the previous code example will apply only to the first <div> element that has a class of box. As you can see, the second <div> element with a class of box is inside another <div> element. As a result, the styles will not apply to that element, even though it too has a class of box.

Again, selectors that use this combinator can be somewhat restricting, but they can come in handy—for example, when styling nested lists.

General Sibling Combinator

A selector that uses a general sibling combinator matches elements based on sibling relationships. That is to say, the selected elements are beside each other in the HTML.

h2 ~ p {
   margin-bottom: 20px;
}

This type of selector is declared using the tilde character (~). In this example, all paragraph elements (<p>) will be styled with the specified rules, but only if they are siblings of <h2> elements. There could be other elements in between the <h2> and <p>, and the styles would still apply.

Let’s apply the CSS from above to the following HTML:

<h2>Title</h2>
<p>Paragraph example.</p>
<p>Paragraph example.</p>
<p>Paragraph example.</p>
<div class="box">
  <p>Paragraph example.</p>
</div>

In this example, the styles will apply only to the first three paragraph elements. The last paragraph element is not a sibling of the <h2> element because it sits inside the <div> element.

Adjacent Sibling Combinator

A selector that uses the adjacent sibling combinator uses the plus symbol (+), and is almost the same as the general sibling selector. The difference is that the targeted element must be an immediate sibling, not just a general sibling. Let’s see what the CSS code for this looks like:

p + p {
   text-indent: 1.5em;
   margin-bottom: 0;
}

This example will apply the specified styles only to paragraph elements that immediately follow other paragraph elements. This means the first paragraph element on a page would not receive these styles. Also, if another element appeared between two paragraphs, the second paragraph of the two wouldn’t have the styles applied.

So, if we apply this selector to the following HTML:

<h2>Title</h2>
<p>Paragraph example.</p>
<p>Paragraph example.</p>
<p>Paragraph example.</p>

<div class="box">
  <p>Paragraph example.</p>
  <p>Paragraph example.</p>
</div>

…the styles will apply only to the second, third, and fifth paragraphs in this section of HTML.

Attribute Selector

The attribute selector targets elements based on the presence and/or value of HTML attributes, and is declared using square brackets:

input[type="text"] {
   background-color: #444;
   width: 200px;
}

There should not be a space before the opening square bracket unless you intend to use it along with a descendant combinator. The above CSS would match the following element:

<input type="text">

But it wouldn’t match this one:
                                                         <input type="submit">

The attribute selector can also be declared using just the attribute itself, with no value, like this:

input[type] {
   background-color: #444;
   width: 200px;
}

This will match all input elements with an attribute of type, regardless of the value.

You can also use attribute selectors without specifying anything outside the square brackets (thus targeting based on the attribute alone, irrespective of the element). It’s also worth noting that, when using values, you have the option to include quotes (single or double,) or not.

Pseudo-class

A pseudo-class uses a colon character to identify a pseudo-state that an element might be in—for example, the state of being hovered, or the state of being activated. Let’s look at a common example:

a:hover {
   color: red;
}

In this case, the pseudo-class portion of the selector is the: hover part. Here we’ve attached this pseudo-class to all anchor elements ( elements). This means that when the user hovers their mouse over an element, the color property for that element will change to red. This type of pseudo-class is a dynamic pseudo-class, because it occurs only in response to user interaction—in this case, the mouse moving over the targeted element.

It’s important to recognize that these types of selectors do not just select elements; they select elements that are in a particular state. For the purposes of this example, the state is the “hover” state.

Pseudo-element

Finally, CSS has a selector referred to as a pseudo-element and, used appropriately, it can be very useful. The only caveat is that this selector is quite different from the other examples we’ve considered. Let’s see a pseudo-element in context:

.container:before {
   content: "";
   display: block;
   width: 50px;
   height: 50px;
   background-color: #141414;
}

This example uses one kind of pseudo-element, the: before pseudo-element. As the name suggests, this selector inserts an imaginary element into the page, inside the targeted element, before its contents.


 Document Object Model

Introduction

The Document Object Model (DOM) is a programming API for HTML and XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated. In the DOM specification, the term "document" is used in the broad sense - increasingly, XML is being used as a way of representing many different kinds of information that may be stored in diverse systems, and much of this would traditionally be seen as data rather than as documents. Nevertheless, XML presents this data as documents, and the DOM may be used to manage this data.

With the Document Object Model, programmers can create and build documents, navigate their structure, and add, modify, or delete elements and content. Anything found in an HTML or XML document can be accessed, changed, deleted, or added using the Document Object Model, with a few exceptions - in particular, the DOM interfaces for the internal subset and external subset have not yet been specified.

As a W3C specification, one important objective for the Document Object Model is to provide a standard programming interface that can be used in a wide variety of environments and applications. The Document Object Model can be used with any programming language. In order to provide precise, language-independent specification of the Document Object Model interfaces, we have chosen to define the specifications in OMG IDL, as defined in the CORBA 2.2 specification. In addition to the OMG IDL specification, we provide language bindings for Java and ECMAScript (an industry-standard scripting language based on JavaScript and JScript). Note: OMG IDL is used only as a language-independent and implementation-neutral way to specify interfaces. Various other IDLs could have been used; the use of OMG IDL does not imply a requirement to use a specific object binding runtime. 

 Document Object Model is

The Document Object Model is a programming API for documents. The object model itself closely resembles the structure of the documents it models. For instance, consider this table, taken from an HTML document:

      <TABLE>
      <ROWS> 
      <TR> 
      <TD>Shady Grove</TD>
      <TD>Aeolian</TD> 
      </TR> 
      <TR>
      <TD>Over the River, Charlie</TD>
      <TD>Dorian</TD> 
      </TR> 
      </ROWS>
      </TABLE>
    
The Document Object Model represents this table like this: 

kk


In the Document Object Model, documents have a logical structure which is very much like a tree; to be more precise, it is like a "forest" or "grove" which can contain more than one tree. However, the Document Object Model does not specify that documents be implemented as a tree or a grove, nor does it specify how the relationships among objects are implemented in any way. In other words, the object model specifies the logical model for the programming interface, and this logical model may be implemented in any way that a particular implementation finds convenient. In this specification, we use the term structure model to describe the tree-like representation of a document; we specifically avoid terms like "tree" or "grove" in order to avoid implying a particular implementation. One important property of DOM structure models is structural isomorphism: if any two Document Object Model implementations are used to create a representation of the same document, they will create the same structure model, with precisely the same objects and relationships.

The name "Document Object Model" was chosen because it is an "object model" is used in the traditional object oriented design sense: documents are modeled using objects, and the model encompasses not only the structure of a document but also the behavior of a document and the objects of which it is composed. In other words, the nodes in the above diagram do not represent a data structure, they represent objects, which have functions and identity. As an object model, the Document Object Model identifies:

  • the interfaces and objects used to represent and manipulate a document
  • the semantics of these interfaces and objects - including both behavior and attributes
  • the relationships and collaborations among these interfaces and objects
The structure of SGML documents has traditionally been represented by an abstract data model, not by an object model. In an abstract data model, the model is centered around the data. In object oriented programming languages, the data itself is encapsulated in objects which hide the data, protecting it from direct external manipulation. The functions associated with these objects determine how the objects may be manipulated, and they are part of the object model.

The Document Object Model currently consists of two parts, DOM Core and DOM HTML. The DOM Core represents the functionality used for XML documents, and also serves as the basis for DOM HTML. All DOM implementations must support the interfaces listed as "fundamental" in the Core specification; in addition, XML implementations must support the interfaces listed as "extended" in the Core specification. The Level 1 DOM HTML specification defines additional functionality needed for HTML documents.

 Document Object Model is not

This section is designed to give a more precise understanding of the Document Object Model by distinguishing it from other systems that may seem to be like it.

Although the Document Object Model was strongly influenced by Dynamic HTML, in Level 1, it does not implement all of Dynamic HTML. In particular, events have not yet been defined. Level 1 is designed to lay a firm foundation for this kind of functionality by providing a robust, flexible model of the document itself.

The Document Object Model is not a binary specification. Document Object Model programs written in the same language will be source code compatible across platforms, but the Document Object Model does not define any form of binary interoperability.

The Document Object Model is not a way of persisting objects to XML or HTML. Instead of specifying how objects may be represented in XML, the Document Object Model specifies how XML and HTML documents are represented as objects, so that they may be used in object-oriented programs.

The Document Object Model is not a set of data structures, it is an object model that specifies interfaces. Although this document contains diagrams showing parent/child relationships, these are logical relationships defined by the programming interfaces, not representations of any particular internal data structures.

The Document Object Model does not define "the true inner semantics" of XML or HTML. The semantics of those languages are defined by the languages themselves. The Document Object Model is a programming model designed to respect these semantics. The Document Object Model does not have any ramifications for the way you write XML and HTML documents; any document that can be written in these languages can be represented in the Document Object Model.

The Document Object Model, despite its name, is not a competitor to the Component Object Model (COM). COM, like CORBA, is a language independent way to specify interfaces and objects; the Document Object Model is a set of interfaces and objects designed for managing HTML and XML documents. The DOM may be implemented using language-independent systems like COM or CORBA; it may also be implemented using language-specific bindings like the Java or ECMAScript bindings specified in this document.

 Document Object Model came from

The Document Object Model originated as a specification to allow JavaScript scripts and Java programs to be portable among web browsers. Dynamic HTML was the immediate ancestor of the Document Object Model, and it was originally thought of largely in terms of browsers. However, when the Document Object Model Working Group was formed, it was also joined by vendors in other domains, including HTML or XML editors and document repositories. Several of these vendors had worked with SGML before XML was developed; as a result, the Document Object Model has been influenced by SGML Groves and the HyTime standard. Some of these vendors had also developed their own object models for documents in order to provide programming APIs for SGML/XML editors or document repositories, and these object models have also influenced the Document Object Model. 

Entities and the DOM Core

In the fundamental DOM interfaces, there are no objects representing entities. Numeric character references and references to the pre-defined entities in HTML and XML are replaced by the single character that makes up the entity's replacement. For example, in:

<p>This is a dog &amp; a cat</p>

the "&amp;" will be replaced by the character "&", and the text in the <p> element will form a single continuous sequence of characters. The representation of general entities, both internal and external, are defined within the extended (XML) interfaces of the Level 1 specification. Note: When a DOM representation of a document is serialized as XML or HTML text, applications will need to check each character in text data to see if it needs to be escaped using a numeric or pre-defined entity. Failing to do so could result in invalid HTML or XML.

DOM Interfaces and DOM Implementations

The DOM specifies interfaces which may be used to manage XML or HTML documents. It is important to realize that these interfaces are an abstraction - much like "abstract base classes" in C++, they are a means of specifying a way to access and manipulate an application's internal representation of a document. In particular, interfaces do not imply a particular concrete implementation. Each DOM application is free to maintain documents in any convenient representation, as long as the interfaces shown in this specification are supported. Some DOM implementations will be existing programs that use the DOM interfaces to access software written long before the DOM specification existed. Therefore, the DOM is designed to avoid implementation dependencies; in particular,

  1. Attributes defined in the IDL do not imply concrete objects which must have specific data members - in the language bindings, they are translated to a pair of get()/set() functions, not to a data member. (Read-only functions have only a get() function in the language bindings).
  2. DOM applications may provide additional interfaces and objects not found in this specification and still be considered DOM compliant.
  3. Because we specify interfaces and not the actual objects that are to be created, the DOM can not know what constructors to call for implementation. In general, DOM users call the createXXX() methods on the Document class to create document structures, and DOM implementations create their own internal representations of these structures in their implementations of the createXXX() functions.

Limitations of Level One

The DOM Level 1 specification is intentionally limited to those methods needed to represent and manipulate document structure and content. Future Levels of the DOM specification will provide:

  • A structure model for the internal subset and the external subset.
  • Validation against a schema.
  • Control for rendering documents via stylesheets.
  • Access control.
  • Thread-safety.


DOM Manipulation with jQuery

jQuery makes available to the developer

There’s a series of fundamental components jQuery provides that we need to understand and be aware of to take advantage of if we intend on being proficient and highly effective with jQuery. These are:


  • DOM element selection based on CSS selectors
  • Events
  • Effects and animations
  • AJAX
  • JSON parsing
  • Extensibility through plug-ins
  • Utilities — i.e. feature detection
  • Compatibility methods, which are inherent in modern browsers, but fall short in the older browser (cough*IE9 and older*cough)
  • Multi-browser support


Alright, that’s quite a series of components that make jQuery something that CoffeeScript was able to abstract on (quite elegantly I might add), and other frameworks have strived to replicate. Let’s iterate through that list to further understand exactly what each function is about.

DOM element selection based on CSS selectors

If you’re reading this, I’m assuming you know what a CSS selector is. This can be an id, a class, or an attribute. Say you want to show a BootStrap alert when a button gets clicked. Your HTML looks something like:

<div id=“msg-id” class=“alert alert-success”>
    Hey, there! I’m a Bootstrap Alert
</div> 
<button id=“show-msg-id” class=“btn btn-primary”>
    Show Message
</button>

Easy enough, right? We have a simple div with the id of msg-id, and we have a button with the id of show-msg-id. For the sake of brevity, assume that our CSS file has a line like #msg-id { display: none; }. This ensures that our message isn’t just hanging out and being visible when we don’t want it to be. Now, to make this work how we want it to, let’s write up some jQuery.

$(“#show-msg-id”).bind(‘click’, function(e) { 
    setTimeout(function(){ 
        $(“#msg-id”).fadeIn(600, function(){ 
            setTimeout(function(){ 
                $("#msg-id").fadeOut(600); 
            }, 3500); 
        }); 
    },500); 
    e.preventDefault(); 
}

I know this looks like a lot of code, and it is, for what it does. Let’s go line by line. setTimeout() is a function which does exactly what its name insinuates — it takes two parameters, a function call and a duration in milliseconds. The function we’re calling doesn’t have a name, this is an abstract function which will run the code within the curly braces. Next, we call $(“#msg-id”).fadeIn(…). fadeIn() is another jQuery function which does as it says also (pretty nice, having these types of inherent functions, no?). It doesn’t require any arguments and default to 400 milliseconds for the duration when no arguments are passed to it. Here, we’re passing in 600 milliseconds, and another anonymous function. Inside this anonymous function, we’re calling setTimeout() again, and this time, we’re calling fadeOut(). This does the opposite of fadeIn() and we also set it to 600 milliseconds.

The reason we call setTimeout() within fadeIn() is because if we did not, and simply called fadeOut(), we wouldn’t be able to see the alert. We want this alert to be visible for a moment, think like the growl notifications on your Mac or the toast notifications on your Android. These have a series of pauses the developer-defined (in the case of Android, these times are constants, but that’s a whole other article). We let the alert stay visible for three and a half seconds before the anonymous function is fired which then fades out the alert. Coming down to the next line, we see 500, and that’s our timeout for how long we want to want after the button is clicked to begin the whole chain of events.

Another method of using CSS selectors is to grab a series of elements based off a CSS class. Say you have a series of inputs:

<form id=“form-id”> 
    <input type="text" id=“input_one-id” class="form-control required"> 
    <input type="text" id="input_two-id" class="form-control required"> 
    <input type="text" id="input_three-id" class="form-control required"> 
    <input type="text" id="input_four-id" class="form-control required"> 
</form>

Obviously, each has a different ID since HTML elements can only have unique IDs. This is even more important when manipulating the DOM since you’ll get unexpected results if you have multiple elements with the same id on the same page. To iterate over these with jQuery we can do something like:

$(“#form-id”).find(‘.required’).each(function() { 
    if($(this).val()) 
        console.log($(this).val()); 
    else 
        console.log(“#”+$(this).attr(‘id’)+” has no value”); 
}

What we’re doing here is referencing the DOM element with the id form-id, and within that element, we are searching for all the elements with the class of required. Then, since the DOM has an object with each of the referenced we can iterate over each element. For this example, we’re simply logging the value of each element to the console, and if there’s no value in that input we log that fact as well with the id so we can investigate further. This is a fundamental method of input validation, so it’s really important to keep this kind of function in mind.

This last bit of code showed another method of accessing DOM elements with CSS selectors as well. the call $(this).attr(‘id’) is using a jQuery function called attr(); short for attribute. This works for any common HTML attribute. If you have data- attributes, you can use .data(custom-attribute-name’) to retrieve its value. In addition, you can reference element based on their type, or search for attribute values with prefixes or suffixes. The possibilities are endless. Here are some examples:

$('input[type=“text”]’).val(); 
$(‘a[href*=“-suffix”]).val(); 
$('a[href^=“prefix-“]).val(); 
$(‘div.class’).data(custom-attribute-name’);

Events — clicks, focuses, keyups, and more

Our last line, and probably the most used line you will see in jQuery, is e.preventDefault(). You can see in the first line of our script our anonymous function takes an argument of e. This isn’t special, and in fact, is short for the event. bind() is an event handler, and the first argument it takes is what event do we want to bind to. Since we’re working with a button here, we want to bind to click. The problem is, browsers all have default functions they anticipate DOM elements to perform. Buttons trigger responses, links go places, and inputs receive input. By passing the event into our anonymous function, we can dictate exactly what we want to happen. In this case, we don’t want the button to perform its regular behavior (would reload the page or scroll to the top, and that’s not the UX we’re after.) Instead, we want it to do what we told it to do: fade in an alert and fade out the alert after set periods of time. e.preventDefault() ensures that’s all the button does — forget it, browser, we’re in control here.


bb


Another beautiful thing about events is we can trigger auto-completes, date pickers, calendar date selection windows, modal events, and more. For example, let’s take a look at jQuery’s date picker plug-in. This allows for a user to click on an input box, and select a date from a small window that pops up. The date can be formatted in any way you want and makes for a pleasant UX (though there are much better options for this, jQuery’s date picker suffices for 90% of use cases).

Our HTML looks something like:

<label class=“control-label” for="date">Date</label> 
<input type="text" id=“dateDisp" class="form-control"> 
<input type="hidden" name="date" id="date-id">
Simple enough. Never mind the classes if you aren’t familiar with Bootstrap, they’re classes that provide rapid ways of developing user interfaces. I highly recommend learning Bootstrap if you’re unfamiliar. Anyways, here’s the jQuery that makes the awesomeness happen:

$('#dateDisp').datepicker({ 
    showOn: 'focus', 
    altField: ‘’#date-id', 
    altFormat: 'yy-mm-dd', 
    dateFormat: 'mm/dd/yy', 
    maxDate: 0 
});

And that’s it. jQuery takes care of the rest. You end up with a beautiful box as seen below, and your user’s experience will be all the better for it. Read through the jQuery documentation for all the events you can respond to, as there are thousands of ways to interact with the DOM and create a unique experience for your users, makes your life easier for managing data flow, and generally improve the performance of any dynamic page.


Effects and animations — where’s the eye candy?

Now before you get too excited, let me remind you this isn’t 1999. No one wants to go to a site with glittering text, and shit flying all over the place. The era of flash animations and GIFs galore is over (ok, maybe GIFs are seeing a resurgence). Regardless of that last tidbit, animations put the dynamic on a dynamic website. While there are thousands of methods of accomplishing many of the effects jQuery offers by using CSS3 transforms, transitions and keyframes, jQuery enables you to achieve much of the same with sometimes fewer lines of code. We’ve touched on two of the built-in animation functions already in the first section of this article, and there are plenty more for you to take advantage of. I’m not going to go into too much depth on this portion as I don’t need you junior developers getting crazy, and pissing off your senior developers to the point they email me threats for showing you all the “totally rad animations” you decided to implement on your latest project. Find your way to the jQuery documentation and discover for yourself all the sweet shorthand this library offers.

11

AJAX — cooking with gas in jQuery

I was on Quora the other day and came across a question from someone wanting to make their blog more dynamic. They wanted the article links to change the blog content without refreshing the page. While they were insistent on not using any kind of server-side language or database to store their data, my first point of response was educating them on AJAX. What AJAX does for us is provide an efficient, asynchronous means of taking our client-side events and interfacing them to a back-end processor to do whatever we need it to. For the sake of brevity, I’m going to show you a simple contact form.

121


You have your form built like so:

<form id="form-id” class="form"> 
    <div class="row"> 
        <div class="col-sm-12"> 
            <input type="text" id="fname-id" name="fname" class="form-control" size="33" value="" placeholder="FIRST NAME" maxlength="25" /> 
        </div> 
    </div> 
    <div class="row"> 
        <div class="col-sm-12"> 
             <input type="text" id="lname-id" name="lname" class="form-control" size="33" value="" placeholder="LAST NAME" maxlength="25" /> 
        </div> 
    </div> 
    <div class="row"> 
         <div class="col-sm-12"> 
             <input type="text" id="email-id" name="email" class="form-control" size="33" value="" placeholder="EMAIL" maxlength="25" /> 
         </div> 
    </div> 
    <div class="row"> 
        <div class="col-sm-12"> 
            <input type="text" id="phone-id" name="phone" class="form-control" size="33" value="" placeholder="PHONE" maxlength="12" /> 
        </div> 
    </div> 
    <div class="row"> 
        <div class="row text-center btn-row"> 
            <h2>
                <a id="submit" class="btn-orange btn-xl">SUBMIT</a>
            </h2> 
         </div> 
     </div> 
</form>

Now, let’s collect these form values and send them off to some script so that we can build a contact list. Think of this as the foundation for a very minimal CRM.

$(document).ready(function() { 
  $(“#submit”).bind(‘click’, function(e) { 
    submit(); 
  }); 
}); 
function submit(){ 
  // gather all the valid info and store it for POST to PHP script 
  var formData = { 
    'firstName' : $(“#fname-id").val(), 
    'lastName' : $(“#lname-id").val(), 
    'email' : $("#email-id").val(), 
    'phone' : $("#phone-id").val() 
  }; 
  // AJAX POST 
  function $.ajax({ 
    type : 'POST', 
    url : 'scripts/script.php', 
    data : formData, 
    success : function(result){ 
      // log data to the console so we can see 
      // console.log("Result From Server:\n\n" + result); 
      result = parseInt(result); 
      switch(result){ 
        case 0: 
          $(‘#form-id’).empty().html("<p class='alert alert-danger center'>We were unable to process your request at this time. We apologize for the inconvenience. Please try again later.</p>");
          break; 
        case 1: 
          $(‘#form-id’).empty().html("<p class='alert alert-success center'>Thank you for your suggestions! We may be in touch shortly.</p>"); 
          break; 
        case 2: 
          $("#form-msg").fadeIn(300, function(){
            setTimeout(function(){ 
              $("#form-msg").fadeOut(300); 
            }, 4000); 
          }); 
          break; 
      } 
    }, 
    error : function(xhr, type, exception){ 
      // console.log("ajax error response type: ", type); 
      $('#form-id').empty().html("<p class='alert alert-danger'>We were unable to process your request at this time. We apologize for the inconvenience. Please try again later.</p>"); 
    } 
  }); 
}

There’s a lot that goes into AJAX, so I’m going to just give a very high-level review of what this script does. Something i haven’t touched on yet is $(document).ready(). This is another event we can act on and use. It fires whatever code is within its anonymous function as soon as the DOM is ready, or basically done loading all the resources. This means any bindings you need to do, or timers that need to start running, or whatever, need to be put in here. Anyways, we bind to the button at this point. Inside the button’s function, we call submit().

submit() starts by constructing a JavaScript object of the form values. Why do we do this, you ask? Because it’s easier to manipulate an object than pass in individual values when working with datasets. If you’re unfamiliar with arrays, I’ll write about them at a later date. Just know if you’re new to development, you’ll use arrays a lot so you better get comfortable with them. Moving forward you see this funny looking call: $ .ajax. No, this isn’t a made up method, this is the beauty of jQuery at its very essence. What the $. does is create a utility function: a function that does not act upon a jQuery object directly.

To construct an AJAX request of this nature, we need to specify a type. In this case, we specify it as POST as we’re sending data to the server. URL specifies what script to call, data passes our form values object in, and success is where we are able to start doing some interesting things.

We pass in a function with the argument result. the result is the response coming from our script on the backend (I hope you’re returning messages from your backend scripts). In this case, my PHP script returns some error codes, so we call parseInt() on the value contained in the result. Then we run the result through a switch statement and notify the user accordingly. At this point, you’ve seen most of these functions. empty() empties all the HTML from a DOM element, and HTML() insert HTML into a DOM element. Mind you, success does not necessarily mean everything was successful on the server, it simply means your request returned a 200 response. That’s why you need to do further validation on the backend of the input you’re sending (NEVER trust user input).

The final piece of our AJAX call is an error. This is fired when our request doesn’t go through, or in other words, the client receives a response other than 200 from the server. We handle this accordingly, and you can see I have commented out a console.log() used during debugging to determine what the specific failure was. Do study AJAX documentation thoroughly; it’s an indispensable function of the jQuery library and absolutely vital for dynamic websites. It also goes beyond what I’ve shown here and is capable of so much more.

JSON parsing — make data management easy

JSON is JavaScript Object Notation. In a nutshell, JSON is a hashed array of key, value pairs. Typically you’ll see something like this as a JSON response from a backend script:

{ id: 3, name: “Jane Smith”, age: “25”, city: “Portland”, state: “OR” }

When it comes to parsing JSON, we used to have to do this manually. Now we can call a fancy little method named parseJSON(). This breaks the object down into individual components which you then can reference from within your object. So, for instance, so we have a callback function that receives a JSON response. We need to populate a formerly populated form with this data. We could do something like:

function load(response) { 
  var r = $.parseJSON(response); 
  $(“#name-id”).val(r.name); 
  $(“#age-id”).val(r.age); 
  $(“#city-id”).val(r.city); 
  $(“#state-id”).val(r.state); 
  $(“#object-id”).val(r.id); 
}

It’s a simple and elegant solution to a problem that has plagued web developers for years and used to be much more clumsy with alternative formats (XML, CSV, TSV, etc.). Flex JSON whenever you can as you’ll be hard pressed to find a more efficient means of handling large datasets.

Extensibility — Through plug-ins, anything is possible

Long ago, when it came to using plugins, you had two options. Either you used libraries which were system level and part of the OS your program would function on, or you built modular code that could be repurposed across many projects. While you still do both, there are certain tasks every developer faces regularly, and frankly, needed to be standardized. Thanks to the mindset of open source, and jQuery being part of that ecosystem, we now have thousands of plug-ins available for a developer to rapidly deploy common functionality without having to craft their own methods. From validations, to form controls/events, and even some epic animations, if you need to something accomplished and don’t want to code it yourself (due to ambiguity or common nature) hit up the jQuery plugin registry to solve your woes.

We’ve already used one such plugin in this article when we illustrated the use of date picker. Now, we’re going to look at a quick file uploader using HTML5 and jQuery, which surprisingly, goes by the name of jquery-file-upload. This plugin makes easy work of file uploads without having an ugly UI, excessive code, or overly complex user experience for neither the developer nor the user. Below is the basic implementation of the uploader, less the server-side file handler. This code was pulled directory from the project’s page linked earlier in this paragraph.

<form id="fileupload" action="//jquery-file-upload.appspot.com/" method="POST" enctype="multipart/form-data"> 
  <noscript><input type="hidden" name="redirect" value="https://blueimp.github.io/jQuery-File-Upload/"></noscript> 
  <div class="row fileupload-buttonbar"> 
    <div class="col-lg-7"> 
      <span class="btn btn-success fileinput-button"> 
        <i class="glyphicon glyphicon-plus"></i> 
        <span>Add files...</span> 
        <input type="file" name="files[]" multiple> 
      </span> 
      <button type="submit" class="btn btn-primary start"> 
        <i class="glyphicon glyphicon-upload"></i> 
        <span>Start upload</span> 
      </button> 
      <button type="reset" class="btn btn-warning cancel"> 
        <i class="glyphicon glyphicon-ban-circle"></i> 
        <span>Cancel upload</span> 
      </button> 
      <button type="button" class="btn btn-danger delete"> 
        <i class="glyphicon glyphicon-trash"></i> 
        <span>Delete</span> 
      </button> 
      <input type="checkbox" class="toggle"> 
      <span class="fileupload-process"></span> 
    </div> 
    <div class="col-lg-5 fileupload-progress fade"> 
      <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100"> 
        <div class="progress-bar progress-bar-success" style="width:0%;"></div> 
      </div> 
      <div class="progress-extended">&nbsp;</div> 
    </div> 
  </div> 
  <table role="presentation" class="table table-striped">
    <tbody class="files"></tbody>
  </table> 
</form>
And now for the jQuery — so simple and elegant, there’s no reason not to love this plugin.

$(function () { 
  'use strict'; 
  $('#fileupload').fileupload({ 
    //xhrFields: {
      withCredentials: true
    }, 
    url: 'assets/plugins/jQuery-File-Upload/server/php/' 
  }); 
  $('#fileupload').fileupload( 
    'option', 
    'redirect', 
    window.location.href.replace( /\/[^\/]*$/, '/cors/result.html?%s' ) ); 
    if ($.support.cors) { 
      $.ajax({ 
        url: '//jquery-file-upload.appspot.com/', 
        type: 'HEAD' 
      }).fail(function () { 
        $('<div class="alert alert-danger"/>')
          .text('Upload server currently unavailable - ' + new Date())
          .appendTo('#fileupload'); 
      }); 
    } 
    else { 
      $('#fileupload').addClass('fileupload-processing'); 
      $.ajax({ 
        //xhrFields: {withCredentials: true}, 
        url: $('#fileupload').fileupload('option', 'url'), 
        dataType: 'json', 
        context: $('#fileupload')[0] }).always(function () { 
          $(this).removeClass('fileupload-processing');   
        }).done(function (result) { 
          $(this).fileupload('option', 'done')
          .call(this, null, {result: result}); 
        }); 
    } 
  });

So, the beauty of this plugin is you have to edit very little code and it is incredibly flexible. The maintainers have done well to provide users with a damn near a plug-and-play solution to a problem every web developer faces at some point, and common have to readdress. While I could discuss the pros and cons of the many solutions available for this problem, in particular, jQuery-File-Upload presents a great example of the power and flexibility of plugins within the jQuery ecosystem that you can and should take advantage of.

Feature detection

The whole reason there are so many frameworks and libraries in this world now is that of compatibility issues. Every developer has a phase where they believe they can solve all of the world’s problems by producing this new, exciting framework that functions across every device and browser…. until they realize that their quest is a futile effort. Look at Internet Explorer, for example. Since Microsoft decided the wise decision would be to incorporate that pile into the OS (seriously, who does that?!) we web developers have had a non-stop, pulling teeth, life sucks to be that guy type of battle. For a while, we had to write code specific to each browser, check the user agent on page load, and reference the appropriate resources. Then the major players (not IE) decided to listen to the W3C and adhere to standards. They worked out how a browser should behave across the board. The reason for this: yes, they’re in competition with each other, but the users suffer when developers can’t anticipate how a certain browser is going to interpret their code. Microsoft still hasn’t caught on to this in all their infinite wisdom about user experience.

Aside from my obvious strong distaste for that organization’s software, jQuery provides inherent functionality that handles most of what we need in terms of feature detection. There are methods available to handle a vast array of problems, including user agent detection and addressing the lack of certain required features. While jQuery is pretty damn good at this basic stuff, it’s still not a bad idea to incorporate a couple additional scripts into any website that relies heavily on not just jQuery, but JavaScript as a whole. Queue normalize.jz and Modernizr. Normalize.js takes JSON returned from APIs and ensures it fits an easy to parse format, which can become problematic for Redux or Flex applications where difficulties arise when parsing nested JSON. Modernizr helps ensure the code you write on your fully updated dev system will function on grandma’s Windows 2000 NT box running IE8 (ok, maybe not that far, but it’ll help with legacy browsers).

Overall the goal here is to offer a uniform user experience; something we’ve strived for decades to do and are barely getting on the right track to achieving it. Take a further look at the documentation to find out more about what other, convenient utilities are available in jQuery. Things such as isNumeric() or isArray(), hell, you can even grep() an array. Super cool methods that serve the specific purpose of making jQuery more versatile.

Compatibility methods — play nice with other frameworks and older browsers

While Modernizr provides various avenues of ensuring your beautiful jQuery will work on older browsers, enabling all the CSS3 and HTML5 magic to do its thing, sometimes you need more than jQuery. Sometimes, another framework has a particular function you’re rather fond of or handles an issue you’re working to overcome more elegantly than you yourself want to re-engineer in jQuery. So, you load up that script then low and behold, the console is full of error messages. You’ve got conflicts flying around like crazy, and your site just isn’t loading now.

This is where jQuery has yet another awesome feature. Using one of the many compatibility methods you are able to circumvent many of the issues that can come about when mixing frameworks and libraries together. Since jQuery and the majority of its tools are contained in the jQuery namespace, and most of the global objects are also stored in the jQuery namespace, you shouldn’t run into issues. The problem arises when another framework chooses to use $ as a shortcut too. jQuery by default uses this symbol as its shortcut (remember our $.ajax call, the $ is short for jQuery). To alleviate this issue jQuery has an awesome method that needs to be called immediately after jQuery is loaded on the page and before you use any jQuery.

var $j = jQuery.noConflict();

What we just did there is created our own shortcut. This will take care of any conflicts — the one issue being if you have already written extensive jQuery scripts, you’re going to have to go through all of them and replace $ with $j. BUT this takes care of that problem. On to the next.

Multi-browser support

Given the fact that the whole purpose of having a language like JavaScript is to make our pages more dynamic and responsive to user interaction, it’s mind-boggling that we still deal with certain browsers not adhering to the same rules so many others do. Not to mention there are still tons of legacy systems out there on the internet that may want to take advantage of your new app. Unfortunately, jQuery 2.x broke backward support for browsers older than IE9. While I personally don’t disagree with this move, it does pose a set of problems that you might want to consider depending on who you’re targeting. jQuery 1.x supports browsers as old as IE6, but you won’t get to take advantage of many of the bugs fixes that were implemented in the 2.x series, as well as various new methods that weren’t in the older versions.


7


Another aspect consider is this is yet another reason to make sure you’re doing feature checks on $(document).ready(). For instance, I typically run a check for IE/Mozilla/Chrome browsers. If the visiting user is on anything older than IE10, I display a message saying their browser may not be supported and they should consider upgrading to a modern browser, then give them a gentle nudge towards Chrome. This is typically not intrusive and doesn't impact their UX significantly, but I feel it's a stance that needs to be taken to ensure good usability and proper security hygiene for the less informed. Without taking off on a tangent, it is up to us to ensure our users are practicing proper security hygiene. They oftentimes aren't aware that old software is full of vulnerabilities, and while we don't have to educate them on CSRF, Remote File Inclusions, XSS, and a slew of other issues, they do need to at very least be reminded to update their software. Continuing.


jQuery Event Methods

 Events are,

All the different visitors' actions that a web page can respond to are called events.

An event represents a precise moment when something happens.

Examples:

  • moving a mouse over an element
  • selecting a radio button
  • clicking on an element
The term "fires/fired" is often used with events. Example: "The keypress event is fired, the moment you press a key".

Here are some common DOM events:


vv


jQuery Syntax For Event Methods

In jQuery, most DOM events have an equivalent jQuery method.

To assign a click event to all paragraphs on a page, you can do this:

$("p").click();

The next step is to define what should happen when the event fires. You must pass a function to the event:

$("p").click(function(){
  // action goes here!!
});

Commonly Used jQuery Event Methods

  • $(document).ready()

The $(document).ready() method allows us to execute a function when the document is fully loaded. This event is already explained in the jQuery Syntax chapter.

  • click()

The click() method attaches an event handler function to an HTML element.

The function is executed when the user clicks on the HTML element.

The following example says: When a click event fires on a <p> element; hide the current <p> element:

Example

$("p").click(function(){
  $(this).hide();
});

cc


  • dblclick()

The dblclick() method attaches an event handler function to an HTML element.

The function is executed when the user double-clicks on the HTML element:

Example

$("p").dblclick(function(){
  $(this).hide();
});


ccc


  • mouseenter()

The mouseenter() method attaches an event handler function to an HTML element.

The function is executed when the mouse pointer enters the HTML element:

Example

$("#p1").mouseenter(function(){
  alert("You entered p1!");
});

b


  • mouseleave()

The mouseleave() method attaches an event handler function to an HTML element.

The function is executed when the mouse pointer leaves the HTML element:

Example

$("#p1").mouseleave(function(){
  alert("Bye! You now leave p1!");
});

x


  • mousedown()

The mousedown() method attaches an event handler function to an HTML element.

The function is executed, when the left, middle or right mouse button is pressed down, while the mouse is over the HTML element:

Example

$("#p1").mousedown(function(){
  alert("Mouse down over p1!");
});

vb


  • mouseup()

The mouseup() method attaches an event handler function to an HTML element.

The function is executed, when the left, middle or right mouse button is released, while the mouse is over the HTML element:

Example

$("#p1").mouseup(function(){
  alert("Mouse up over p1!");
});


cv


  • hover()

The hover() method takes two functions and is a combination of the mouseenter() and mouseleave() methods.

The first function is executed when the mouse enters the HTML element, and the second function is executed when the mouse leaves the HTML element:

Example

$("#p1").hover(function(){
  alert("You entered p1!");
},
function(){
  alert("Bye! You now leave p1!");
});

xxx

  • focus()

The focus() method attaches an event handler function to an HTML form field.

The function is executed when the form field gets focus:

Example

$("input").focus(function(){
  $(this).css("background-color", "#cccccc");
});

lk


  • blur()

The blur() method attaches an event handler function to an HTML form field.

The function is executed when the form field loses focus:

Example

$("input").blur(function(){
  $(this).css("background-color", "#ffffff");
});

nn


  • The on() Method

The on() method attaches one or more event handlers for the selected elements.

Attach a click event to a <p> element:

Example

$("p").on("click", function(){
  $(this).hide();
});

aa


Attach multiple event handlers to a <p> element:

Example

$("p").on({
  mouseenter: function(){
    $(this).css("background-color", "lightgray");
  }, 
  mouseleave: function(){
    $(this).css("background-color", "lightblue");
  }, 
  click: function(){
    $(this).css("background-color", "yellow");
  } 
});

zx

jQuery Event Methods

Event methods trigger or attach a function to an event handler for the selected elements.

The following table lists all the jQuery methods used to handle events.


ss
sss
s4
as


Improve User Experience with jQuery


jQuery is a fast and concise library that simplifies how to traverse HTML documents, handle events, perform animations, and add AJAX.  As a web designer, knowing the ins & outs of jQuery was a prerequisite for my employment, however, much of what I know now was learned through years of hands-on experience.  If you don’t have that type of time frame to complete your project, I suggest you look into the myriad of jQuery plug-ins offered by open-source developers.

jQuery plug-ins offer a vast array of benefits to web designers of all levels of experience.  Those who are just beginning to fiddle with web design may find that plug-ins allow them to implement functionality in their web site that they don’t have the skill to code themselves.  To experienced web designers, the greatest benefit is time saved.  Solving simple issues of functionality with a plug-in allows them to sink all of their time into creating an improved user experience.

Another advantage of utilizing jQuery plug-ins is the built-in support for backward compatibility.  A plug-in that is backward compatible should display as it was intended to display, regardless of user preferences.  Without this compatibility, designers would need to spend long hours ensuring their jQuery works correctly for a multitude of browsers, browser versions, and user-specific options (ie. User has JavaScript disabled).  Using jQuery plug-ins makes this process much simpler and guarantees that your website will perform properly for the broadest audience possible.

Even with all of the options available to designers, finding the right plug-in can be difficult at times. Never spend more time searching for a plug-in than it would take for you to code it yourself.  If you aren’t capable of coding jQuery functionality from scratch, consider altering an existing plug-in to fit your needs.  Don’t just stick in a stock plug-in, make it yours. Make it look like it belongs.

Plug-ins can make a designer’s life much easier, but I would suggest that you not get too “plug-in happy” with your website.  Some plug-ins are bulky and can considerably hinder a page’s load time.  With page load speed being a factor that is now used to calculate your page rank in the search engines, optimizing for fast load times is more important than ever.

Lastly, only use plug-ins when they contribute to a better experience for the end user.  As with most things in life, simpler is almost always better.

As a web design and development shop, we tend to place importance on our ability to custom hand-code websites.  However, I am quite familiar with some of the jQuery plug-ins and would like to share with you a few of my favorites.

jQuery Cycle


The jQuery Cycle Plugin is a slideshow plugin that supports many different types of transition effects. It supports pause-on-hover, auto-stop, auto-fit, before/after callbacks, click triggers and much more.  It’s biggest plus side, in my opinion, is that it supports swapping of any number of different types of content, and not just images.

Lazy Load


Lazy Load is a great plugin if you are having trouble with loading a lot of images on your site.  By delaying the loading of images in long web pages until the user scrolls to them, Lazy Load can resolve many of the issues related to a large number of images including reducing server load.

IE-CSS3


IE CSS3 is probably one of my most used plug-ins. It essentially enables CSS3 selectors for older versions of Internet Explorer.

Plug-ins can be a great asset to your site and your personal library of code. But remember to be responsible when choosing plug-ins and only select those that add to your user’s experience.

New jQuery Techniques for a Better User Experience

Form Manipulations

Forms are always an integral part of a website. It is so common that you can find them on almost every blog. This makes it essential for developers to focus on forms and refine them for the best user experience possible.

  •  jQuery Login Form

As a web developer, you can either use a plugin or build a sliding panel from scratch. Check out the tutorial by Jake Rocheleau to learn more about how to create sliding elements within the login form.


  •  Hide Some Useful Info With Spoiler Revealer

You can improve how users reveal information thanks to the spoiler revealer technique. You can find a tutorial on the subject here. It is elegant and provides a sense of exploration for the end user.


  • Form Submission Without Page Refresh

When a form is submitted, the page refreshes in order to send the info to the server. However, you can make it look swift by using jQuery to do form submissions without a page refresh. CodeTuts has a clear tutorial on the topic.

Navigation Menus

Navigations also plays a crucial role in the user experience. They dictated how a user navigates through the website and a good navigation menu determines how the user feels about the website.


  •  jQuery Plugin for Smooth Navigation

You can use a lot of jQuery plugins to ensure smooth navigation. There are many plugins out there and that’s why we recommend reading the list of 20 jQuery plugins which will let you improve the user experience. If you fancy not using a plugin, you can also check out the tutorials on how to create different types of menus using jQuery. The choice of which navigation menu technique depends on you.

You can also create simple jQuery tabs which can come handy during navigation. The tabs should be responsive and offer smooth navigation. You can follow the detailed tutorial on Web Designer Hut to learn more.

Content Manipulation

You can also manipulate content using jQuery. By doing so, you can customize the content according to your choice and customize it for the best user experience possible.


  •  Text Size Slider

User experience is also about providing users an option to change things which, in return, gives them more control. This is why you may want to give your readers the ability to change the text size slider. You can implement it either by using a plugin or by manually coding it.

Tutorial: https://www.script-tutorials.com/text-animation-jquery-ui-slider/

Plugin: https://www.jqueryscript.net/tags.php?/font%20size/


  •  jQuery Pagination

Pagination provides the necessary pages to the website and it helps readers to easily digest the content better.

Plugins: https://jqueryhouse.com/jquery-pagination-plugins/

Tutorial: https://codepen.io/SitePoint/pen/WprNwa


  •  Content Slider

With a content slider, you can manipulate content in a cool format. Want to slow down the slider or change how the slider animates? If you do, you can customize the slider with jQuery. You can also create a fully custom slider if you want.

You can create a simple content slider with the help of CSS3 and jQuery. Moreover, you can use check out the content slider plugins available online.

Animation Effects

Animations also play a crucial role in improving user experience. There are tons of jQuery animation libraries that you can utilize to make the website pop, not only in terms of looks but also user experience.


  •  Smooth Content Scrolling

Adding small bits of customization to scrolling can add value to your website. Make scrolling not only fun but a seamless experience. You can also opt to put all the posts on a single page and offer unlimited scrolling. Many websites do that, including the Forbes website. The flow is what you need. Scrolling can also open interactivity options that might be missing from the vanilla website.

You can use plugins to achieve the desired result. There are many different types of animations and functionalities that you can achieve with these plugins. Check out the comprehensive article by CSSAuthor on the jQuery scrolling plugin which contains 75+ plugins. You can also check out a detailed tutorial on them and get a better understanding of implementing custom jQuery scrolling.


  • jQuery Fading Menu

You can also improve the menu by adding fading animation to it. This animation will make the menu react to user input, thus improving interactivity and user experience. It will also entice visitors to click and reduce bounce rate.

Image Manipulation

If you are running an image-heavy website, you may want to add image manipulation features to it. Clearly, there are plenty of ways you can add functionality.


  •  Image Cropping and Zoom

Our last jQuery technique that can further improve user experience is image cropping and zoom. You can use Cropper, a jQuery image cropping plugin to add functionality to the website. You can also use jQuery zoom by Jack Moore to get the desired results.

Resources & Links



  • JavaScript For Cats
  • A Re-introduction to JavaScript via Mozilla Developer Network 
  • 30 Days to Learn jQuery via Tuts+ Premium 
  • Google Hosted Libraries 
  • jQuery Documentation 
  • jQuery Fundamentals via Bocoup
  •  jQuery UI

j

Share:

0 comments