This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the meaning of “$” sign in javascript
I've encountered a code in JavaScript that looks like this:
$('svg circle').tipsy({
gravity: 'w',
html: true,
title: function() {
return 'Color: ';
}
});
What does $('') mean here?
This is from using the jQuery library, which is used to standardize JavaScript usage between browsers and make accessing elements and other common tasks much, much easier. It is not a part of JavaScript itself, except insofar as $ is an acceptable name for a function or variable.
Usually when you encounter $(), that means the developer is using a javascript library, such as jQuery.
The $ symbol is the namespace for those libraries. All the functions they define begin with $., such as $.get(). Passing the id of an html tag like this: $("#myId") will give you a jQuery object representing that node.
This is the shorted initializing function for jQuery or zeptojs
$("selector").method();
It can also mean an shorten for document.getElementById if the framework is used:
$('myId'); // document.getElementById("myId");
The plugin tipsy is used witch creates tooltips on hover.
Related
I was recently assigned a very small but complex task in jQuery, the requirement was quite simple, given the following HTML :
<div>
<span id="myid2151511" class="myclass23462362">....foobar....</span>
<span id="myid2151512" class="myclass23462362">....YoLO....</span>
<span id="myid2151513" class="myclass23462362">....lalal....</span>
<span id="myid2151514" class="myclass23462362">....foobar....</span>
</div>
What i have to do i recursively go through all the span under div, With a certain id and check if the values contained in the spans is foobar, So i can up with the following jQuery code:
$(function(){
$('div [id^="myid"]:contains("foobar"):last').css({'background' : 'rgb(227, 216, 22)' })
});
FIDDLE HERE
Its quite a complex bit of code by itself, but the jQuery documentation made it a cakewalk for me as for as understanding the code is concerned.
By now i am comfortable writing code like so in jQuery:
$('some-Element').somemethod().anothermethod().yetanothermethod();
Every function returns a value in the above jQuery statement, so chain ability becomes a reality.
but when i see code like so.
$('div [id^="myid"]:contains("foobar"):last').css({'background' : 'rgb(227, 216, 22)' });
I am thrown a bit off the hook(although i managed to write the above line myself), notice how alot of the filtering is done by a selector :last and :contains, to me they appear to be working much like some kind of a jQuery method. So my question is, how do these selectors in jQuery work in comparison to jQuery methods ?
If anybody could explain or give me a vague idea, it would be Fantastic.
EDIT ::
well to clarify my question in one line, to me $(".someClass").eq('10'); makes sense, but somehow $(".someClass:eq(10)") does't , i mean it works, but how on earth is it implemented internally ?(I wrote this edit after reading the answers below, and well this question has been thoroughly answered by now, but this edit is just to clarify my question.).
That's an interesting question. The short answer is they both accomplish the same thing. Of course though, there's always more to the story. In general:
$('div [id^="myid"]:contains("foobar"):last').css({'background' : 'rgb(227, 216, 22)' });
Is equivalent to:
$("div").find("[id^='myid']").filter(":contains('foobar')").last().css({'background' : 'rgb(227, 216, 22)' });
Most of the time when you call $(), jQuery is calling document.querySelectorAll(). This is a browser implemented function that grabs elements based on a selector. That complex string you create is passed to this method and the elements are returned.
Naturally, things implemented by the browser are faster than JavaScript so the less JavaScript and more C++, the better. As a result, your example passing everything as a selector is likely to be faster as it just sends it all to the browser as one call and tells it "do it." Calling $(), contains(), last() on the other hand is going to call querySelectorAll multiple times and therefore it will likely be slower since we're doing more JavaScript as opposed to letting the browser do the heavy lifting in one shot. There are exceptions though. JQuery generally calls querySelectorAll. However, there are times when it doesn't. This is because jQuery extends what querySelectorAll is capable of.
For example, if you do something like $(".someClass:eq(10)") per the jQuery documentation:
jQuery has extended the CSS3 selectors with the following selectors. Because these selectors are jQuery extension and not part of the CSS specification, queries using them cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using these selectors, first select some elements using a pure CSS selector, then use .filter().
So in that case, while $(".someClass:eq(10)") might seem to be faster, in reality $(".someClass").eq(10) or $(".someClass").filter(":eq(10)") is going to be faster since the first call will be executed as JavaScript code. The latter two will first call querySelectorAll to select by class, then only use JavaScript to find the 10th element. When jQuery has to do the selection in pure JavaScript, it does it using the Sizzle engine which is fast, very fast, but not faster than native code in the browser. So again, the short answer is, they're the same thing, the long answer is, it depends. If you're interested in all the extensions that fall into that category, the link to the jQuery documentation I included lists them.
First of all, yes nikhil was right. ID is unique identifier and can be only used once. If you are willing to apply same styles to several elements, or you to use it to select several elements together use class attribute. But however, i couldn't understand your question. But maybe this could help
there is function in javascript which is widely supported by almost all major browsers
document.querySelectorAll("div [id^=myId]");
in fact you could write your own library (well not as advanced one like jquery but)
var $ = function(selector){
return document.querySelectorAll(selector);
}
// and then you could use it like this
var elementsWithMyId = $("div [id^=myId]");
// where elementsWithMyId will contain array of all divs which's id start with myId
so as i understood your question, No. there is no magic happening behind jQuery selections it's just browser built in function which is kinda shortened by jquery. of course they added tons of new features, which would work like this:
var $ = function(selector){
var elementsArray = document.querySelectorAll(selector);
elementsArray.makeBlue = function(){
for(var i = 0; i < elementsArray.length; i++){
elementsArray[i].style.backgroundColor = "blue";
}
// so elementsArray will now have function to make all of its
// div blues. but if you want to have chain like that, we have to return this array not just make all of it blue
return elementsArray;
}
elementsArray.makeRed = function(){
for(var i = 0; i < elementsArray.length; i++){
elementsArray[i].style.backgroundColor = "red";
}
return elementsArray;
}
return elementsArray;
}
// so now you can use it like this
// this returns array which has options make blue, and make red so lets use make blue first
// makeBlue then returns itself, meaning it returns array which has again options of making itself red and blue so we can use makeRed now
$("div [id^=myId]").makeBlue().makeRed();
and thats it!
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
jQuery attribute selector for multiple values
I have this
$('input:radio[name=foo]').change(function() {
blah();
});
$('input:radio[name=bar]').change(function() {
blah();
});
Can I do something like this?
$('input:radio[name=foo||bar]').change(function() {
blah();
});
what If I had another one?
$('input:radio[name=foo||bar||foobar]').change(function() {
blah();
});
I can't use class which would be ideal as this is a custom framework (not mine) that
generates the HTML which is overriding my class. Also there is no id selector available
just the name attribute. I think I'm stuck doing separate functions but wanted to pose the question to see if anyone can think outside the box on this one.
Note: this project uses jQuery 1.3.2 and I can't upgrade just yet. And before you say anything, yeah I'm with you on upgrading...
There is no 'or' character, but you can use multiple selectors - you just separate them by commas:
$('input:radio[name=foo], input:radio[name=bar]').change(function() {
blah();
});
Or better yet, use a class selector as this is exactly what they were designed for.
Unfortunately there isn't a simple selector for or within [attr] selectors. You can use a comma (,) to separate your selections:
$('input:radio[name=foo], input:radio[name=bar]').change(...);
Or if your selection happens to be longer, you can use $.fn.filter:
$('#foo #bar #baz .fizz .buzz input:radio').filter('[name=foo], [name=bar]').change(...);
I recommend reviewing the entire list of jQuery selectors.
jQuery's $() function uses CSS selectors (nearly all of CSS3 plus a few of its own). Their syntax has nothing whatsoever to do with JavaScript's logical operators.
Neither CSS3 nor jQuery offer a "match any of these", so you use a selector group instead:
$('input:radio[name=foo], input:radio[name=bar], input:radio[name=foobar]').change(function() {
blah();
});
Another alternative is adding a new filter for regex:
http://james.padolsey.com/javascript/regex-selector-for-jquery/
Then you can do something like
$('input:radio:regex(name, ^(foo|bar|baz)$)')
Your proposed solution does work on newer versions of jQuery. You can chain filter onto your query, though ...
$('input:radio').filter("[name=foo],[name=bar]").change(function() {
blah();
});
View and play with the jsfiddle here
http://jsfiddle.net/NAgv5/1/
I've come across the dollar sign function over the internets and decided to use it for a javascript toggle menu. However, the "$" symbol makes my code fail.
This is what I'm trying to use:
function $() {
var elements = new Array();
for (var i = 0; i < arguments.length; i++) {
var element = arguments[i];
if (typeof element == 'string')
element = document.getElementById(element);
if (arguments.length == 1)
return element;
elements.push(element);
}
return elements;
}
function toggle(obj) {
var el = $(obj);
el.style.display = (el.style.display != 'none' ? 'none' : '' );
}
The $ from "function $(){" seems to break the code. How do you declare this function?
If I replace $ with "anything", it works, but not as a dollar function...
The dollar sign is not a standard Javascript function, but is part of a third party library.
There are two well-known libraries which use the dollar sign in this way.
The older one is called Prototype, but the one which is currently in vogue, and most likely to be the one you've seen in use is JQuery.
Both these libraries would be used by adding a <script> tag to your HTML page, to include the library code, after which you can use their functionality.
Most of the functionality of both these libraries is contained within their respective $() functions. In the case of JQuery, you can also refer to the $() function as jQuery() to prevent namespace clashes, in the event that you wanted to use both of them.
I suggest reading up on JQuery before continuing -- JQuery is very powerful, and adds a lot of functionality, but the coding style for writing JQuery code can be quite different from regular Javascript, and can take a bit of getting used to. And that's quite apart from learning the API and finding out what it can do.
To actually answer your question -- which is how to declare $ as a function name, I suggest having a look at the JQuery source code to see how they do it. However, I managed to produce a working $() function first time I tried, like this:
var $ = function() {alert('dollar works for me');}
$();
But to be honest, I wouldn't do that. If you really want to use the $() function in the way it's being used in other sites, you need to use JQuery. It does a whole lot more than just wrapping document.getElementById().
By the way, JQuery and Prototype are not the only similar libraries out there. If you're interested in this sort of thing, you may also want to look into MooTools, YUI, and a few others.
Hope that helps.
The $ sign is a notation for various javascript frameworks (prototype/jQuery). Since replacing it with "anything else" works, you most likely have a clash between that inline function and the framework you are using.
In itself, the notation and function is correct, as the following example shows.
Open a new tab/window and enter this on the address bar:
javascript:eval("function $() { alert('hi'); } $();");
I'm new with javascript, so i'm trying to use two jQuery plugins, together they don't work properly. Just if i remove one of two.
How can i resolve this problem ? I could paste both .js files, but that is 2k lines of code, I don't want bother you with so many lines of code.
jQuery.autocomplete.js
Greybox plugin AJS.js
Or if you know some plugin that do some functionality, will help too =)
--
UPDATE:
Thank you guys,
(i'm not able to add comment in your answers (i really don't know why), some problem with the site.)
#Mörre i noted when i remove this line in AJS.js it works (part of it) :
AJS.exportToGlobalScope();
But after that I don't know what to do, sorry guys, I'm new in javascript so many things that you said I don't understand.
#Jim, i don't find any:
$(document).ready(function() {
});
the replace by jQuery as you said.
I try to replace all '$' by 'jQuery', and still doesn't work.
Valter,
you may find that there's a collision on the $ alias going on. you'll possibly get it to work if you explicity reference jquery object using the full jquery alias i.e rather than:
<script type="text/javascript">
$(document).ready(function() {
});
</script>
try:
<script type="text/javascript">
jQuery(document).ready(function() {
});
</script>
change any $ references to jQuery in the client code when using the autocomplete lib.
just a thought if it's in relation to this'area'
Without checking any further after looking at the code briefly, the AJS code puts everything in a global object AJS at first - but then exports every single property of that object into the global namespace. Bad behavior. The first one is a regular jQuery plugin. Recommendation: Don't use AJS, or remove the export to global space (you then just call AJS methods by prefixing them with "AJS.").
This question already has answers here:
Getting an empty JQuery object
(4 answers)
Closed 5 years ago.
Edit: As of jQuery 1.4, using $() will work as described below.
I need to loop through an array and create a number of elements which I want to have in a single jQuery result object.
for (var i = 0; i < 10; ++i) {
$myJQueryObj = $myJQueryObj.add($("<span>blahblah</span>"));
}
The problem with this, however, is that you need a jQuery object to begin with, and you obviously want to start it empty. In the above example, how should I initialise $myJQueryObj ?
The following examples do not work, as they all select the document object:
$('')
$()
$(null)
$(false)
These do work... but...
$('#nonExistantElement') // yuck
$().slice(0,0) // surely there's a nicer way?
Is there a better way?
Yep. Try $([]). The reason $() doesn't work is because that jQuery expects a context, and without any supplied, will default to document as the context. Many things depend on this assumption being true, so changing $() to mean "give me the empty set" would be problematic at best.
Ah, I figured it out just after I wrote the question. Here's what I found, in case anyone else is interested:
$([])