jquery variable vs $(jquery varibale), what is difference b/w the two - javascript

When I do:
var x = $("#listing")
I get back html element with id listing,
And when I do $(x) or $($("#listing")), I get the same.
What is difference b/w two?

$() will convert something to a jQuery object (or collection). This is not the same as a Javascript variable.
When you store #listing in a variable such as var x = '#listing', you are simply passing a string to the jQuery constructor, which is then interpreted as a selector by Sizzle, jQuery's selector engine.
In the example provided, there is no difference between the two following lines:
var x = $('#listing');
var x = '#listing',
$x = $(x);
In the first snippet, x is identical to $x in the second.
In the interest of completeness, the jQuery constructor can also accept a mixed type variable as its first parameter; it doesn't have to be a string. For example, it's possible to convert a DOMElement variable into a jQuery object using the following syntax:
var ele = document.getElementById('myItem'),
$ele = $(ele);
Notice that $ele now has access to jQuery's own functions, such as addClass(), etc. Please see this demo.
Furthermore, passing a jQuery object to the constructor will simply return the same jQuery object. For example, given the following snippet:
var $x = $('#listing'),
$x2 = $( $x );
$x is identical to $x2.

Your x variable was made a jQuery object once it found the dorm item.
Once you run var x = $('#listing'); x has everything wrapping it has.
Thus you can run x.addClass('thing')

Adding $ is creating jQuery object, its not normal variable. You can create jQuery object from DOM element, from another jQuery object or from normal javascript variable. Try to run console.log(x) console.log($(x)) and it will tell you all differences.

Related

jQuery difference between "var name" and "$name" [duplicate]

I know it's a silly question but I am a bit confused with this. For example, if I have an input with an ID: rad1, is there any difference between below lines of code?
var $a = $('#rad1')
or
var a = $('#rad1')
No there is no real difference.
It's just a convention that helps you remember that a isn't the DOM element but it's a jQuery object.
var a = document.getElementById('a');
a.innerHTML //fine
var $a = $('#a');
$a.html() // fine
Ohhh, and by the way, neither a or $a are good variable names ... you should use meaningful variable names not abc characters.
Read the jQuery info tag on this very same site:
Variable Naming Conventions
jQuery wrapped variables are usually named starting with '$' to distinguish them from standard JavaScript objects.
var $this = $(this);
It's only for showing that it's a Jquery variable.
Declaring $a you're showing that your variable is for JQuery objects, it's just a notation. So the most readable thing will be to declare Jquery variable with $ notation
var $obj=$("#obj");
And DOM element without $ notation
var obj = document.getElementById("obj");
There's no difference. It's just a coding convention to help identify that the variable represents a jquery wrapped object.
No difference its just coding convention , check this
I think this scenario should illustrate the reason for remembering(off course, assigning '$' ) jquery and simple javascript variables:
<form id='myform' >
<input id="name" type="text" value="Peter" />
</form>
<script>
$(document).ready(function(){
var name = document.getElementById('name');
var $name = $('#name');
console.log(name.value); // javascript's properties are available
console.log($name.value); //it is undefined (worth of notice)
console.log(name.val()); // error! name.val is not a function ! (jquery function will not be available)
console.log($name.val()); // jquery functions are available
});
</script>
A composition also works fine:
You can also do something like this to show a <div>:
function getCompTable(divId){
var $d = $('#' + divId);
$d.show();
}
USAGE
getCompTable('compListDiv'); // compListDiv - is a div id=""
Yosi Lev

Javascript: How to dynamicly add a number to a variable name?

Say I have to following code:
var numb = $(selector).length;
And now I want to dynamicly make variables based on this:
var temp+numb = ...
How would I be able to do this?
Edit:
I know some of you will tell me to use an array. Normally I would agree but in my case the var is already an array and I rly see no other solution than creating dynamic names.
Variables in Javascript are bound to objects. Objects accept both . and [] notation. So you could do:
var num = 3;
window["foo"+num] = "foobar";
console.log(foo3);
PS - Just because you can do that doesn't mean you should, though.
In global scope (not recommended):
window["temp"+numb]='somevalue;
window.console && console.log(temp3);
In a scope you create - also works serverside where there is no window scope
var myScope={};
myScope["temp"+numb]="someValue";
window.console && console.log(myScope.temp3);

jQuery objects as elements

I see this syntax in some advanced jQuery:
$container
as in:
$input = $container.find('.fn_this_timeline')
EDIT: based on some of the comments below, just to clarify the first instance of '$container' that I can see is created right at the beginning:
init: function($container){
var myThing = this,
$input = $container.find('.fn_do_some_calc'),
$submit = $container.find('.fn_do_some_other_calc'),
defaultValue = parseInt($input.val(), 10);
myThing.$container = $container;
The line above confuses me even more :/
I'm used to using jQuery selectors like this: $('#mySelector').method('etc');
Can someone let me know what the difference is and when it's appropriate or applicable to use the 'shorthand' style?
This isn't some shorthand, this is just the use of Javascript variables. For example, the $container variable was probably declared like this:
var $container = $("#container");
Because it's stored, the element (jQuery object) is "cached" and can be reused without having jQuery go out and re-traverse the DOM to find it again (because it has to every time $("select") is used).
The use of $ at the beginning of the variable name is sometimes helpful for the developer to remember that it holds a jQuery object and not a Javascript element (like what's returned from document.getElementById("container");.
Depending on where your question's init method is, the line myThing.$container = $container; is just setting an object's property "$container" as the value of the $container variable. So the object is probably like:
var myObject = {
init: function () {
// blah blah blah
},
$container: undefined
};
And after running the init method, it will set the "$container" property to something.
This is just to make clear, that the $container variable is already a wrapped jQuery object, instead of e.g. a native DOM node.
For Example you can write:
var container = document.getElementById('item');
var $container = jQuery(container); // or:
var $container = jQuery('#item');
Got the point?
Basically, yes it is shorthand.
For the function you noted:
init: function($container){
var myThing = this,
$input = $container.find('.fn_do_some_calc'),
$submit = $container.find('.fn_do_some_other_calc'),
defaultValue = parseInt($input.val(), 10);
The $ is included so you know to pass a jQuery object into the function. So When you call it, you may do something like this:
init($('#theid'));
As far as the line below:
myThing.$container = $container;
That is just storing your jQuery object as part of your myThing object. One other note, you could do something like $var = 1 and that would be perfectly valid. However usually it is done as a reminder to store a jQuery object.
There is no shortcut method for using jQuery.
It is Standard Method to declare variable in jQuery.
i.e $container = $("#container");
$container is a jquery object.
Understanding: $ indicate that it is jquery object so apply operation on it as appropriate.

How do I optimize this Javascript?

I tried to convert snippet 1 to snippet 2 but this did not work (the text fields did not clear). f3aa and f3bb are each text fields that I need to clear after a sumbit.
Snippet 1
var target=document.getElementById('f3aa');
target.value='';
var target=document.getElementById('f3bb');
target.value='';
Snippet 2
o1('f3aa')=o1('f3bb')='';
Snippet 3
function o1(a)
{
document.getElementById(a);
}
Assuming I've understood your question correctly, you were nearly there:
document.getElementById('f3aa').value = '';
document.getElementById('f3bb').value = '';
In your snippet 2, you are trying to assign an empty string to a DOM element, rather than the value property of that element.
In snippet 1, you assign a DOM element to the target variable, and then assign an empty string to the value property of the target variable. As target contains a DOM element, you assign that string to the value property of that element, which is equivalent to the code I have shown above.
You forgot to include the attribute names from your first snippet in your second:
document.getElementById('f3aa').value='';
document.getElementById('f3bb').value='';
(Note that this isn't really an "optimization" - there will be no noticeable difference in how quickly the two snippets run. Use whichever is more readable.)
X('f3aa').value = X('f3bb').value = '';
where X is your query-by-ID implementation.
Live demo: http://jsfiddle.net/zmr29/
(I wrote a X function in my demo, but I assume that you either use a library or have some other shorthand for DOM queries.)
I think it's illegal to use var to declare a variable more than once in the same scope.
This code is bad:
var test = true;
var test = false;
This code is good:
var test = true;
test = false; // <-- no "var" keyword here

Executing a function by name, passing an object as a parameter

Here's the problem - I know function by name (and that function has already been loaded form an external script), but I don't have an actual function object avail for me to call. Normally I would call eval(function_name + "(arg1, arg2)"), but in my case I need to pass an object to it, not a string.
Simple example:
var div = document.getElementById('myDiv')
var func = "function_name" -- this function expects a DOM element passed, not id
How do I execute this function?
Thanks!
Andrey
Never use eval, it´s evil (see only one letter difference)
You can simply do:
var div = document.getElementById('myDiv');
var result = window[function_name](div);
This is possible because functions are first class objects in javascript, so you can acces them as you could with anyother variable. Note that this will also work for functions that want strings or anything as paramter:
var result = window[another_function_name]("string1", [1, "an array"]);
You should be able to get the function object from the top-level window. E.g.
var name = "function_name";
var func = window[name];
func( blah );

Categories