setting default root element in jquery - javascript

jQuery currently uses window as its default element so any call like $('div') will look for div tags inside window.
Is there any way to change defaults on jQuery like:
$.defaultRoot = $('.anyOtherRootElement');
$('div').text("Hello");
this will select any div inside the elements containing .anyOtherRootElement class.
Thanks in advance
Upate
just an update refining the question a bit more here:
I would like to perform the actions above based on external queries coming from external script which won't know what defaultRoot is so they can still be calling what is supposed to be the current base, so in this instance, I'm afraid adding the a second parameter wouldn't be an option, unfortunately.
And at the same time creating a function which returns defaultRoot.find(el) would prevent me of using first-level methods such $.trim, $.each, etc… so unfortunately that would not be possible as well.

Ideally (for performance reasons) you'd want to use find()
$.defaultRoot.find("div");
Otherwise you can use the 2 argument form that sets a context
$("div", $.defaultRoot);
In general you don't want to do these types of things implicitly since someone else could easily end up thoroughly confused when having to work with your code later. If you want to do it consistently and make it shorter you should create your own function to do so like:
var $s = function(selector) {
return $.defaultRoot.find(selector);
}
and then you'd just be able to use
$s("div")
or you could also do a scoped higher order function with something like
var withScope = function(scope$) {
return function(selector) {
return scope$.find(selector);
}
}
var $s = withScope($.defaultRoot);
$s("div")
If for some reason you really want to screw around with the default state for client code (begging for chaos IMO), you should look at the functional practice: currying.

$('SELECTOR', 'CONTEXT')
You can use context. As in your case $('div', '.anyOtherRootElement')
For more details, visit http://api.jquery.com/jQuery/

Given that you can pass the context as a second argument, you can easily overwrite the $() operator in Javascript with a version which internally calls JQuery using jQuery.noConflict(); and always passes your new root as the second argument.

I don't think jQuery provide such method or variable. But you can pass second parameter in jQuery method to set context.
$.defaultRoot = $('.anyOtherRootElement');
$('div', $.defaultRoot ).text("Hello"); // all div inside $('.anyOtherRootElement')
$('div' ).text("Hello"); //all div inside body tag

Related

Javascript/jQuery variable, what is the proper way to use a var?

I am sorry if this is a dumb or easy question but I am fairly new to Javascript/jQuery. The past month I have really started to delve into the land of scripting and have seen two different, maybe three, ways people use var in Javascript/jQuery.
The way I use a var is like so,
var nav = $('nav');
nav.hide();
A very common way I have seen people use vars,
var nav = $('nav');
$(nav).hide();
From the answers,
var $nav = $('nav');
$nav.hide();
From what I have learned from searching through Google is what you typed inside the variable is saved there to later be used. I then figured if I wrote the $() around the var when I was using it, it would duplicate the $(). Yet both ways seem to work so I know it does not duplicate it and therefore can tell that it is the same thing.
Is there a correct way to use vars or are both equally the same and it doesn't matter?
I apologize again if this is a known answer and will be happy to remove it if someone can show me the original question but I couldn't find anything on it.
A great bit of information from an answer that I didn't mark as the answer but I find to be very important.
var element = document.createElement("div");
$("body").append(element);
$(element).hide();
In the example above, $(element) is necessary, because it takes a DOM
object and converts it to a jQuery selector. jQuery functions only
work on jQuery selectors, so you couldn't simply do element.hide().
$() creates a new jQuery object. If you save a jQuery object to a variable it is pointless to create another jQuery object from it, although it still works. You will often see people wrap variables that were previously created as jQuery objects in $() purely due to bad practice and either forgetting it's already an object...or not understanding what they just created in the first place
Perhaps you may have seen
var $nav = $('nav');
$nav.hide();
Using the $ prefix is a common practice to denote that the variable is a jQuery object for code readability mostly
Both variables store a jQuery object, which has access to jQuery methods. The latter approach unnecessarily tries to re-wrap that jQuery object in another jQuery object. The former approach is 'correct,' in that it's more efficient and less, to be frank, silly.
I've seen this issue in a lot of places. People use a lot of $ when they don't need to. Some use it just as an ornament on their variable name, which adds to the confusion.
First of all, there are no jQuery variables, only JavaScript variables, and as you said, variables store information. When the right hand side begins with $(), you're storing the results of a jQuery function in the variable. In the vast majority of cases, what you'll be storing is called a jQuery selector.
In the case of var nav = $('nav'), what you're storing is a selector representing all the elements in the DOM that are nav tags, i.e. that look like <nav></nav> (or equivalent).
As others already mentioned, the $(nav) is taking the stored selector, and creating a new selector out of it. It accomplishes nothing and is redundant, and is a poor programming practice, even if it is a pervasive one.
However, there is a similar syntax that makes sense:
var element = document.createElement("div");
$("body").append(element);
$(element).hide();
In the example above, $(element) is necessary, because it takes a DOM object and converts it to a jQuery selector. jQuery functions only work on jQuery selectors, so you couldn't simply do element.hide().
As I mentioned at the top, some people also use $ as a decorator on their variable names, e.g. var $selector = $("nav"). The $ on the left hand side means nothing - it's just a character in a variable name, but they use it as a convention to remind themselves that they're storing a jQuery selector. I'd avoid it, simply because it adds to the confusion, but it's out there, so I just wanted to mention it.
var is used to create any kind of variable. Could be var diceRoll = 4 or var myMessage = "Hello!", or anything else.
$ is a function that jQuery provides, which behaves in different ways depending on what you pass to it. For example, if you pass it a string (e.g. 'nav'), it will find every nav element in the document and return a set of jQuery objects (elements) - one for each DOM element it finds. When you say var nav = $('nav');, you are assigning this set of jQuery objects to your nav variable, so you can work with it later. So far so good.
Instead of passing a string to $, you technically could pass jQuery objects back into the $ function, which is what you are doing when you say $(nav).hide();. DOING THIS MAKES LITTLE SENSE - it will just return the same array of jQuery objects, nav, which you put into it in the first place!!
Personally, I like to prefix any variable which holds a jQuery object with a $ sign, i.e. var $nav = $('nav');. This is just a convention that allows me to see at a glance that this variable holds a jQuery object (element) rather than a native DOM element, or integer, or so on. If I ever see $($myVar) in my code, I know it's probably time for bed...
Update: there are other things that it DOES make sense to pass into the $() function, apart from strings. Passing in a DOM element, for example (such as saying $(document)) creates a jQuery object representation of that DOM element, which can be very useful.
All of these answers are pieces to the entire answer . . . let me add yet another piece. :)
As others have said, the $(...) notation is a JQuery function that returns a JQuery object. Depending on what "..." is, determines how that is done.
Some examples:
if you put a selector, such as "div", in there, you will get a JQuery object that contains all of the DOM elements that match the selector pattern . . . in this case, all of the <div> elements.
if you pass a string representation of an HTML element (e.g., "<div></div>"), you will get a JQuery object that points to a newly created <div> element.
if you put a DOM node reference in there (e.g., one created by using document.getElementsByTagName("div")), it will create a JQuery object that points to that node(s) in the reference.
The whole point of this is that JQuery works with JQuery objects, so these various functions help programmers create them.
Now this is where we get to your question . . .
Each time you use $("..."), you are creating a brand new object, so, for example the following code will produce two unique JQuery objects, each of which pointing to the identical DOM elements:
var $firstObject = $("div");
var $secondObject = $("div");
So, if you do a comparison of them (like this ($firstObject === $secondObject)), they will not be seen as equal, because they are not the same object.
Now, let me do a slight variation of your second example to add a little more clarity. If you create a third variable and set it equal to the second one, like this:
var $thirdObject = $secondObject;
. . . you have two elements that are actually pointing to the same JQuery object, so they ARE actually equal (i.e., ($secondObject === $thirdObject) will evaluate as true).
Now finally, what you've shown with this peice of code:
$(nav).hide();
. . . is simply another example of trying to create a JQuery object . . . this time using another JQuery object. Doing this with that third variable that I created above, however, will now break the relationship that it has with the second variable . . . ($secondObject === $($thirdObject)) . . . they are no longer equal, because the two sides of the comparison no longer point to the same object. Much like the comparison between $firstObject and $secondObject from earlier, that comparison is using two unique JQuery objects.
However . . .
Unlike some of the other answers, I would disagree that it is a completely incorrect form of coding . . . while I would never use it in the situation that you provide in your example, passing a JQuery object into the $(...) function is essentially the same thing as using .clone(). The two $bar assignments below are functionally equivalent:
var $foo = $("<div></div>");
var $bar = $($foo);
var $bar = $foo.clone();
The JQuery API even makes the same point (http://api.jquery.com/jQuery/):
Cloning jQuery Objects
When a jQuery object is passed to the $() function, a clone of the object is created. This new jQuery object references the same DOM elements as the initial one.
EDIT :
Out of curiosity, I set up a quick test at jsPerf and the $($foo) approach is pretty significantly faster than .clone() in Firefox, IE9, and Chrome: http://jsperf.com/clone-technique-test
var nav = $('nav');
$(nav).hide();
nav is already a jQuery object so $(nav) is useless.

Dojo - how to use forEach on selected node inside another forEach

In jQuery I would do:
var foo = jQuery("form");
foo.each(function(){
this.find(".required").each(function(){...})
})
This would find every required field in a form currently processed.
But as I have to use Dojo I'm kind of lost. In Dojo you need to use dojo.forEach()
var foo = dojo.query("form");
dojo.forEach(foo, function(self,i){
// And now I have no idea on what to use the forEach.
// The "self" parameter is the form node. So now I
// would need something like `self.forEach`
// But that obviously does not work
}
You just need to do another query again, like you did in the first level. The philosophy in Dojo is that things are usually less "magic" then they are in jQuery.
var forms = dojo.query("form"); //No second argument; Searches whole document
dojo.forEach(forms, function(form){
var requireds = dojo.query(".required", form);//Only search under
// the current form.
dojo.forEach(requireds, function(required){
/* do stuff*/
});
})
I also took the liberty to change the name of the self variable (since unlike jQuery, Dojo does not change the this) and removed the optional i parameter from the forEach.
Note that you could have used the dijit.form.Form and save a lot of hassle for your checks ;)
Also instead of nesting forEach you could have directly used :
dojo.query("form *.required").forEach(function(requiredNode){}, this);
or even (but have not tested yet)
dojo.query("form .required").forEach(function(requiredNode){}, this);

live function with out arguments in jQuery

I wanna select some item by jQuery which has been added after loading page,so I wanna use live() function.I used it before for clicking like following code:
$("selector").live('click')
but now when I wanna use it in another function.
but It will not work with out argument,like it live()
for e.g followin code will alert test (work)
var pos_eq=Math.abs($('.myList').css("left").replace("px","")/$('.myList').children('li').eq(0).css('width').replace("px","")) + 1;
alert("test");
but this will not.
var pos_eq=Math.abs($('.myList').live().css("left").replace("px","")/$('.myList').live().children('li').eq(0).css('width').replace("px","")) + 1;
alert("test");
how can I solve it?
You want a function, not a variable. It looks like you are trying to keep pos_eq up to date after elements have been added to the page. Having a variable auto-update when the DOM changes in the way you are trying to do is not possible with JavaScript. What you can do is use a function instead of a variable. This way whenever the value is accessed you are getting the latest value because it is computed on demand:
function pos_eq() {
var list = $('.myList');
var left = parseInt(list.css("left"));
var width = parseInt(list.children('li').eq(0).css('width'));
return Math.abs(left / width) + 1;
}
I broke your code up into multiple statements to make it more readable. You would use this function the same as you used the variable, but instead add parens to the end to invoke the function:
alert(pos_eq);
alert(pos_eq());
To get a set of objects at the time you need them, just do $("selector"). That will do a query at that time and get the set of objects. There is no need to use .live() in order to query objects on the page. It does not matter whether the objects were part of the original page or were added dynamically later. When you do $("selector"), it will search the contents of the current page and get you the objects that are currently in the page that match the selector.
There is no way to do a live selector query and save it and have it automatically update in jQuery or any other library I know of. The way you solve that issue with a dynamic page is that you just do a new query when you need current results.
The description of live() is: Attach a handler to the event for all elements which match the current selector, now and in the future. It does not give you a live node list despite its name. jQuery does not have any method that returns a live node list(such as those returned by getElementsByTagName etc.) as far as I know.

Using Jquery, call function on selection just once

Say i have a selection of textboxes like this;
var arrayoftextboxes = $('.textbox1, .textbox2, .textbox3');
Is there a way I can call a function on each one in a simpler way than this?
It only needs to be called once.
arrayoftextboxes.each(function(i){foo(arrayoftextboxes[i]);});
I tried
arrayoftextboxes.load(function(){foo(this)});
and
arrayoftextboxes.bind(function(){foo(this)});
but the functions dont seem to be called.
You can do this:
$('.textbox1, .textbox2, .textbox3').each(function() { foo(this); });
The .each() call creates a closure, inside it this refers to the DOM element you're currently on, but it may be better to write what you have as a jQuery plugin. Or, if you just use this inside foo (instead of the DOM element as a parameter) you can shorten it down to:
$('.textbox1, .textbox2, .textbox3').each(foo);
Here's a demonstration of that method
Also, make sure you're running this on document.ready like this:
$(function() {
$('.textbox1, .textbox2, .textbox3').each(foo);
});
Otherwise the DOM elements may not be there to find, making that selector return an empty array (so nothing to run on).

Jquery Replace with return value of Javascript function

OK I am just starting out with jQuery.
I have a page with a table of date-values. Each is wrapped in a tag which I can find with
$('mytag').
<mytag>2009-10-31</mytag>
How, using Jquery, would I
take each of the source values and
pass it to a Javascript function
then replace that source value within the table with the result of the function calculation.
So <mytag>2009-10-31</mytag>would be replaced with <mytag>Very Late</mytag>
I have the Javascript function written. My question is the jQuery syntax to pass the individual value.
Firstly, you will need an element selector, e.g.
$('table')
Will select all <table> elements in your html. So,
$('mytag')
will give you your elements. You will get a jQuery object (not a DOM object) returned. See http://docs.jquery.com/Selectors
Then you want to call a function for each of your elements. For this we call the .each function, and pass the function to call for each element:
$('mytag').each(function(){
//function code goes here
});
(See http://docs.jquery.com/Utilities/jQuery.each)
The function in this case is called an Anonymous function
Then you want to reference the current object in the iteration, so we use the DOM this item and wrap it into a jquery object. To get the value, we use the .text() function (http://docs.jquery.com/Attributes/text)
$('mytag').each(function(){
$(this).text()
});
Note: if it were an input element then you would have used .val()
Passing it to a function is easy:
...
MyFunction($(this).text());
...
The text() function has an overloaded implementation which allows you to set the text if you pass a value:
$(this).text(someval);
So, we can factor this into our code
...
$(this).text(MyFunction($(this).text()));
...
Making our final code block:
$('mytag').each(function(){
$(this).text(MyFunction($(this).text()));
});
$('mytag').each(function (index,tag) {
$(tag).text( myFunc($(tag).text()) );
});
$("mytag").each(function() {
$(this).html("Very Late");
});
$('mytag').each(function() {
$(this).text(someFunction($(this).text()));
});
But, from the sound of your problem, you might be better served by the jQuery-timeago plugin. For your particular case, you'd possibly want to allow dates in the future:
jQuery.timeago.settings.allowFuture = true;
...and you'd want to create your own language override. See the language override examples. You could define several "late" and "very late" values. You can also pass a function to each one to change the value depending on how many days ago a timestamp was.

Categories

Resources