jQuery objects as elements - javascript

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.

Related

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

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.

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

Changing variable name with javascript and jQuery

How to shift between variable names in jQuery and change them?
//predefined variables
var s1='';
var d2='';
//trying to change variables by .attr() parameter but no luck
$('body').on('click','span', function() {
var $(this).parent().attr('data-scan')=$(this).attr('id');
});
HTML
<div data-scan="s1"><span id="banana">Banana</span><span id="apple">Apple</span></div>
<div data-scan="d2"><span id="orange">Orange</span><span id="apple">Apple</span></div>
How can I change specific variables? I do't care about changing attr papameter, all I need is changing predefined global var parameters!
You are using wrong syntax of attr()
Syntax: attr( attributeName , value)
Change
var $(this).parent().attr('data-scan')=$(this).attr('id');
To
$(this).closest('div').attr('data-scan',$(this).attr('id'));
You code would be
Live Demo
$('body').on('click','span', function() {
debugger
$(this).closest('div').attr('data-scan',$(this).attr('id'));
s1=$(this).closest('div').attr('data-scan');
alert(s1);
});​
Firstly, your html for the data-scan attributes is wrong, you have no closing quotes.
Secondly, you can the data() jquery function to access data attributes.
Thirdly, you cannot set values by using the = operator.
You want something like this:
$(this).parent().data('scan', $(this).attr('id'));
or, without the data() function:
$(this).parent().attr('data-scan', $(this).attr('id'));
Here is a working example
To get the value you can do one of the following:
var dataScan = $(this).parent().data('scan');
or
var dataScan = $(this).parent().attr('data-scan');
Your exact requirements for setting a variable based on the data-scan value
Based on your comments and code, I think it has not been clear what you were trying to do. I think I have worked it out though and you want to use the data-scan value to determine which global variable should be set...
//predefined variables
var s1='';
var d2='';
$('body').on('click','span', function() {
var variableType = $(this).parent().data('scan');
var valueToSet = $(this).attr('id');
if(variableType == "s1"){
s1 = valueToSet;
}
else if(variableType == "d2"){
d2 = valueToSet;
}
});
Here is an example of what I think you are trying to do.
However, if you have lots of variables then it is not ideal to use so many if/else statements. So you could use the javascript eval() function.
var variableType = $(this).parent().data('scan');
var valueToSet = $(this).attr('id');
eval("" + variableType + " = '" + valueToSet + "';");
See here for an example
But be careful the your eval code is subjected to user injected values (not that javascript is safe from users anyway)
You're pretty close!
// set
$('#item').attr('data-scan', 'set new value');
// get
var dataScan = $('#item').attr('data-scan');
console.log(dataScan); //=> set new value
Probably best if you use .prop() rather than .attr()
$(this).parent().prop('data-scan', $(this).attr('id') );
As the jQuery api documentation states
As of jQuery 1.6, the .attr() method returns undefined for attributes
that have not been set. In addition, .attr() should not be used on
plain objects, arrays, the window, or the document. To retrieve and
change DOM properties, use the .prop() method.

Javascript class initialization and jQuery DOM in memory

Which is the best way between:
var myClass = function() {
this.myContainer = function(){ return $(".container");}
this.mySubContainer = function(){ return this.myContainer().find(".sub"); }
}
AND
var myClass = function() {
this.myContainer = $(".container");
this.mySubContainer = this.myContainer.find(".sub");
}
Is there any concrete differences?
The memory problem arose when I have seen that my web page, that has enough javascript ( about 150KB of mine + libs ) takes more then 300-400MB of RAM. I'm trying to find out the problem and I don't know if this could be one of them.
function myClass{
this.myContainer = function(){ return $(".container");}
this.mySubContainer = function(){ return this.myContainer().find(".sub"); }
}
Here you will need to call it something like myClassInstance.myContainer() and that means jquery will search for .container element(s) any time you are using that function. Plus, it will create 2 additional closures any time you will create new instance of your class. And that will take some additional memory.
function myClass{
this.myContainer = $(".container");
this.mySubContainer = this.myContainer.find(".sub");
}
Here you will have myContainer pointing to an object which already contains all links to DOM nodes. jQuery will not search DOM any time you use myClassInstance.myContainer
So, second approach is better if you do not want to slow down your app. But first approach could be usefull if your DOM is frequently modified. But I do not beleave you have it modified so frequently that you may need to use second approach.
If there is a single variable you are trying to assign , then the second approach looks cleaner..
Yes they are different.
MODEL 1:
In the first model, myContainer is a function variable.It does not contain the jQuery object.You cannot call any of jQuery's methods on the objet. To actually get the jQuery object you will have to say
var obj = this.myContainer() or this.myContainer.call()
MODEL 2:
The second model stores the actual jQuery object.
try alerting this.myContainer in both models, u will seee the difference.
Yes this is different. after you fix your syntax error :
function myClass(){... // the parentheses
1st
When you create a new object var obj = new myClass(), you are creating two functions, and the jquery object is not returned until you call it
var container = obj.myContainer();
2nd
As soon as the object is initialized the dom is accessed and you have your objects cached for later use;
var container = obj.myContainer;

Set document.getElementById to variable

The following works:
$ = document.form;
x = $.name.value;
This doesn't:
$ = document.getElementById;
x = $("id").value;
Any ideas on why this doesn't work or how to make it so?
The value of this depends on how you call the function.
When you call document.getElementById then getElementById gets this === document. When you copy getElementById to a different variable and then call it as $ then this === window (because window is the default variable).
This then causes it to look for the id in the window object instead of in the document object, and that fails horribly because windows aren't documents and don't have the same methods.
You need to maintain the document in the call. You can use a wrapper functions for this e.g.
function $ (id) { return document.getElementById(id); }
… but please don't use $. It is a horrible name. It has no meaning and it will confuse people who see it and think "Ah! I know jQuery!" or "Ah! I know Prototype" or etc etc.
The context object is different. When you get a reference of a function you're changing that context object:
var john = {
name : "john",
hello : function () { return "hello, I'm " + this.name }
}
var peter = { name : "peter" };
peter.hello = john.hello;
peter.hello() // "hello, I'm peter"
If you want a reference function bound to a specific context object, you have to use bind:
peter.hello = john.hello.bind(john);
peter.hello(); // "hello, I'm john"
So in your case it will be:
var $ = document.getElementById.bind(document);
Don't know what you want to achieve, but this can be made working like this
$ = document.getElementById;
x = $.call(document, "id").value;
because getElementById works only when it is a function of document because of the scope it needs.
But I would recommend #Quentin's answer.
getElementById is a method of the HTMLDocument prototype (of which document is an instance). So, calling the function in global context you will surely get an "Wrong this Error" or something.
You may use
var $ = document.getElementById.bind(document);
but
function $(id) { return document.getElementById(id); }
is also OK and maybe better to understand.
If you are trying to achieve something like that I would suggest using jQuery. Their $ notation is much more powerful than just getting an element by id.
Also, if you are using any platform that already uses the $ as a variable (ASP .Net sometimes uses this) you may have unpredictable result.

Categories