I have selected a control using the following variable
var txt = $("#text1");
Now when I have to handle events on the textbox, do I have to reference it as $(txt) or txt will do
$(txt).keydown(function() {})
or
txt.keydown(function(){})
What is the advantage. Please explain it taking the variable txt as the context.
If txt is already equal to a jquery object, there is no need to use $(txt) as it's just extra processing to return the same thing.
The best approach is to declare your variables so know what they are. Basically, what I'm saying is apply some apps hungarian and prefix your jQuery variables with a $
var $text1 = $("#text1"); // this is a jQuery object
var text1 = $text1[0]; // this is not
A bit more info on Chad's response.
The $() is a short cut to the commonly used function
document.getElementById().
Once you lookup and store the object's value you don't need to look it up again. As Chad mentioned. Ask your self is the variable an object or a name (string), if it's a name you will have to lookup the object.
In my experience I've found that using $(txt) yields more predictable results compared to assigning it as a reference ans using the reference to call the same methods/properties. It's possibly superstition on my part, however a few of us at work have been foiled by using a reference such as txt rather than an implicit $(txt) once txt has been assigned.
Related
My problem is simple:
I want to concatenate a dynamic variable name in a function, so with the name insert in parameter, when I call the function, she concat automatically the string in the new variable name.
Exemple (wrong, I think):
function blockDL(insertName){
return var 'block' + insertName + 'DT'= document.createElement('dt');
};
blockDL('First');
I expect the code return:
blockFirstDT = document.createElement('dt');
Thanks for your help ! =)
What you want is not possible. See "Variable" variables in Javascript? for alternatives of what you can do.
However, "variable variables" is usually a indicator of bad code design. Especially in your case, there is absolutely no reason or benefit to do any of these. Just name the variables blockDT and paraphDT or whatever you want.
The only way you will be able to use a string for a variable name is by placing it as the property of another object. if you want the variable global you could use the window object.
window['block' + insertName + 'DT'] = document.createElement('dt');
that said, you really shouldn't need to and should probably look for other ways of structuring your code.
I don't have an issue, but have had times when I got code that didn't work because there was a jQuery object inside another jQuery object.
So I'm just looking for some clarity on the matter. I've looked for answers on this but haven't found anything.
Can we have:
var element1 = $("some-element");
$(element1).addClass("hidden");
Not sure if I'm just stupid (by no means a JavaScript or jQuery expert. I'm still quite junior), but I just wanted to find out what the deal with this is.
you don't need to use like this you can just use this way
var element1 = $("some-element");
element1.addClass("hidden");
you can you jquery object inside jquery object.
I can for example this, hope to have the same idea with your problem
function buildArray(variable){
if (variable.constructor === Array) return variable;
return toArray(variable);
}
So, when i call buildArray function and pass variable parameter, it was Array. I can call member function of Array from buildArray.
Example:
var arr = [1, 2, 3, 4];
var index = buildArray(arr).indexOf(4);
With your question, can jQuery check with $() function.
I am still confused by the question, even with the fiddle..
Correct me if I am wrong, but assigning the name $element1 to a variable would behave no differently than using the name element1. It is simply used as a naming convention (Hungarian Notation) in order to:
distinguish jQuery objects which are stored in variables from
other variables
But using $("#element1") is effectively selecting HTML element(s) for manipulation.
I have modified your Fiddle example, this would be my approach personally (although to be honest, this question is almost a little too broad and open to interpretation).
If you cache a var:
var something = $('#something');
I have seen that being used later as:
$(something).doAction();
something.doAction();
Is there a difference in using either? I have started using something.doAction() as it looks cleaner and easier to read. But I'd like to know if this could cause any problems?
$(...) returns a jQuery object.
If you put a jQuery object in a variable, the variable will still hold a jQuery object in it when you check on it later, just like anything else you might put in a variable.
No magical gremlins will come and get rid of the jQuery object behind your back.
(unless you accidentally put something else in the variable elsewhere)
This has nothing to do with jQuery. This is just a fundamental of Javascript.
var x = foo();
x.something();
Is of course the same as foo().something(). Go study programming or Javascript until this makes sense.
something is a jQuery object and there is no need to put it in brackets with dollar sign as this: $(something)
jQuery selectors return jQuery objects, which is case here $('#something').
Good naming practice would be to name something as $something, so you know that variable contains jQuery object.
Also good use of $(..) example, would be wrapping html as string to get jQuery object, like this:
$divObject = $('<div>Some text</div>');
$divObject.text(); // value is 'Some text'
There is just hold this a jquery object to use it later or avoid repetition.
var $button = $('#button');
$button.click(function(){
//some code here
});
//now applying some style to it
$button.css({color:"#ccc",background:"#333"});
Or could be replace with
var $button = $('#button').css({color:"#ccc",background:"#333"});
$button.click(function(){
//some code here
});
Or
$('#button').css({color:"#ccc",background:"#333"}).click(function(){
//some code here
});;
Update:
Sometimes if you look for a button, jquery will return you the button, not the object so to edit or do some action you pass it as argument to the jquery constructor.
Here a little example. You are just looking for the button and jquery returns that button but if you need to apply some style,event, etc,etc, you would need to pass it as argument to the jquery contructor ($ or jQuery). And here another without the constructor that does not work
In sample code of the yui library, I see this notation:
var obj = document.getElementById("coffee_msg");
obj.style.display = 'block';
As obj is only used once, I would rather prefer this:
document.getElementById("coffee_msg").style.display = 'block';
Is there any reason why the first notation is used in the yui library and many other places?
Are there incompatibilities with certain browsers?
If you only need to set one property it doesn't matter at all (as long as you do not want to check if the return value is valid before trying to access a property of it).
However, if you have multiple properties you'll want to do the lookup only once (even though an id lookup is extremely fast), so assigning the element to a variable is the way to go in that case.
Of course you could make this even shorter with jQuery: $('#coffee_msg').show()
Also has the advantage that you do not get an error if the element does not exist for some reason. And if you want to set multiple CSS properties etc, you can simply use a function that does that for you with a single call or chain multiple calls to different jQuery methods.
The two different ways work exactly the same. Using a temporary obj variable could be useful to improve readability of the code (but it should be given a name better than obj in that case).
There isn't a "real" reason, just to make the code a little bit more readable.
Just like with:
var myAge = 26;
var myAgeNextYear = myAge + 1;
VS:
var myAgeNextYear = 26 + 1;
My personal preference is to keep a reference to the obj only if I'm using it more than once.
The first option is useful because it improves readability, it also makes the obj variable available immediately for other use. I would use this example personally.
I have been wondering how I can create functions like jQuery. For example: $(ID).function()
Where ID is the id of an HTML element, $ is a function that return the document.getElementById reference of the element "ID" and function is a custom javascript function.
I'm creating a little library which implements some functions. And I want to use that sintax without using jQuery.
Now, my questions are: how I can implement that? What is the name of the tecnique that allow that?
Edit:
What I want to do is this:
HTMLElement.prototype.alertMe = function() {alert(this.value);}
Then, when I call document.getElementById('html_input_id').alertMe(), it must show an alertbox with the input value. But HTMLElement.prototype doesn't work in IE.
$ = function(id) {
return document.getElementById(id);
}
Okay, look, what you're asking has a lot of details and implications. The code for jQuery is open source, you can read it for the details; you'd do well to find a good Javascript book as well, the the O'Reilly Definitive Guide.
$ is just a character for names in JS, so as some of the other answers have shown, there's no reason you can't just write a function with that name:
var $ = function(args){...}
Since everyone and his brother uses that trick, you want to have a longer name as well, so you can mix things.
var EstebansLibrary = function(args){...}
var $ = EstebansLibrary; // make an alias
Since you end up doing different things with the entry point function, you need to know how JS uses arguments -- look up the arguments object.
You'll want to package this so that your internals don't pollute the namespace; you'll want some variant of the module pattern, which will make it something like
var EstebansLibrary = (function(){
// process the arguments object
// do stuff
return {
opname : implementation,...
}
})();
And you'll eventually want to be prepared for inheritance and that means putting those functions into the prototype object.
You can use prototype to assign a new function to the Element prototype.
Element.prototype.testFunction=function(str){alert(str)};
This would provide the function 'testFunction' to all HTML elements.
You can extend any base Object this way, i.e. Array, String etc.
This will work without any plugin at all - although that said I don't think it will work in IE. I believe libraries such as MooTools and jQquery create their own inheritance with DOM elements to ensure cross-browser compatibility, although don't quote me on that.