To use or not to use jQuery? - javascript

I have an <img id="mypic"> that i need to change with an interval its src.
Should I use jQuery or not?
Should I do:
document.getElementById('mypic').src='src2';
or
jQuery('#mypic').attr('src','src2');

It...doesn't really matter. I'd say use jQuery if you are using it in other places in your code, otherwise..it is up to you. However, if you are doing this in an interval, it would be slightly (but not noticeably) faster to use natural JS.

Use JQuery if the benefit of having convenient selectors and AJAX support is worth the 29 KB it'll add to your page download time. For most of my uses, it is worth is.
Also, for your JQuery code snippet, the $ character is the JQuery selector. So, you can do this:
$('#mypic').attr('src','src2');
In my opinion, JQuery is very concise, and you can get a lot done once you get used to it.

You should not use jQuery if you don't know how to do it in plain Javascript.
Looks like you know, feel free to use it :)

Related

How to execute Javascript inside jQuery selector

I have a code like this:
$('.' + InjectionPoint).removeClass('classname');
where InjectionPoint is the part controlled by end user, apparently this code is vulnerable to DOM XSS, but is it really exploitable? and how should an attack vector be like?
Thanks
On what are you basing your belief that "this code is vulnerable to DOM XSS"?
Based on this answer, that was true in older versions of jQuery, but not any version later than 1.6.3: https://stackoverflow.com/a/11170073/877682
This is definitely subject to XSS. Check out this article which describes how an attacker might go about it: https://ttmm.io/tech/jquery-xss/
Basically, the author recommends that you use document.querySelectorAll() instead of the jQuery selector function. Someone commented that this is a non-issue for jQuery 1.7 and above but don't quote me on that.
In general, it's never ever a good idea to trust what your users give you.

Jquery plugin Vs javascript

Can somebody please explain the pros and cons for below.
Am having a function to get the url querystring parameters, but I need to know which is the best way to write the function. Eg: if i create the function using jquery plugin style, then every time I need to use a target element to access the function as below
$("#targetDom").getQueryString("name");
However, if I create the function using javascript classes or javascript design pattern, it would be
getQueryString("name");
This is a small example but considering large application which approach is best? is there any disadvantage in going with jquery plugin way?
Regards,
Navin
I found a while ago this sentence:
Don't learn jQuery. Just use it.
It's one of the best advices for a newbie, I think.
jQuery is just an addition to javascript. It simplifies DOM traversing/manipulation, makes easy event handling and so on, but it is not something you should start learning before you know vanilla Javascript.
Regarding your example, it is not the best thought example for jQuery plugin.
The syntax you suggested ($("#targetDom").getQueryString("name");) implies that you treat URL query string as attached somehow to the HTML element, which is wrong...

Reading a javascript script, why so many $ (dollar signs)?

I am trying to decipher a .js script and I am finding it filled with $ throughout? Is there any reason to use this? I'm pretty new to JavaScript.
I think you are reading a JavaScript library famously known as jQuery (or possibly another library). The $ is just a short form for a namespace or use as an identifier.
You can think of it like this jQuery('p') to select all the paragraphs on a page,
or for short form you can just write $('p').
Here is a link for jQuery tutorials/docs jQuery
Here is a list of standards section 7.6 describes it in detail ECMA Standard
A number of libraries have used $ as their primary symbol. It's nothing to do with JavaScript per se, but it's a short distinctive symbol and so libraries have tended to glom onto it. (You can start an identifier with $ in JavaScript, and identifiers can be one character long, so $ is a valid identifier, just like a or x.)
I know of at least three libraries that use $ for something:
jQuery - It's the all purpose function for jQuery, an alias of the jQuery function; more here.
Prototype - It's Prototype's replacement for document.getElementById, more here. Prototype also has $$, which is for looking things up via CSS selectors.
MooTools - Same use as Prototype (because MooTools is either "inspired by" or "forked from" Prototype, some years back, depending on who you ask), more here. And like Prototype, it has $$.
$ is a variable. A number of frameworks use it as a short hand for using it. Prototype and Jquery are the two big ones. This does not mean that the $ automatically is either one of those. It could be anything as anything in JavaScript can assign something to the $. This is something to be aware of, because when you start combining scripts from different sources, it's really easy for one to accidentally reassign a variable to something else.
Most likely it is a framework reference, but you'll have to read the code to be sure. At one point in time the $ was meant to be used to indicate that the code referenced by it was auto generated, but this is just a guideline.
if you're new to javascript, $() can look strange.
Try to think of it like
var $ = function(){
//do something
}
So the dollar sign is just the name of a variable like any other.
var myFunction = function(){
//do something
}
// this is exactly the same just a different name.
So the dollar sign has no special meaning in javascript.
Frameworks like to use it because you are using their functions so often, having to write e.g. jQuery() every time would be tedious. Having one character is nice and short.
I think they also have a preference for the $ symbol, purely because it is unusual so it is quickly distinguishable from other code.
A quick way to find out if it is jQuery is to do console.log(jQuery) if the console returns a string of code $() is jQuery. If you get undefined, it is something else.
Maybe you're reading jQuery code.
Because JavaScript lets you define variables which start with $ sign, or literally which are only $. For example, you can do:
var $ = "something";
alert($);
jQuery is a library built on JavaScript (the most popular at the time) and it has a global object to keep everything encapsulated. You access that global object using $.
The script is probably using a third party library such as Prototypejs or jQuery or he defined his own function $() which explain why the dollar sign appears so often in that script.
It's a jQuery function. That's what it is most probably. Might also be the Prototype library, or just a function that does something that's needed many times in the code, like getElementById etc
Without seeing the code, it sounds like the script you are looking at makes use of jQuery, as the $ is the default jQuery object.
Typically the $ will represent jQuery or another specific library (Moo Tools, etc.) . $ is the shortened form of referencing the jQuery object (or whatever library it was assigned). It makes the code much more readable and easy to use.
If you are just learning javascript, you will soon become very familiar with jQuery. :)
Either its jQuery or an old PHP habit by some javascript programmer :)
$ is only a function. It means you work with some javascript superstructure (framework).

How to detect what Library is behind the $ function?

I am developing some JavaScript that should work with either Prototype.js or JQuery, thus I need some way to identify what is the primary library in use. How can I do that?
You can check for jQuery like this:
if (window.$ === window.jQuery)
Well, you could check for the presence of jQuery:
if(window.jQuery !== "undefined")
{
// jQuery Yay!
}
and then if it is assigned to $
if(window.jQuery === window.$)
{
// jQuery Yay!
}
Could jQuery noconflict help? Then you could use jQuery for jQuery and $ for prototype.
#SLaks and #Chacha102 are right for detecting jQuery, but if you want to make sure that if the $ function is not from jQuery, comes from PrototypeJS, you can:
​if (typeof $ == 'function'​​) {
if ($.fn && $.fn.jquery) { // $.fn.jquery contains the version number
// jquery
} else if (window.Prototype && Prototype.Version) {
// prototype
}
}​
I am developing some JavaScript that should work with either Prototype.js or JQuery, thus I need some way to identify what is the primary library in use. How can I do that?
Your question is ambiguous, there are two obvious meanings to me so I'll answer both.
If you mean you want write code that will work regardless of whether jQuery or Prototype.js has been used, the answer is that it is quite easy to write code that works regardless of the libraries that have been, or will be, loaded. So there is no need to discover which one has been used.
If you mean that you are going to write two separate scripts, one for jQuery and one for Prototype.js, then, depending on which one you "detect", you'll load one script or the other, then you basing your code on a very bad architecture. Neither of those libraries support a particularly wide selection of browsers and both need updating whenever a new version comes out, even of the "popular" ones they support.
Attempting to support both using separate scripts will create an on-going maintenance headache - times two. Or perhaps that is your intention.
--
Rob
Write it without dependency on any library and it should work fine with both jQuery and Prototype ;)
Seriously, isn't one of the main points of these library to avoid having to write three different variations of each line of code for each browser? Writing code to try to suit more than one library seems quite silly.
Anyway, looking at the documentation for either library for about 5 seconds should give you a hint as to what properties jq $ will have that pt $ will not. This suggests that you haven't really bothered to look at the differences between the frameworks (which is obviously going to be the best way to tell them apart, right?). Are you sure you know what you're getting yourself into?
As several have mentioned:
var whosThatDollarSign = typeof window.$=='undefined' ? 'none' : (window.$==window.jQuery ? 'jQuery' : 'not jQuery')

Is there a good way to prevent jQuery from being redefined?

I encountered a problem that took me some time to debug where a plug-in that I was using for jQuery (in this case jFeed) was not working. The problem ended up being because we also used Amazon Associates product previews. The product previews code ends up including a number of other JS files through document.write(), including another copy of jQuery. Because the product previews code appeared below the jFeed script, jQuery was redefined without the getFeed function.
Is there a best practice to ensure that certain objects like jQuery only get defined once on a page? I'm thinking of something like #ifndef with C/C++, but I don't know how it would work in this case where I didn't write the code that dynamically pulled in jQuery again.
I think in your situation, it would probably be best to redefine the jQuery variable as something else. The other jQuery code might use a different version so you might want to define a new variable which would indicate which jQuery you're using.
You could so something like this:
<script>
var $jMain = jQuery;
</script>
You would then just use the $jMain instead of jQuery or $. It'll be up to you to you to ensure you have the correct jQuery object when you do this. Here's the documentation.
Unfortunately the environment inside one JS sandbox (like within a window or frame of a browser) was not really designed to support the modern world of pulling in scripts from various places; there's no way you can say "define this object and make it resistant to redefinition". (You can even redefine most of the Javascript built-ins if you try!)
Your best shot is to make sure that your code is eval'd last, which gives you final say over the state of the environment when it runs. That doesn't mean other code can't come along later and clobber your definitions, but that's generally really bad form. You can do this by having your script tag be the last element in the body of the document, for example.
See also this jQuery method, which won't help you directly, but gets you thinking about some solutions to page sharing: http://api.jquery.com/jQuery.noConflict/

Categories

Resources