how to shift from JavaScript to jQuery - javascript

jQuery is a framework of javaScript. But, I very well able to code in javaScript. I am not getting how do I (re)code it in jQuery !
Is learning jQuery from beginning is only way or should I follow any other way ?
EDIT : is jQuery used only for AJAX ? or where can I find proper to use jQuery ?

You have to learn jQuery in order to use it, yes.
(You don't, however, use jQuery instead of JavaScript. You might use it instead of directly using DOM, XHR and so on, but it is JavaScript)

jQuery is JavaScript. It's just another tool. Its big benefit is that you can manipulate the DOM and perform AJAX requests much easier.
For example, to get all links by class name in JavaScript (using this function) is:
function getElementsByClassName(className, tag, elm){
var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
var tag = tag || "*";
var elm = elm || document;
var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
var returnElements = [];
var current;
var length = elements.length;
for(var i=0; i<length; i++){
current = elements[i];
if(testClass.test(current.className)){
returnElements.push(current);
}
}
return returnElements;
}
var elements = getElementsByClassName(document,'a','myclass');
The same using jQuery*:
var elements = $("a.myclass");
Of course, jQuery would do similar things behind the scenes but the point is that you don't need to know about it (and more importantly, don't need to rewrite it all). There are lots of people coming up with clever things for jQuery (and tests, so you know it works cross browser).
Use jsFiddle to quickly play with some examples in jQuery (look at the jQuery docs). Don't necessarily set out to rewrite your entire JavaScript using jQuery. Just start using it for DOM operations/AJAX requests (even something as simple as using the show or hide methods). Eventually you'll get used to using jQuery and eye up your older code to rewrite. Just to give you an example, I once rewrote a 200-300 line piece of JavaScript into about 20 lines with jQuery. The reason for the massive difference is because I was able to remove all the 'helper' functions (like getElementsByClassName one above) since jQuery handles that for me.
Good luck :)
* The pedantic among you will know it's not entirely the same, since it returns the jQuery object - but this can really be ignored because it'll do the same result.

Rewriting existing javascript code to take advantage of the jQuery framework will require you knowledge of jQuery. There's no other way. In fact there is: you could hire someone doing the job for you but I don't think this was your original question.

There's no easy answer on that question. Learn the fundamentals of jQuery then rewrite your code from scratch.
As with all new languages/concepts start small and then get bolder..
But from someone who did the transition, I can say that the effort was worth it!
Enjoy learning jQuery!

My advice is don't go for recoding the entire javascript at first time.
First take a small parts in a javascript for show and hide the div or table or any other elements.Then you will do it by using Jquery.After getting success on this you will get some confidence.
Then go for ajax using Jquery.
By this way you can learning the Jquery and step by step you changed your javascript to jquery.
Hope this will help you.

I'm quite surprised this hasn't been mentioned before now. But one of the absolutely best sources for beginners is the well written and open sourced book jQuery Fundamentals by Rebecca Murphey.
It will walk you through the basics of both JavaScript and jQuery, and will hopefully be the only thing (together with the docs) you'll need to get you going with jQuery!
I also recommend this for more advanced users because it will help you break free of bad practices that you might have picked up from, I'm sad to say it, badly written tutorials or books.
Happy reading!

jQuery isnt very different. It just combines some of the best features of javascript and uses CSS selectors to give you a easy to use language. Where most of the typical lines of code can be converted into smaller jQuery statements just start following a few examples and u will by default start moving to learning jQuery more.

Related

Do jQuery or raw JavaScript precompile or cache variable expressions or selectors?

Pretty basic question.
I want to know if jQuery or raw JavaScript are smart enough to precompile, or cache variable expressions in functions, or selectors, and if not, are there any reasons that would stop them doing this?
e.g.
$('#whatever').on('click', function(){
$('#template').click();
});
var n = 0;
for(var i = 0; i < 20; i++){
n = 1 + 1;
$('#whatever').click();
}
console.log(n);
Are we going to search the dom 20 times for the $('#template') element? or are the library/engine smart enough to store a pointer?
And, are we going to computer 1+1 2 times, or is that expression cached or precompiled?
Obviously these are really dumb examples, but they get the point across.
Yes, no one is going to have the line (hopefully) n = 1 + 1 in their code.
And we could change the code to have `var template = $('#template'); before the click handler if it doesn't deal with it itself, but I am wondering do we/ why we have to do that?
First off, jQuery is javascript. jQuery does not and cannot add features to JavaScript as a language.
With that being said, JavaScript is ECMAScript, and also implemented differently in every browser. It would be very difficult (if not impossible) for me to tell you anything about what level of caching a JavaScript implementation has, because as a language, there isn't any prescribed behavior.
I think it would make sense to cache references to DOM elements for performance reasons, but I cannot speak to what each separate implementation does behind the scenes.
As far as jQuery is concerned, there is no magical selector caching happening in the current version as far as I'm aware. Every time $(...) is called, it has to re-evaluate the selector. The selector could be a simple css-style selector, e.x. $('#foo .bar baz'), or it could be an element fragment, e.x. $('<div>foo bar baz</div>').
If the jQuery function is passed a selector, it would have to re-check the DOM because new elements may have been added that could match the selector, or existing elements may have changed to no longer match the selector.
As far as caching jQuery objects goes, it is common to save a reference to a jQuery object, and in some circumstances is more performant. The only way to know for sure which method is better is to run the script with a performance analyzer and see where the bottlenecks are. There's no reason to just assume that writing your code in one particular way will improve the performance of your code.
If you're just trying to perform a series of operations on the same selection, be sure to take advantage of jQuery's method chaining:
$('.selector').addClass('foo').removeClass('bar').click(function () {...});
jQuery methods typically return the original selection as a return value, which allows for a very elegant simplification of code.

Dom Language Javascript?

I am new to javascript and jQuery.
i just want to know that is there any way create something different ,say structured dom language ?
in jQuery to select all div
var divs = $("div");
i want to know the possibility of something like this
var SDL = new SDL();
var div = SDL.query("select div from document"); //or something like that ..
or to select a div with ID
var div = SDL.query("select div from document where id='divID'");
looking mad right ?
i am sure i will not care about the downvotes for the question , but i need to know why this is not good ? or why its is not posible ?
Please say something on this ...
Thank you.
It's not good because it's pointless to implement or use. It would make the jQuery library much larger than it needs to be, and CSS selectors are clear enough anyway, as well as being far more concise.
It is possible, but what you're describing is actually pretty close to CSS selectors, but with a couple of extraneous words thrown in with some formatting changes.
In your "SDL" selector, it would simply be replaced by:
div#id
Why go through the trouble of writing a whole sentence to do the same thing? There may be a third party SQL-like selector library, in the same way Sizzle is a CSS selector library, however I've never heard or seen of one personally.
An SDL would also be much slower than using CSS-based selectors, as the string is more complex and has more garbage in it than a CSS selector string. More importantly, however, you wouldn't get the native speedups that querySelectorAll() et al give when used natively.

Tool to translate old javascript into jQuery

I know there are lots of tools on the net that can make our lives easier, for us, developers, including some that are quite powerful.
I ask if you know a tool to translate old javascript into jQuery?
A tool that can help make this stuff ? Because I have to translate thousands of lines of code in jQuery, and I think I have about 15 years... :)
Thanks !
No, such a tool doesn't exist. If it existed the code created by it wouldn't be something anyone wanted to work with.
The best way to start using jQuery is simply using jQuery for new stuff and if there's time slowly migrating old stuff manually - preferably stuff that's broken or needs modifications anyway.
The question doesn't make sense. jQuery is not a language that you can translate into. jQuery is a library that you can use in your Javascript code if you want. There is nothing jQuery can do that can't be done without it.
What you probably want is a tool to help you refactor your Javascript code, replacing specific patterns with equivalent jQuery methods. The problem is that this would produce a mess.
E.g. the jQuery equivalent to:
var x = document.getElementById('foo');
is:
var x = $('#foo');
but now x is a jQuery object, not a DOM object, so the code that uses it will break.
You could do:
var x = $('#foo')[0];
which would give you a DOM object, but then you are wasting jQuery.
One solution is to replace the code with:
var $x = $('#foo');
var x = $x[0];
Then stick to the convention that $var is the jQuery wrapped version of var. As refactoring progresses, you can use a tool that tells you 'x' is unused (like jsLint) to know that it's safe to remove it.
Various IDEs have tools to refactor Javascript a bit. See this question for some: How do you refactor JavaScript, HTML, CSS, etc?

Javascript stylistics - Professional looking code

I keep reading JS books that contain stuff like:
function onSuccess(entries) {
document.getElementById("loading").innerHTML="";
var ul = document.getElementById("file-listing");
for(var index=0;index<entries.length;index++) {
var li = document.createElement('li');
li.innerHTML = entries[index].name;
ul.appendChild(li);
}
}
However, I read on multiple sites that it's faster and cleaner to create the whole list in a html = "", add the ul and li elements and then add the block, append it all in one call... so I am wondering if I should follow the style that I find in many js books or what I read on performance blogs? I am mostly concerned that people reading my code will find it amateurish, if I use the previous code block. Also I have meet a few people that are like, wow all you use is jQuery... instead of using DOM calls like document.getElementById(), etc...
However, I read on multiple sites that it's faster and cleaner to create the whole list in a html = ""...
If you mean, someElement.innerHTML = "HTML tags here"; then yes, it's faster in most cases, because fundamentally parsing and rendering HTML is what browsers do and so they're very fast at it, whereas if you build things up with DOM calls, there are lots of trips across various layers (JavaScript, DOM, browser internals) each time.
But: It also doesn't matter, in most cases. It can matter if you're rendering a 2,000-row table with lots of columns; but if you're not doing that it mostly doesn't matter. You can optimize if and when you see a problem.
so I am wondering if I should follow the style that I find in many js books or what I read on performance blogs?
You should do whatever seems cleanest, clearest, and easiest to you.
I am mostly concerned that people reading my code will find it amateurish, if I use the previous code block.
That's their problem. :-)
Also I have meet a few people that are like, wow all you use is jQuery... instead of using DOM calls like document.getElementById(), etc...
There's nothing wrong with using jQuery for all or nearly all of your DOM manipulations; it's really good at it, and saves you a lot of time and trouble. You should be familiar with the DOM so you can use it when it's appropriate (jQuery doesn't do everything; in particular it's not good at dealing with text nodes), but that doesn't mean you shouldn't use jQuery when and where appropriate.
Toward that end, some reading:
DOM2 Core
DOM2 HTML
DOM3 Core
HTML5 Web Application APIs
...but again, that doesn't mean you should use it just because someone looks down on using jQuery. Use tools appropriately. The important thing is understanding the tools you're using (including jQuery, and also the DOM itself), so you can understand when and where to apply them.

When to use Vanilla JavaScript vs. jQuery?

I have noticed while monitoring/attempting to answer common jQuery questions, that there are certain practices using javascript, instead of jQuery, that actually enable you to write less and do ... well the same amount. And may also yield performance benefits.
A specific example
$(this) vs this
Inside a click event referencing the clicked objects id
jQuery
$(this).attr("id");
Javascript
this.id;
Are there any other common practices like this? Where certain Javascript operations could be accomplished easier, without bringing jQuery into the mix. Or is this a rare case? (of a jQuery "shortcut" actually requiring more code)
EDIT : While I appreciate the answers regarding jQuery vs. plain javascript performance, I am actually looking for much more quantitative answers. While using jQuery, instances where one would actually be better off (readability/compactness) to use plain javascript instead of using $(). In addition to the example I gave in my original question.
this.id (as you know)
this.value (on most input types. only issues I know are IE when a <select> doesn't have value properties set on its <option> elements, or radio inputs in Safari.)
this.className to get or set an entire "class" property
this.selectedIndex against a <select> to get the selected index
this.options against a <select> to get a list of <option> elements
this.text against an <option> to get its text content
this.rows against a <table> to get a collection of <tr> elements
this.cells against a <tr> to get its cells (td & th)
this.parentNode to get a direct parent
this.checked to get the checked state of a checkbox Thanks #Tim Down
this.selected to get the selected state of an option Thanks #Tim Down
this.disabled to get the disabled state of an input Thanks #Tim Down
this.readOnly to get the readOnly state of an input Thanks #Tim Down
this.href against an <a> element to get its href
this.hostname against an <a> element to get the domain of its href
this.pathname against an <a> element to get the path of its href
this.search against an <a> element to get the querystring of its href
this.src against an element where it is valid to have a src
...I think you get the idea.
There will be times when performance is crucial. Like if you're performing something in a loop many times over, you may want to ditch jQuery.
In general you can replace:
$(el).attr('someName');
with:
Above was poorly worded. getAttribute is not a replacement, but it does retrieve the value of an attribute sent from the server, and its corresponding setAttribute will set it. Necessary in some cases.
The sentences below sort of covered it. See this answer for a better treatment.
el.getAttribute('someName');
...in order to access an attribute directly. Note that attributes are not the same as properties (though they mirror each other sometimes). Of course there's setAttribute too.
Say you had a situation where received a page where you need to unwrap all tags of a certain type. It is short and easy with jQuery:
$('span').unwrap(); // unwrap all span elements
But if there are many, you may want to do a little native DOM API:
var spans = document.getElementsByTagName('span');
while( spans[0] ) {
var parent = spans[0].parentNode;
while( spans[0].firstChild ) {
parent.insertBefore( spans[0].firstChild, spans[0]);
}
parent.removeChild( spans[0] );
}
This code is pretty short, it performs better than the jQuery version, and can easily be made into a reusable function in your personal library.
It may seem like I have an infinite loop with the outer while because of while(spans[0]), but because we're dealing with a "live list" it gets updated when we do the parent.removeChild(span[0]);. This is a pretty nifty feature that we miss out on when working with an Array (or Array-like object) instead.
The correct answer is that you'll always take a performance penalty when using jQuery instead of 'plain old' native JavaScript. That's because jQuery is a JavaScript Library. It is not some fancy new version of JavaScript.
The reason that jQuery is powerful is that it makes some things which are overly tedious in a cross-browser situation (AJAX is one of the best examples) and smooths over the inconsistencies between the myriad of available browsers and provides a consistent API. It also easily facilitates concepts like chaining, implied iteration, etc, to simplify working on groups of elements together.
Learning jQuery is no substitute for learning JavaScript. You should have a firm basis in the latter so that you fully appreciate what knowing the former is making easier for you.
-- Edited to encompass comments --
As the comments are quick to point out (and I agree with 100%) the statements above refer to benchmarking code. A 'native' JavaScript solution (assuming it is well written) will outperform a jQuery solution that accomplishes the same thing in nearly every case (I'd love to see an example otherwise). jQuery does speed up development time, which is a significant benefit which I do not mean to downplay. It facilitates easy to read, easy to follow code, which is more than some developers are capable of creating on their own.
In my opinion then, the answer depends on what you're attempting to achieve. If, as I presumed based on your reference to performance benefits, you're after the best possible speed out of your application, then using jQuery introduces overhead every time you call $(). If you're going for readability, consistency, cross browser compatibility, etc, then there are certainly reasons to favor jQuery over 'native' JavaScript.
There's a framework called... oh guess what? Vanilla JS. Hope you get the joke... :D It sacrifices code legibility for performance... Comparing it to jQuery bellow you can see that retrieving a DOM element by ID is almost 35X faster. :)
So if you want performance you'd better try Vanilla JS and draw your own conclusions. Maybe you won't experience JavaScript hanging the browser's GUI/locking up the UI thread during intensive code like inside a for loop.
Vanilla JS is a fast, lightweight, cross-platform framework for
building incredible, powerful JavaScript applications.
On their homepage there's some perf comparisons:
There's already an accepted answer but I believe no answer typed directly here can be comprehensive in its list of native javascript methods/attributes that has practically guaranteed cross-browser support. For that may I redirect you to quirksmode:
http://www.quirksmode.org/compatibility.html
It is perhaps the most comprehensive list of what works and what doesn't work on what browser anywhere. Pay particular attention to the DOM section. It is a lot to read but the point is not to read it all but to use it as a reference.
When I started seriously writing web apps I printed out all the DOM tables and hung them on the wall so that I know at a glance what is safe to use and what requires hacks. These days I just google something like quirksmode parentNode compatibility when I have doubts.
Like anything else, judgement is mostly a matter of experience. I wouldn't really recommend you to read the entire site and memorize all the issues to figure out when to use jQuery and when to use plain JS. Just be aware of the list. It's easy enough to search. With time you will develop an instinct of when plain JS is preferable.
PS: PPK (the author of the site) also has a very nice book that I do recommend reading
When:
you know that there is unflinching cross-browser support for what you are doing, and
it is not significantly more code to type, and
it is not significantly less readable, and
you are reasonably confident that jQuery will not choose different implementations based on the browser to achieve better performance, then:
use JavaScript. Otherwise use jQuery (if you can).
Edit: This answer applies both when choosing to use jQuery overall versus leaving it out, as well as choosing whether to to use vanilla JS inside jQuery. Choosing between attr('id') and .id leans in favor of JS, while choosing between removeClass('foo') versus .className = .className.replace( new Regexp("(?:^|\\s+)"+foo+"(?:\\s+|$)",'g'), '' ) leans in favor of jQuery.
Others' answers have focused on the broad question of "jQuery vs. plain JS." Judging from your OP, I think you were simply wondering when it's better to use vanilla JS if you've already chosen to use jQuery. Your example is a perfect example of when you should use vanilla JS:
$(this).attr('id');
Is both slower and (in my opinion) less readable than:
this.id.
It's slower because you have to spin up a new JS object just to retrieve the attribute the jQuery way. Now, if you're going to be using $(this) to perform other operations, then by all means, store that jQuery object in a variable and operate with that. However, I've run into many situations where I just need an attribute from the element (like id or src).
Are there any other common practices
like this? Where certain Javascript
operations could be accomplished
easier, without bringing jQuery into
the mix. Or is this a rare case? (of a
jQuery "shortcut" actually requiring
more code)
I think the most common case is the one you describe in your post; people wrapping $(this) in a jQuery object unnecessarily. I see this most often with id and value (instead using $(this).val()).
Edit: Here's an article that explains why using jQuery in the attr() case is slower. Confession: stole it from the tag wiki, but I think it's worth mentioning for the question.
Edit again: Given the readability/performance implications of just accessing attributes directly, I'd say a good rule of thumb is probably to try to to use this.<attributename> when possible. There are probably some instances where this won't work because of browser inconsistencies, but it's probably better to try this first and fall back on jQuery if it doesn't work.
If you are mostly concerned about performance, your main example hits the nail on the head. Invoking jQuery unnecessarily or redundantly is, IMHO, the second main cause of slow performance (the first being poor DOM traversal).
It's not really an example of what you're looking for, but I see this so often that it bears mentioning: One of the best ways to speed up performance of your jQuery scripts is to cache jQuery objects, and/or use chaining:
// poor
$(this).animate({'opacity':'0'}, function() { $(this).remove(); });
// excellent
var element = $(this);
element.animate({'opacity':'0'}, function() { element.remove(); });
// poor
$('.something').load('url');
$('.something').show();
// excellent
var something = $('#container').children('p.something');
something.load('url').show();
I've found there is certainly overlap between JS and JQ. The code you've shown is a good example of that. Frankly, the best reason to use JQ over JS is simply browser compatibility. I always lean toward JQ, even if I can accomplish something in JS.
This is my personal view, but as jQuery is JavaScript anyway, I think theoretically it cannot perform better than vanilla JS ever.
But practically it may perform better than hand-written JS, as one's hand-written code may be not as efficient as jQuery.
Bottom-line - for smaller stuff I tend to use vanilla JS, for JS intensive projects I like to use jQuery and not reinvent the wheel - it's also more productive.
The first answer's live properties list of this as a DOM element is quite complete.
You may find also interesting to know some others.
When this is the document :
this.forms to get an HTMLCollection of the current document forms,
this.anchors to get an HTMLCollection of all the HTMLAnchorElements with name being set,
this.links to get an HTMLCollection of all the HTMLAnchorElements with href being set,
this.images to get an HTMLCollection of all the HTMLImageElements
and the same with the deprecated applets as this.applets
When you work with document.forms, document.forms[formNameOrId] gets the so named or identified form.
When this is a form :
this[inputNameOrId] to get the so named or identified field
When this is form field:
this.type to get the field type
When learning jQuery selectors, we often skip learning already existing HTML elements properties, which are so fast to access.
As usual I'm coming late to this party.
It wasn't the extra functionality that made me decide to use jQuery, as attractive as that was. After all nothing stops you from writing your own functions.
It was the fact that there were so many tricks to learn when modifying the DOM to avoid memory leaks (I'm talking about you IE). To have one central resource that managed all those sort of issues for me, written by people who were a whole lot better JS coders than I ever will be, that was being continually reviewed, revised and tested was god send.
I guess this sort of falls under the cross browser support/abstraction argument.
And of course jQuery does not preclude the use of straight JS when you needed it. I always felt the two seemed to work seamlessly together.
Of course if your browser is not supported by jQuery or you are supporting a low end environment (older phone?) then a large .js file might be a problem. Remember when jQuery used to be tiny?
But normally the performance difference is not an issue of concern. It only has to be fast enough. With Gigahertz of CPU cycles going to waste every second, I'm more concerned with the performance of my coders, the only development resources that doesn't double in power every 18 months.
That said I'm currently looking into accessibility issues and apparently .innerHTML is a bit of a no no with that. jQuery of course depends on .innerHTML, so now I'm looking for a framework that will depend on the somewhat tedious methods that are allowed. And I can imagine such a framework will run slower than jQuery, but as long as it performs well enough, I'll be happy.
Here's a non-technical answer - many jobs may not allow certain libraries, such as jQuery.
In fact, In fact, Google doesn't allow jQuery in any of their code (nor React, because it's owned by Facebook), which you might not have known until the interviewer says "Sorry, but you cant use jQuery, it's not on the approved list at XYZ Corporation". Vanilla JavaScript works absolutely everywhere, every time, and will never give you this problem. If you rely on a library yes you get speed and ease, but you lose universality.
Also, speaking of interviewing, the other downside is that if you say you need to use a library to solve a JavaScript problem during a code quiz, it comes across like you don't actually understand the problem, which looks kinda bad. Whereas if you solve it in raw vanilla JavaScript it demonstrates that you actually understand and can solve every part of whatever problem they throw in front of you.
$(this) is different to this :
By using $(this) you are ensuring the jQuery prototype is being passed onto the object.

Categories