jQuery, Javascript : Javascript wrapped in jQuery(), $() - what does it mean? - javascript

I'm having trouble understanding a type of jQuery selection, and I hope someone can explain it to me in clear terms.
It's taken from this Stack Overflow question.
Basically, it has the common jQuery: $( selector ).
But inside that it has $({ y: iFrameScrollY }).
I've never seen this before. What does it mean to have { ... } and someVal: anotherVal inside the brackets?
Also, please recommend a different title for this question, to make it easier for others to find it.

What $({ y: iFrameScrollY }) does is wrap a jQuery selector object around the JavaScript object { y: iFrameScrollY }.
The JavaScript object is declared { y: iFrameScrollY }, meaning it contains a property named y set to the value of iFrameScrollY.
By wrapping the object into a jQuery object one can avail of executing jQuery methods against the wrapped object.
See this documentation for more details.

Wrapping plain JavaScript object inside jQuery object you can use few jQuery methods including: .data(),.prop(),.bind(), .unbind(), .trigger() and .triggerHandler().
Here is an example taken from jQuery.com:
// define a plain object
var foo = {foo:'bar', hello:'world'};
// wrap this with jQuery
var $foo = $(foo);
// test accessing property values
var test1 = $foo.prop('foo'); // bar
// test setting property values
$foo.prop('foo', 'foobar');
var test2 = $foo.prop('foo'); // foobar
// test using .data() as summarized above
$foo.data('keyName', 'someValue');
console.log($foo); // will now contain a jQuery{randomNumber} property
// test binding an event name and triggering
$foo.bind('eventName', function (){
console.log('eventName was called');
});
$foo.trigger('eventName'); // logs 'eventName was called'

That's a call to the jQuery() function, which is overloaded to do a lot of different things, depending on the arguments being passed.
The {someVal : anotherVal} is a JavaScript object with a property named someVal with a value equal to the value of the anotherVal variable.
If you join those two pieces of information together, and look at the linked page, you'll see this:
jQuery( object )
object A plain object to wrap in a jQuery object.

Related

jQuery / JavaScript, why do I need to wrap variables in $() to use them?

Say I have a map on an array of elements. The callback function takes the index and the value at that position in the array.
If I wrap the array element that the callback receives in $(), it behaves as I expect. If I use it without wrapping it in $(), it gives an error.
var nonHiddenElements = $( "form :input" ).not(':hidden');
nonHiddenElements.map(function(index, element){
input_id = $(element).attr('id'); // this works
input_id = element.attr('id') ; // this gives an error
})
Can someone explain how this works.
Is this a jQuery quirk, or a JavScript thing?
What type of objects does my nonHiddenElements array contain exactly?
What is element that gets passed to the callback?
And mainly what is the $() doing?
You need to understand how jQuery actually works. I will try to explain it briefly.
$ is nothing but a normal javascript function. jQuery === $, is just a function with a fancy name. This function does a lot of different things, depending on what you pass in it. For example if you pass a string it will be treated as CSS selector and jQuery internals will try to find corresponding DOM elements. Or if you pass a string starting with < and ending with > jQuery will create a new DOM element by provided HTML string.
Now if you pass a DOM element or NodeCollection of DOM elements, it/they will be wrapped into jQuery instances so that they can have a jQuery prototype methods. There are many prototype methods jQuery offers. For example text, css, append, attr - those are all methods of jQuery prototype. They are defined basically like this (simplified):
jQuery.prototype.text = function() { ... }
Normal DOM elements don't have those convenient methods jQuery provides. And inside of methods like map or each if you check this value or element parameter like you do, you will see that they are actually not jQuery instances:
element instanceof jQuery // => false
and of course you can't use instance methods with not an instance.
So in order to use jQuery prototype methods you need have a jQuery instance, which you can obtain if you call jQuery function with DOM element passed in it:
$(element) instanceof jQuery // true
Javascript is a programming language.
jQuery is a JavaScript Library.
With jQuery:
$("some element")
In native JavaScript you would have to do something like this.
getElementById('elementByID')
Explained in detail here: https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById
MDN is a great resource for beginners. https://developer.mozilla.org/en-US/docs/Web/JavaScript

about javascript / jquery syntax

I couldn't find the syntax something like this anywhere:
var mz = jQuery.noConflict();
mz('#zoom01, .cloud-zoom-gallery').CloudZoom();
This means: jQuery.noConflict()('#zoom01, .cloud-zoom-gallery').CloudZoom();
And something like this:
$(window)[this.off?'off':'on']("scroll", fixDiv );
So, I'm wondering about the syntax something like of these:
jQuery.noConflict()(syntax) and $(window)[syntax](syntax) and I also think there might be something like this $(selector){syntax}
Can anyone elaborate of those syntax?
The best place to start is the documentation
$.noConflict()
Many JavaScript libraries use $ as a function or variable name, just
as jQuery does. In jQuery's case, $ is just an alias for jQuery, so
all functionality is available without using $. If you need to use
another JavaScript library alongside jQuery, return control of $ back
to the other library with a call to $.noConflict(). Old references of
$ are saved during jQuery initialization; noConflict() simply restores
them.
In other words, noConflict() sets a variable to equal jQuery, so this
var mz = jQuery.noConflict();
mz('#zoom01, .cloud-zoom-gallery').CloudZoom();
is the same as
$('#zoom01, .cloud-zoom-gallery').CloudZoom();
or
jQuery('#zoom01, .cloud-zoom-gallery').CloudZoom();
noConflict() does not directly take selectors, it's just a function that sets jQuery in a certain scope to a variable so you can have multiple versions of jQuery (which you shouldn't) or use other libraries that also uses $ for something, it does not mirror the selector engine or anything else, even if it might seem so at first glance, it simply returns an instance of jQuery
In javascript there is dot notation and bracket notation, so an object can be accessed as
object.propertyName
or
object['propertyName']
as everything in javascript is an object, even jQuery methods, they can be accessed as
$('#element').fadeIn(200);
or
$('#element')['fadeIn'](200);
it's the same thing, so doing
$(window)['on']("scroll", fixDiv );
is the same as
$(window).on("scroll", fixDiv );
the advantage of using brackets is that they can contain any string, even variables, or in this case ternary statements, or the returned result of a function
var event = 'on';
$(window)[event]("scroll", fixDiv );
or
var event = this.off ? 'off' : 'on';
$(window)[event]("scroll", fixDiv );
that one also uses this, which in the global scope would be window, and it's the same as
$(window)[this.off ? 'off' : 'on']("scroll", fixDiv );
The ternary statement itself is just a fancy condition, and this
var event;
if (this.off) {
event = 'off';
} else {
event = 'on';
}
is exactly the same as
var event = this.off ? 'off' : 'on';
Added for the edited question :
jQuery() or $() is a function, something we can tell from the parenthesis, so it's something like
function jQuery(arguments) {
// do something
}
which can be called as
jQuery(some_arguments);
and as var $ = jQuery one can also do $();
Now that we know it's a function, it makes sense that we can do
$('#element_id')
and internally jQuery checks what kind of argument we passed, it sees that is's a string, and it's starting with #, so it's an ID, and then jQuery can do document.getElementById() and get that DOM element, and at the same it wraps that element in a new array-like object, usually referred to as a jQuery object.
We can also pass in a DOM node, array, object or anything else, and jQuery tries to figure out what it is, and wrap in that jQuery object for us to use with other jQuery methods, so this :
$({x:10, y:20})
is the same as
var obj = {x:10, y:20};
$(obj)
and its turned into one of those jQuery objects with the properties x and y. Passing in an object like this means we can chain on methods, and those properties are available in the methods.
$({x:10, y:20}).animate({x:50}, 1000);
And that's basically how it works, simplified a lot.
As for passing objects to methods, that's a very common way to pass arguments.
To see how it works, it's easiest to create a method:
$.fn.doStuff = function(argument) {
this.css(argument);
}
inside a jQuery plugin, this is the jQuery object, and we can now use the mothod above that does nothing more than pass the arguments to jQuery's css().
We know we can pass an object to css() like this :
$('#element').css({left: '10px', top: '20px'});
so using our plugin we can do the same
var obj = {left: '10px', top: '20px'};
$('#element').doStuff(obj);
and it ends up doing exactly the same thing. Of course, we could do anything with the object :
$.fn.doStuff = function(args) {
if ( typeof args == 'string' ) {
alert(args); // if it's a string, just alert it
} else if ( typeof args == 'object' ) {
for ( var key in args ) { // if it's an object, iterate
this[0].style[key] = args[key]; // and do something
}
}
}
foo['bar'] syntax is to get the property bar from object foo.
foo() is to execute the function foo.
And you can combine these as you wish.
jQuery.noConflict() returns a function so you could execute the result by jQuery.noConflict()(syntax).
$(window) returns an object so you could get a property from it by $(window)[syntax], and if the property is a function, then you could execute it by $(window)[syntax](syntax).
This is just javascript syntax.
person.name is exactly the same as person["name"]
The same happens with methods
$(window).on(...) is exactly the same as $(window)["on"](...)
One cool thing about the second way is that you can make the member name variable, for example:
So doing:
var windowMethod = "on";
$(window)[windowMethod](...)
is the same as
$(window)["on"](...)
And you can have an expression inside the brackets, so this:
$(window)[this.off ? 'off' : 'on']("scroll", fixDiv );
would be exactly the same as doing this:
if(this.off)
$(window).off("scroll", fixDiv);
else
$(window).on("scroll", fixDiv);
But the former is shorter.
Hope this helps. Cheers
PS: The jQuery.noConflict()(syntax) is straightforward, .noConflict() just returns a function and then we append some other parens to call it just as any other function.

confusion over simple variable declaration jQuery "$variable" vs javascript "var"

I have this simple ghost text implementation:
HTML code:
<div id="searchPanel">
<form method="get" id="searchBox" action="somePage.php">
<input class="ghText" type="text" name="query" value="search here"/>
</form>
</div>
jQuery code:
$(document).ready(function(){
$txtField = "#searchPanel form input.ghText";
var value = $($txtField).val();
$($txtField).focus(function(){
if($(this).val() == value)
$(this).val("").removeClass("ghText");
});
$($txtField).blur(function(){
if($(this).val()==""){
$(this).val(value).addClass("ghText");
}
});
});
The example above is not going to work. When the user focuses the cursor on the search bar, the class "ghText" wont be removed for some reason.
However now if I change the "var value" (variable initialization) and "value" with
"$value" as in:
$value = $($txtField).val();
$(this).val($value).removeClass("ghText");
$(this).val($value).addClass("ghText");
everything works perfectly.
I can just go to sleep and not worried too much about it..but I am very curious why something like that can happen?
is it because of the "this" not referreing to the right object, or is it because i tried storing jQuery object in non-jQuery variable or is it about something else..can somebody point out to me what was wrong? I have always thought that "var x" is the same as "$x"..?
You seem to be confused about JavaScript variables. There is no such thing as "jQuery variables" and "non-jQuery variables". Some specific cases:
A variable declared with var is different to a variable without. "var x" is a local variable, so it will not share a value with other functions which also have a variable called "x". This is almost always a good thing, so you should almost always declare variables with "var".
The $ in jQuery is sort of special. It isn't that special; it's just that jQuery has declared a variable called "$" which does some fancy operations.
There is nothing special about variables that begin with "$". In other words, "$x" is just a variable name. It is a different variable to "x", and it isn't a "jQuery variable". It's just a JavaScript variable called "$x". (This is different from PHP, where the $ is actually a special variable syntax.)
So you can just call it "value" instead of "$value".
Possibly the fact that you removed the "var" changed things by making it into a global variable.
As for "this", yes, that is a tricky aspect of JavaScript, and might be causing your problem. The value of "this" inside the inner 'focus' and 'blur' functions is likely to be different from the value of "this" outside. I'm not sure exactly what "this" refers to in an event handler, but it will not be the same object. So what you probably want to do is assign "this" to a variable in the outer function, and then refer to that variable on the inside in place of "this".
When storing a jQuery selection in a variable, it's common practice to add a $ before the variable name like this:
var $banner = $('#banner');
It's not necessary to include the dollar sign — var banner = $('#banner') would work just as well. However, the dollar sign reminds you that the variable holds a jQuery selection and not just any value like a number or a string.
#mgiuca is entirely right about Javascript variables - the '$' that precedes them is just a naming convention that most use to identify jQuery objects. I add this because you say
because i tried storing jQuery object
in non-jQuery variable
but this is wrong. $txtField is a string that you are using to select an object. If you want to store the object itself you should do $txtField = $(#searchPanel form input.ghText) and then use it thusly $txtField.val().
Having said that your code works fine for me unaltered. I've set up a demo which works on Chrome - is this a cut down version of you code?
In to addition #mgiuca's answer here is a little more elaborate approach to your problem that also shows some of the jQuery concep:
$(document).ready(function () {
// define two helper functions
var removeDefault = function () {
if( $(this).val() == $(this).data("defaultValue") ) {
$(this).val("").removeClass("ghText");
}
};
var setDefault = function () {
if( $(this).val() == "" ) {
$(this).val( $(this).data("defaultValue") ).addClass("ghText");
}
};
// the following works on all input elements
$("#searchPanel form input.ghText").each(function () {
$(this)
.data("defaultValue", $(this).val())
.focus(removeDefault)
.blur(setDefault);
});
});
Note
the use of .data() to associate a value with a specific element.
the use of .each() to apply the same behavior to any number of elements
the use function references for .focus() and .blur() - jQuery will always set the this correctly on its own
see it working over here http://jsfiddle.net/xsXxn/
So $x is a jQuery variable after all :) ... Well, anyway, here is one instance when $ or not $ did make a big difference in my code:
...load("whatever.php", {par1: var1, par2: var2})
didn't work, at least inside the $(obj).attr() assignment, unless $var1, $var2 where used. This worked:
$(obj).attr("onClick",$("#wherever").load("whatever.php", {par1: $var1, par2: $var2})...

Why do I have to use $(this)? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
jQuery $(this) vs this
In jquery sometimes I find that within a function I have to use $(this) because this won't work:
var listItems = $('li');
listItems.each(function(index) {
$(this).css({
})
})
Any ideas as to the reason why?
$() is the jQuery constructor function
this is a reference to the DOM element of invocation
So basically, you're turning a DOM reference into a jQuery object
In your example, you could also use
listItems.each(function(index, element){
$(element).css({
});
});
..since .each() will pass both, index + element in its callback.
I know I'm a bit late to this thread but I just wanted to bring up the fact that redundant wrapping of DOM objects is one of the most frequently committed crimes against jQuery. Taking care with your jQuery-instance constructing can have tremendous effects performance-wise and it's so easy to do that you have no excuse not to.
Typically, when people have a DOM object (whether it be referenced as this or element) they'll try to wrap it each time they need access to a jQuery method:
jQuery(this).css('a', 'b');
The problem is when you're doing this multiple times:
jQuery(this).css('a', 'b');
jQuery(this).find('span').attr(...);
jQuery(this)....
Every time jQuery() is called, a new jQuery instance is constructed. That kind of operation is expensive and should be avoided if at all possible -- especially in loops!
To avoid this, for one, you could utilise chaining with all methods that return a jQuery instance $(this).css(a,b).attr(a,b)...). The rest of the time you should have a locally declared variable that refers to the jQuery instance and then just use that:
var self = jQuery(this);
self.css(...);
self.attr(...);
If you're doing this within an .each() callback function, there is still a new jQuery object being constructed on every single iteration. You can avoid this by having one generic jQuery object which you continually mutate and then you can run jQuery methods off that single instance:
Look at this:
jQuery.single = function(a){
return function(b){
a[0] = b;
return a
}
}(jQuery([1]));
Now look at this:
$('a').each(function(i){
$.single(this).append('Anchor number ' + i);
});
Only one jQuery object is being used. You can make it even faster by avoiding the identifier resolution:
$_ = $.single;
$('a').each(function(i){
$_(this).append('Anchor number ' + i);
});
Food for thought. More info here: http://james.padolsey.com/javascript/76-bytes-for-faster-jquery/
this is the native DOM element. $(this) is a jQuery object that allows you to call functions such as .css() on it.
this is typically a DOM object by default, which means it only has the methods on normal DOM objects.
If you want to invoke a library-specific function (such as jQuery's .css function), you have to convert it to a full jQuery object first, which is what $() does by default if you pass it a DOM object.
(You can also pass other things to $(), such as an HTML string (to construct a new jQuery-wrapped DOM object) or a CSS selector (to get a set of jQuery objects that correspond to DOM objects matching the selector).
If you are using Firefox, try console.log($(this)) and console.log(this) to see the difference.

How to get ID when you pass my ID

I have a function that gets passed the document object like:
toggle( $('username') );
function Toggle(id)
{
/// ??
}
How can I get the actual name of the object passed i.e. username?
If I understand you correctly, can't you:
$(id).attr("id");
or
$(id).attr("name");
Or am I mistaken?
Either what Jonathon said or with
$(id).val();
The object that gets passed in is an instance of the jQuery object, which contains a set of elements (in this case with only one element in it). The documentation is on the jQuery documentation site.
The jQuery object that $() returns, wraps one or more DOM elements.
Using the accessors $().attr(), $().val(), $().text() and $().html() will act on the first of those wrapped elements.
If you want to drop out of jQuery mode so that you can work with the native DOM element (sometimes useful) use $().get( index ).
eg
var el = $('#mytextbox').get(0);
el.value = 'a new value';
alert(el.id);
etc...

Categories