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
Related
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).
I want to create a plugin that works like so:
var fmatted = $('someString').myFunction();
I've developed jQuery functions in the following manner:
$(someSelector).someFunction();
I know that the selector gets converted to a jQuery object and can be used via this in the plugin. However, if I want to use a string rather than a selector, I'm not sure how I can access that string within my plugin.
Basically, I want to be able to use a plugin to operate on something other than a selector, very much like jQuery's .trim() function, but I can't figure out how to access that within the plugin.
jQuery(selector)[docs] (or $(selector)) is used to create a jQuery object containing elements that match the selector. Although it is possible for you to create a method which ignores the elements and retrieve the original selector, this is not efficient and makes it more difficult to understand what your code is doing.
jQuery.trim()[docs] is not implemented like that. In fact, notice that jQuery.trim() isn't a method on a jQuery object at all! If it were, you'd invoke it like this:
jQuery(" foo ").trim();
Instead, you do this:
jQuery.trim(" fooo ");
.trim() is a method, but not a method of jQuery objects. It's a method of the jQuery constructor function itself (in some languages you would call this a "class method").
You're not creating an object and the argument is never treated as a selector. To add a function like this yourself, all you need to do is this:
jQuery.someFunction = function(message) { alert(message); };
More idiomatically, the default behaviour of the jQuery.extend[docs] will do this for you:
jQuery.extend({someFunction: function(s) { alert(s); } })
That's all you need!
use the selector property:
var jQueryObject = $('my string');
var originalString = jQueryObject.selector;// it'll give you 'my string'
Is this what you're after?
$.fn.makeLower = function() { return this.selector.toLowerCase(); }
$("FOO").makeLower(); // produces "foo"
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.
I mean a wrap function like this:
function $(id) { return document.getElementById(id); }
but in some code like this:
oDiv1 = $("postInfoDiv");
oDiv2 = document.getElementById("postInfoDiv");
alert(oDiv1 == oDiv2); // return false
alert(oDiv1.style); // error
alert(oDiv2.style); // correct
alert(document.getElementById("postInfoDiv").style); // correct
I got strange results as the comments imply.
I thought the first alert should return the true since they are the same dom object.
I thought the second alert should alert something like "object" or "CSS StyleDeclaration" but not "defined".
So what are the problems? Have you ever met this kind of problems?
thanks.
Your $ function is probably being overridden, potentially by a framework.
You should try doing alert( oDiv1.nodeType ) to see if it's a DOM element. alert( oDiv1.length ) to see if it's an empty array because you may be using jQuery on the same page which overrides your $ function.
oDiv1 may be an array-like object containing that item if jQuery is included. oDiv2 is an actual DOM reference. You probably need to compare oDiv1[0] to oDiv1, in which you reference the first element in the array which points to the actual dom element to make a fair comparison.
function $(id){return document.getElementById(id)}
$('content') == document.getElementById('content')
true
The custom $ function will work perfectly but if you're using a framework function it will return that array-like object instead of the DOM element.
You can also rename your function to something like function getID which would be unique and not conflict with framework $s.
My main concern with this is that it will confuse the heck out of someone the first time they read your code, especially if they are used to coding with a JavaScript framework such as jQuery.
For this reason alone I recommend you do not use this particular syntax for your wrap function.
BTW note that even when jQuery is not loaded, Firebug provides its own $ function, which may participate to confusion.
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.