Abandon jquery and dive into native JavaScript

Source: Internet
Author: User
Tags event listener

Although I have been doing web site construction for more than 10 years, I've only been learning more about how to use pure JavaScript for work in the last 3 years, rather than always thinking about jquery in the first place. Now I study a lot of things every day. This process makes me think that the adtile JavaScript SDK is more like creating an open source project than "concrete work", and I have to say I like that.

Today, I'm going to share some of the basics I've learned over the past few years with you, which will probably help you get into the world of pure JavaScript, making it easier for you to make a decision about whether you need it in your next project--jquery.

Progressive enhancement

While libraries like jquery can help solve the problem of incompatibility between many browsers, you can really become familiar with them once you start using pure JavaScript to do all the work. To avoid writing JavaScript code that contains browser modifications and only resolves browser-compatible issues, I recommend using feature detection to develop a step-up experience that only uses a more modern browser as a target. This does not mean that there is nothing to be gained from a browser like IE7, which can only mean that they get a more basic experience when JavaScript is not enhanced.

How did we do that?

We have a separate JavaScript section called "Feature.js", which has all the functional tests. The real test list is much longer than that, but let's get back to the problem later. To eliminate the incompatibility of some old browsers, we use the following two tests:

var feature = {  AddEventListener:!! Window.addeventlistener,  queryselectorall:!! Document.queryselectorall,};

Then, in the main application section, we detect whether these features can be supported by simple "if" statements in the following example. If it is not supported, then the browser will not execute any of the following code:

if (Feature.addeventlistener && feature.queryselectorall) {  this.init ();}

These two tests ensure that we have a local method (Queryselectorall) available when using CSS selectors in JavaScript, an easy way to add and remove events (AddEventListener), and that the browser standard support is better than IE8. Read more about this method in the "cutting the mustard" Article of the BBC blog.

Browser support

Here's one of the browsers we're testing to support this feature, and to keep a rough list of JavaScript running in the future:

    • ie9+
    • Firefox 3.5+
    • Opera +
    • Safari 4+
    • Chrome 1+
    • IPhone and IPad ios1+
    • Android Phone and tablets 2.1+
    • Blackberry os6+
    • Windows 7.5+
    • Mobile Firefox
    • Opera Mobile
The basic native JavaScript approach lets us begin to focus on how the most basic and frequently needed features work in pure JavaScript compared to jquery. For each example, I intend to provide two methods of jquery and pure JavaScript.

Document Ready Event

In jquery, many of you may have used document.ready like this in the past:

$ (document). Ready (function () {  //Code});

But you know, you can put all the javascript on the bottom of the page, but are they really the same thing? JavaScript also has a listener for DOM content-loading events, rather than using jquery's Document.ready:

Document.addeventlistener ("domcontentloaded", function () {  //Code}, False);
Selector API

JavaScript's native selector API is excellent. It is useful for CSS selectors and is very similar to what jquery provides. If you used to write like this in jquery:

var element = $ ("div");

Now you can use the following statement instead:

var element = Document.queryselector ("div");

or select some internal containers for all Div:

var elements = Document.queryselectorall (". Container div");

You can also query for a specific element to find its child elements:

var navigation = document.queryselector ("nav"); var links = Navigation.queryselectorall ("a");

It's simple, easy to understand and doesn't need much code right now, is it? Further, we can even build a small JavaScript library of our own to make a simple DOM query. Here are some things Andrew Lunny has come up with:

This gives us simple dollar function and event Bindingvar $ = document.querySelectorAll.bind (document); Element.prototype.on = element.prototype.addeventlistener;//This is the How to use it$ (". Element") [0].on ("Touchstart", Handletouch, false);
Traversing the DOM

Traversing the DOM with pure JavaScript is a bit more difficult than jquery. But it's not too difficult. Here are some simple examples:

Getting the parent Nodevar parent = document.queryselector ("div"). parentnode;
Getting the next Nodevar next = Document.queryselector ("div"). nextSibling;
Getting the previous Nodevar next = Document.queryselector ("div"). previoussibling;
Getting The first child elementvar child = Document.queryselector ("div"). Children[0];
Getting the last Childvar = Document.queryselector ("div"). Lastelementchild;
Add and remove style names (class name)

Using jquery, it's easy to add, remove, and check whether an element has a deterministic class. Using pure JavaScript can be complicated, but not too complicated. Give the element a class called "Foo" and replace all the current classes:

Select an Elementvar element = Document.queryselector (". Some-class");
Give class "Foo" to the Elementelement.classname = "Foo";

Add a class without replacing the current class:

Element.classname + = "Foo";

Remove the "No-js" class from the HTML element and replace it with "JS":

It's pretty simple, isn't it? Next, removing only some classes is a little bit more complicated. I've been using this little helper function, called Util.js, in a separate section. It has two parameters: the element and the class you want to remove:

Removeclass, takes, Params:element and Classnamefunction removeclass (el, CLS) {  var reg = new RegExp ("(\\s|^)" + CLS + "(\\s|$)");  El.classname = El.className.replace (Reg, ""). Replace (/(^\s*) | ( \s*$)/g, "");}

Then, in the main application section, I've been using it like this:

Removeclass (element, "foo");

If you also want to examine an element for some classes, like jquery's hasclass. You may need to add this code to your Utils tool:

Hasclass, takes, Params:element and Classnamefunction hasclass (el, CLS) {  return el.classname && new Re Gexp ("(\\s|^)" + CLS + "(\\s|$)"). Test (El.classname);

You can then use this:

Check If an element has class ' Foo ' if (hasclass (element, "foo")) {  //Show an alert message if it does  alert ("E Lement has the class! ");}
HTML5 's Classlist API introduction

If you only need to support a more modern browser like Ie10+,chrome,firefox,opera and Safari, you can start using HTML5 's classlist feature, which makes adding and deleting classes easier.

This is what I ended up doing in our latest developer documentation, and with the development of features, it's more of a UI enhancement, and if that's not the case, it's actually not something that can break the experience.

With the following simple "if" statement, you can detect if the browser supports this feature:

if ("Classlist" in document.documentelement) {  //classlist are supported, now does something with it}

Use Classlist to add, delete, and convert classes:

Adding a Classelement.classList.add ("bar");
Removing a classelement.classList.remove ("foo");
Checking if has a classelement.classList.contains ("foo");
Toggle a classelement.classList.toggle ("active");

Another benefit of using classlist is that it behaves better than using the original class Name property. If you have elements like this:

<div id= "test" class= "one three" ></div>

Which one do you want to operate:

var element = Document.queryselector ("#test"), addclass (element, "n"), Removeclass (element, "four");

These methods that are read and written by the class name attribute will trigger a browser redraw. But this is not the case if we should use the appropriate Classlist method:

var element = Document.queryselector ("#test"), Element.classList.add ("a"), Element.classList.remove ("four");

With Classlist, the most basic class name attribute is changed only when necessary. When adding a class that already exists and removing a nonexistent class, the class name attribute is not involved at all, which means that we have just avoided redrawing two times.

Event listeners adding and removing an element of an event listener is just as easy in both pure JavaScript and jquery. When you have to add multiple event listeners, things get a little complicated, but I'll explain them to you in detail. In the simplest case, when you click on an element, a warning message pops up, as described in the following code:

Element.addeventlistener ("click", Function () {  alert ("You clicked");}, False);

In order for all elements of the page to implement this function, we must repeat each element in turn and add an event listener to them:

Select all Linksvar links = Document.queryselectorall ("a");//For each link element[].foreach.call (links, function (EL) {  //ADD Event listener  el.addeventlistener ("click", Function (event) {    event.preventdefault ();    Alert ("You clicked");  }, False);});

One of the greatest features of JavaScript for event listeners is that "AddEventListener" can carry an object as a second parameter, which will let it automatically look for a method called "Handleevent" and then invoke it. Ryan Seddon has thoroughly introduced this approach in its article, so I'm just going to give you one of the simplest examples of what you can learn from its blog:

var object = {  init:function () {    Button.addeventlistener ("Click", this, false);    Button.addeventlistener ("Touchstart", this, false);  },  handleevent:function (e) {    switch (e.type) { Case      "click":        this.action ();        break;      Case "Touchstart":        this.action ();        break;    }  ,  action:function () {    alert ("Clicked or touched!");  }};/ /Initobject.init ();
Manipulating the DOM

Manipulating the DOM with pure JavaScript just starts to sound like a scary idea, but it's not much more complicated than using jquery. Below, we will have an example of selecting the elements of the DOM, cloning it, manipulating the cloned style with JavaScript, and substituting the manipulated object for the original element.

Select an Elementvar element = Document.queryselector (". Class");//clone Itvar clone = Element.clonenode (TRUE);//Do Me manipulation off the DOMclone.style.background = "#000";//replaces the original element with the new cloned oneelement . Parentnode.replacechild (clone, Element);

In the DOM, if you don't want to replace anything in addition to the new Div created in <body>, then you can do this:

Document.body.appendChild (clone);

If you think you want to learn more about the different DOM methods, I suggest you read the DOM Core tables of Peter-paul Koch.

Further in-depth

Here I would like to share two more advanced technologies that I have discovered recently. These are the features we need to create adtile, so you'll find them useful as well.

Determine the maximum width of the response picture in JS

This is one of my favorites, and this is useful if you need to manipulate a fluid picture with JavaScript. Because the browser returns the currently resized image by default, we have to think of some other way. Fortunately, modern browsers now have a solution:

var maxWidth = img.naturalwidth;

This will give us a picture of a maximum width of 100% pixels, and both Ie9,chrome,firefox,safari and opera support this approach. We can also keep this feature and then add the old browser support by loading the image into memory:

Get image ' s max-width:100%; In Pixelsfunction getmaxwidth (img) {  var maxWidth;  Check if Naturalwidth is supported  if (img.naturalwidth!== undefined) {    maxWidth = img.naturalwidth;  Not supported, use In-memory solution as fallback  } else {    var image = new Image ();    IMAGE.SRC = IMG.SRC;    MaxWidth = image.width;  }  Return the max-width  return maxWidth;}

You should notice that the picture must be fully loaded before checking the width. This is the method we have been using to determine their size:

function Hasdimensions (img) {  return!! ((Img.complete && typeof img.naturalwidth!== "undefined") | | img.width);}
Determines whether an element is in the view window by using the Getboundingclientrect method, you can get the position of any element in the page. Here's a simple function to show how simple and powerful it is. This function has a parameter, which is the element you want to check. When the element is visible, the function returns true:

Determine if an element was in the visible viewportfunction Isinviewport (Element) {  var rect = ELEMENT.GETBOUNDINGCL Ientrect ();  var html = document.documentelement;  Return (    rect.top >= 0 &&    rect.left >= 0 &&    rect.bottom <= (window.innerheight | | ht Ml.clientheight) &&    rect.right <= (window.innerwidth | | html.clientwidth)  );}

The above function can be used when adding a "scrolling" event listener to the form and then calling the Isinviewport () method.

Conclusion

The use of jquery in your next project is largely dependent on the project you built. If your project requires a lot of front-end code, then you should use jquery. However, when you build a JavaScript plugin or library, you should only consider pure JavaScript. Using pure JavaScript means fewer requests and less data loading. This also means that you don't have to force developers to add jquery to their projects.

Original address: Blog.adtile.me

Abandon jquery and dive into native JavaScript

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.