How to condense similar duplicate jquery functions - javascript

Well if my maths is right, my Jquery file is 16 times bigger than it could be.
I am building a tabbed category page which looks like this..
Tab1
cat1
cat2
etc
Tab2
cat1
cat2
etc
All content starts of hidden and then appears when a button in the category header is clicked (also toggling an arrow up/down).
$("#tabName_contentLink_cat1").click(function(){
$("#tabName_contentLink_cat1 > .arrow").toggleClass('greyArrow_down')
.toggleClass('blackArrow_up');
$("#tabName_content_cat1").slideToggle("fast");
});
This code works fine but I've repeated it 16 times!
The only part that varies is the number at the end of '_cat1'.
How can I convert this one piece of code, so that it can be reused 16 times?
I am a newbie, so please keep that in mind.
In my mind; assigning some sought of unique identifier (applicable category number), collecting it in a jQuery variable onClick and then pasted at the end of each _cat'HERE' seams like the way forward. I haven't a clue on how to carry it out though.
Thanks

you could add another class to all cat elements and then use it as selector or you can do what i did. Notice i made the code smaller, efficient. And it does what you wanted by using Function.
addClick(cat1);
addClick(cat2);
addClick(cat3);
addClick(cat4);
function addClick(x) {
$("#tabName_contentLink_"+x).click(function(){
$(this).slideToggle("fast").children(".arrow")
.toggleClass('greyArrow_down blackArrow_up');
});}

What about
$("[id^='tabName_contentLink_cat']").click(function(){
$(this).children(".arrow").toggleClass('greyArrow_down')
.toggleClass('blackArrow_up');
var contentId = this.id.replace(/contentLink/, 'content');
$("#"+ contentId).slideToggle("fast");
});
It's not the most elegant code, but it should work.

Why don't you use a simple for loop?
for(var i = 1; i <= 16; i++){
$("#tabName_contentLink_cat" + i).click(function(){
$("#tabName_contentLink_cat" + i + " > .arrow").toggleClass('greyArrow_down')
.toggleClass('blackArrow_up');
$("#tabName_content_cat" + 1).slideToggle("fast");
});
}
There are other options, but this seems to be the quickest way to make it work without changing too much of the existing code. To make it more generic you can wrap it in a function that receives 'i' as an argument.

Give them all the tabName_contentLink class, then:
$(".tabName_contentLink").click(function(){
$(this).children(".arrow").toggleClass('greyArrow_down')
.toggleClass('blackArrow_up');
$(this).find(".tabName_content").slideToggle("fast");
});
The keyword this allows you to reference the object calling the function, thus relate to a specific object out of a set. It can become a little tricky, but basically - you can use it as described above.

Related

Easy level, selecting elements in DOM, optimization, creating method function

Please, do not laugh, too much. I know jQuery ans JS for a short a while.
1) How can I make this code more efficient? First line is how do I "select" elements, the second, line is how do I prep to "select", next or previous element.
jQuery('code:lt('+((aktywneZdanie+1).toString())+'):gt('+((aktywneZdanie-1).toString())+')').removeClass('class2');}
aktywneZdanie=aktywneZdanie-1
2) I can not create a function which is working as a method. What I meant is how to change:
jQuery('#something').addClass('class1')
.removeClass('class2');
to something like this:
jQuery('#something').changeClasses();
function changeClasses(){
.addclass('class1');
.removeClass('class2');}
For the first one, why do you need a selector like that? couldn't you find something less specific to hook onto? If you must keep it when joining an number and a string, JavaScript will convert the number to string behind the scenes so you don't really need the .toString() and could do the "maths" +/-1 outside of your selector making it more readable.
Edit
In regards to your comment I am not really sure what you mean, you could assign a class to the "post" items and then add the unique id to a data-attribute ID. To make it simpler you could do something like this:
var codeLt = aktywneZdanie + 1,
codeGt = aktywneZdanie - 1;
$('code:lt(' + codeLt + '):gt(' + codeGt +')').removeClass('class2');
End Edit
And the second solution should work, all your doing is passing the dom elements found from your selector into a function as a jQuery "array" in which manipulate to your needs
And for your second question why not just toggle the class on and off? having a default state which reflects class one?
jQuery('#something').toggleClass('uberClass');
Or you can pass your selector to the function
changeClasses(jQuery('#something'));
Then inside you function work on the return elements.
Edit
Your code should work fine, but id suggest checking to make sure you have got and element to work on:
changeClasses(jQuery('#something'));
function changeClasses($element){
if($element.length > 0) {
$element.addClass('class1');
}
}
End Edit
Hope it helps,
1) How can I make this code more efficient? First line is how do I "select" elements, the second, line is how do I prep to "select", next or previous element.
jQuery('code:lt('+((aktywneZdanie+1).toString())+'):gt('+((aktywneZdanie-1).toString())+')').removeClass('class2');}
aktywneZdanie=aktywneZdanie-1
I stoped creating this wierd code like this one above, instead I start using .slice() (do not forget to use .index() for arguments here), .prev(), .next(). Just those three and everything is faster and clearer. Just an example of it below. No it does not do anything logical.
var activeElem = jQuery('code:first');
var old Elem;
jQuery('code').slice('0',activeElem.index()).addClass('class1');
oldElem=activeElem;
activeElem=activeElem.next();
jQuery('code').slice(oldElem.index(),activeElem.index()).addClass('class1');
oldElem.toggleClass('class1');
activeElem.prev().toggleClass('class1');
and the second part
2) I can not create a function which is working as a method. What I meant is how to change:
jQuery('#something').addClass('class1')
.removeClass('class2');
to something like this:
jQuery('#something').changeClasses();
function changeClasses(){
.addclass('class1');
.removeClass('class2');}
This one is still unsolved by me.

Javascript getElementsByTagName("div") what am I labeling?

I'm attempting to set the IDs of a group of divs "galleryboxes" (that are inside a another div, "galleryimages") to be increasing increments, ie. picture1, picture2, etc.
I've seen questions similar to this and tried to get my head around them, but it's difficult. Right now my questions are, what do I get from the second line here? What is 'galleryboxes'? Am I able to cycle through it like an array and label ids like I'm attempting to?
var galleryimages = document.getElementById("galleryimages");
var galleryboxes = galleryimages.getElementsByTagName("div");
var k = 1;
for (var i = 0; i < galleryboxes.length; i++) {
galleryboxes[i].setAttribute=("id", "picture" + k);
k++;
}
The code seems to work, but I don't think I'm actually labeling the divs I want to be labeling; I check what the contents are of "picture1" and it comes up as null (It should be full of a picture and some text).
What do I get from the second line here?
The line in question is this:
var galleryboxes = galleryimages.getElementsByTagName("div");
What this does is provide a live nodeList complete with all the elements with the tag name <div> that are child to the element which the variable galleryimages represents. Note that this is not an actual array, and there are distinguishing characteristics between an array and a nodeList. Most notably, a nodeList does not inherit from the Array constructor, and thus does not contain essential methods like push, pop, and sort common to all arrays.
Am I able to cycle through it like an array and label ids like I'm attempting to?
Yes. This is made easy for us because fortunately nodeLists have a length property. You've already showed how you can loop through them, but the line on which you set the attribute is ill-formed:
galleryboxes[i].setAttribute=("id", "picture" + k);
The equal sign should not be there. This invokes a syntax error. If you take the equal out, the code works fine.
galleryboxes give you a node list which you can iterate through like an array but you have an error here
galleryboxes[i].setAttribute=("id", "picture" + k);
should be
galleryboxes[i].setAttribute("id", "picture" + k);
notice the lack of =
It can also be done using the id property.
galleryboxes[i].id = "picture" + k;
galleryboxes is an array that contains all the divs from within the element "galleryimages"
<html>
<head>
...
<head>
<body>
<div id="galleryimages">
<div class="img_container"></div>
<p>This text will not be in the array...</p>
<div class="img_container"></div>
<div class="img_container"></div>
</div>
</body>
</html>
If your code looked something like above, the variable galleryboxes would only contain the divs.
As for when you check the contents of "picture1" it is probably null, I think you have defined an background image for #picture1 in css, am I right?
Anyways what you should do is too use something like firebug to see the generated DOM. That way you can debug much easier.
You will need to set the attribute directly (galleryboxes[i].id) if you want to access it programatically afterwards (at least if you want it to work consistently). So:
var galleryimages = document.getElementById("galleryimages");
var galleryboxes = galleryimages.getElementsByTagName("div");
for (var i = 0; i < galleryboxes.length; i++) {
galleryboxes[i].id = "picture" + (i + 1);
}
See this jsfiddle for an example.
I know, you are looking for javascript answers here but you can also try this jQuery code, if you want too:
$("#galleryimages > div").each(function(i) {
$(this).prop("id", "picture" + (i + 1));
});​
See just 3 lines of code :)

Using next() x number of times with jQuery

What's an easy way to iterate x number of times using next() (applying the same function each time)?
I am working in Sharepoint and have limited control of the HTML; what I can do is find an element by its ID, track down the closest <td>, hide() it, and then move on to the next one (I don't want all the <td>'s, just about 7 or 8 in a row).
The code below works but it's not that pretty.
$("#my-easily-identifiable-id").closest("td").hide();
$("#my-easily-identifiable-id").closest("td").next().hide();
$("#my-easily-identifiable-id").closest("td").next().next().hide();
$("#my-easily-identifiable-id").closest("td").next().next().next().hide();
[ ... etc ... ]
What's a better way to do this?
Thanks
PS: added a fiddle (genius)
Use .nextAll() + .andSelf() with .slice().
$("#my-easily-identifiable-id").closest("td").nextAll().andSelf().slice(0, 7);
I think a simpler solution than those posted so far would be .nextUntil():
//to get next 8 elements
var i = $('#my-easily-identifiable-id').index();
$('#my-easily-identifiable-id').closest('td').nextUntil('', ':lt(' + (i+8) + ')');
//to get self and next 3
var i = $('#my-easily-identifiable-id').index();
$('#my-easily-identifiable-id').closest('td').nextUntil('', ':lt(' + (i+3) + ')').andSelf();
Grabs all "next" elements until the filter is hit (in this case we choose the next 8 elements). Verified by jsFiddle.
I've not tried it, but perhaps the following might work (I'll test momentarily):
$("#my-easily-identifiable-id").siblings().slice($(this).index(),($(this).index() + 8)).hide();
Tested and verified with a JS Fiddle demo.
Maybe something like this:
$("#my-easily-identifiable-id").closest("td").hide();
$("#my-easily-identifiable-id").closest("td").nextAll().hide();

How to add an item to the top of a dynamic list

Like the title states, does anyone out there have a clear way to implement this type of functionality?
Example:
If you go to http://weewar.com, in their front page you noticed an ajax module that updates every second. However, all of the new items are added to the top of the list. My question is around that very same functionality.
Does anyone have an easy and clear idea as to how one would implement this functionality?
So far I have a method that initially creates the list, then another method is called in an interval that pulls the most recent data from the server..
However, I'm stuck with, how can I add the new dynamic node to the top of the list.
If you can guide me to where I can find this information or give me an idea as to how I can implement this I will be very happy and grateful.
jQuery would make it pretty easy for you. Here's an example:
jQuery
$(document).ready(function(){
$('<div>News 1</div>').prependTo('#textbox');
$('<div>News 2</div>').prependTo('#textbox');
$('<div>News 3</div>').prependTo('#textbox');
$('<div>News 4</div>').prependTo('#textbox');
});
HTML
<div id="textbox"></div>
Output
News 4
News 3
News 2
News 1
As you can see, the news that was added first gets pushed downwards.
If you use jQuery you can use jQuery('#list_ID:first-child').prepend(new_item);
If you want to do it the old fashion way, document.getElementById('list_ID').innerHTML = new_item + document.getElementById('list_ID').innerHTML;
Or you can use a more DOM friendly method:
var list_item = document.createElement('li');
list_item.innerHTML="Some Text"
document.getElementById('list_ID').insertBefore(list_item, document.getElementById('list_ID').firstChild);
One way will be to recreate the list using javascript. Its like list.items=newitem+list.items. Sorry for writing a conceptual pseudo code. If you need to know the exact javascript, please send me a reply/comment.
You can also implement the same in the following way also:
var m =document.getElementById(listElement).options.length;
for(var i = m; i>= 0 ; i = i-1)
document.getElementById(cmbCategory).options[i] = document.getElementById(cmbCategory).options[i-1];
var opt2 = new Option();
opt2.value="100"; /*new value */
opt2.text="New option text";
document.getElementById(listElement).options[document.getElementById(listElement).options.length] = opt2;

jQuery Tips and Tricks

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
Syntax
Shorthand for the ready-event by roosteronacid
Line breaks and chainability by roosteronacid
Nesting filters by Nathan Long
Cache a collection and execute commands on the same line by roosteronacid
Contains selector by roosteronacid
Defining properties at element creation by roosteronacid
Access jQuery functions as you would an array by roosteronacid
The noConflict function - Freeing up the $ variable by Oli
Isolate the $ variable in noConflict mode by nickf
No-conflict mode by roosteronacid
Data Storage
The data function - bind data to elements by TenebrousX
HTML5 data attributes support, on steroids! by roosteronacid
The jQuery metadata plug-in by Filip Dupanović
Optimization
Optimize performance of complex selectors by roosteronacid
The context parameter by lupefiasco
Save and reuse searches by Nathan Long
Creating an HTML Element and keeping a reference, Checking if an element exists, Writing your own selectors by Andreas Grech
Miscellaneous
Check the index of an element in a collection by redsquare
Live event handlers by TM
Replace anonymous functions with named functions by ken
Microsoft AJAX framework and jQuery bridge by Slace
jQuery tutorials by egyamado
Remove elements from a collection and preserve chainability by roosteronacid
Declare $this at the beginning of anonymous functions by Ben
FireBug lite, Hotbox plug-in, tell when an image has been loaded and Google CDN by Colour Blend
Judicious use of third-party jQuery scripts by harriyott
The each function by Jan Zich
Form Extensions plug-in by Chris S
Asynchronous each function by OneNerd
The jQuery template plug-in: implementing complex logic using render-functions by roosteronacid
Creating an HTML Element and keeping a reference
var newDiv = $("<div />");
newDiv.attr("id", "myNewDiv").appendTo("body");
/* Now whenever I want to append the new div I created,
I can just reference it from the "newDiv" variable */
Checking if an element exists
if ($("#someDiv").length)
{
// It exists...
}
Writing your own selectors
$.extend($.expr[":"], {
over100pixels: function (e)
{
return $(e).height() > 100;
}
});
$(".box:over100pixels").click(function ()
{
alert("The element you clicked is over 100 pixels height");
});
jQuery's data() method is useful and not well known. It allows you to bind data to DOM elements without modifying the DOM.
Nesting Filters
You can nest filters (as nickf showed here).
.filter(":not(:has(.selected))")
I'm really not a fan of the $(document).ready(fn) shortcut. Sure it cuts down on the code but it also cuts way down on the readability of the code. When you see $(document).ready(...), you know what you're looking at. $(...) is used in far too many other ways to immediately make sense.
If you have multiple frameworks you can use jQuery.noConflict(); as you say, but you can also assign a different variable for it like this:
var $j = jQuery.noConflict();
$j("#myDiv").hide();
Very useful if you have several frameworks that can be boiled down to $x(...)-style calls.
Ooooh, let's not forget jQuery metadata! The data() function is great, but it has to be populated via jQuery calls.
Instead of breaking W3C compliance with custom element attributes such as:
<input
name="email"
validation="required"
validate="email"
minLength="7"
maxLength="30"/>
Use metadata instead:
<input
name="email"
class="validation {validate: email, minLength: 2, maxLength: 50}" />
<script>
jQuery('*[class=validation]').each(function () {
var metadata = $(this).metadata();
// etc.
});
</script>
Live Event Handlers
Set an event handler for any element that matches a selector, even if it gets added to the DOM after the initial page load:
$('button.someClass').live('click', someFunction);
This allows you to load content via ajax, or add them via javascript and have the event handlers get set up properly for those elements automatically.
Likewise, to stop the live event handling:
$('button.someClass').die('click', someFunction);
These live event handlers have a few limitations compared to regular events, but they work great for the majority of cases.
For more info see the jQuery Documentation.
UPDATE: live() and die() are deprecated in jQuery 1.7. See http://api.jquery.com/on/ and http://api.jquery.com/off/ for similar replacement functionality.
UPDATE2: live() has been long deprecated, even before jQuery 1.7. For versions jQuery 1.4.2+ before 1.7 use delegate() and undelegate(). The live() example ($('button.someClass').live('click', someFunction);) can be rewritten using delegate() like that: $(document).delegate('button.someClass', 'click', someFunction);.
Replace anonymous functions with named functions. This really supercedes the jQuery context, but it comes into play more it seems like when using jQuery, due to its reliance on callback functions. The problems I have with inline anonymous functions, are that they are harder to debug (much easier to look at a callstack with distinctly-named functions, instead 6 levels of "anonymous"), and also the fact that multiple anonymous functions within the same jQuery-chain can become unwieldy to read and/or maintain. Additionally, anonymous functions are typically not re-used; on the other hand, declaring named functions encourages me to write code that is more likely to be re-used.
An illustration; instead of:
$('div').toggle(
function(){
// do something
},
function(){
// do something else
}
);
I prefer:
function onState(){
// do something
}
function offState(){
// do something else
}
$('div').toggle( offState, onState );
Defining properties at element creation
In jQuery 1.4 you can use an object literal to define properties when you create an element:
var e = $("<a />", { href: "#", class: "a-class another-class", title: "..." });
... You can even add styles:
$("<a />", {
...
css: {
color: "#FF0000",
display: "block"
}
});
Here's a link to the documentation.
instead of using a different alias for the jQuery object (when using noConflict), I always write my jQuery code by wrapping it all in a closure. This can be done in the document.ready function:
var $ = someOtherFunction(); // from a different library
jQuery(function($) {
if ($ instanceOf jQuery) {
alert("$ is the jQuery object!");
}
});
alternatively you can do it like this:
(function($) {
$('...').etc() // whatever jQuery code you want
})(jQuery);
I find this to be the most portable. I've been working on a site which uses both Prototype AND jQuery simultaneously and these techniques have avoided all conflicts.
Check the Index
jQuery has .index but it is a pain to use, as you need the list of elements, and pass in the element you want the index of:
var index = e.g $('#ul>li').index( liDomObject );
The following is much easier:
If you want to know the index of an element within a set (e.g. list items) within a unordered list:
$("ul > li").click(function () {
var index = $(this).prevAll().length;
});
Shorthand for the ready-event
The explicit and verbose way:
$(document).ready(function ()
{
// ...
});
The shorthand:
$(function ()
{
// ...
});
On the core jQuery function, specify the context parameter in addition to the selector parameter. Specifying the context parameter allows jQuery to start from a deeper branch in the DOM, rather than from the DOM root. Given a large enough DOM, specifying the context parameter should translate to performance gains.
Example: Finds all inputs of type radio within the first form in the document.
$("input:radio", document.forms[0]);
Reference: http://docs.jquery.com/Core/jQuery#expressioncontext
Not really jQuery only but I made a nice little bridge for jQuery and MS AJAX:
Sys.UI.Control.prototype.j = function Sys$UI$Control$j(){
return $('#' + this.get_id());
}
It's really nice if you're doing lots of ASP.NET AJAX, since jQuery is supported by MS now having a nice bridge means it's really easy to do jQuery operations:
$get('#myControl').j().hide();
So the above example isn't great, but if you're writing ASP.NET AJAX server controls, makes it easy to have jQuery inside your client-side control implementation.
Optimize performance of complex selectors
Query a subset of the DOM when using complex selectors drastically improves performance:
var subset = $("");
$("input[value^='']", subset);
Speaking of Tips and Tricks and as well some tutorials. I found these series of tutorials (“jQuery for Absolute Beginners” Video Series) by Jeffery Way are VERY HELPFUL.
It targets those developers who are new to jQuery. He shows how to create many cool stuff with jQuery, like animation, Creating and Removing Elements and more...
I learned a lot from it. He shows how it's easy to use jQuery.
Now I love it and i can read and understand any jQuery script even if it's complex.
Here is one example I like "Resizing Text"
1- jQuery...
<script language="javascript" type="text/javascript">
$(function() {
$('a').click(function() {
var originalSize = $('p').css('font-size'); // get the font size
var number = parseFloat(originalSize, 10); // that method will chop off any integer from the specified variable "originalSize"
var unitOfMeasure = originalSize.slice(-2);// store the unit of measure, Pixle or Inch
$('p').css('font-size', number / 1.2 + unitOfMeasure);
if(this.id == 'larger'){$('p').css('font-size', number * 1.2 + unitOfMeasure);}// figure out which element is triggered
});
});
</script>
2- CSS Styling...
<style type="text/css" >
body{ margin-left:300px;text-align:center; width:700px; background-color:#666666;}
.box {width:500px; text-align:justify; padding:5px; font-family:verdana; font-size:11px; color:#0033FF; background-color:#FFFFCC;}
</style>
2- HTML...
<div class="box">
Larger |
Smaller
<p>
In today’s video tutorial, I’ll show you how to resize text every time an associated anchor tag is clicked. We’ll be examining the “slice”, “parseFloat”, and “CSS” Javascript/jQuery methods.
</p>
</div>
Highly recommend these tutorials...
http://blog.themeforest.net/screencasts/jquery-for-absolute-beginners-video-series/
Asynchronous each() function
If you have really complex documents where running the jquery each() function locks up the browser during the iteration, and/or Internet Explorer pops up the 'do you want to continue running this script' message, this solution will save the day.
jQuery.forEach = function (in_array, in_pause_ms, in_callback)
{
if (!in_array.length) return; // make sure array was sent
var i = 0; // starting index
bgEach(); // call the function
function bgEach()
{
if (in_callback.call(in_array[i], i, in_array[i]) !== false)
{
i++; // move to next item
if (i < in_array.length) setTimeout(bgEach, in_pause_ms);
}
}
return in_array; // returns array
};
jQuery.fn.forEach = function (in_callback, in_optional_pause_ms)
{
if (!in_optional_pause_ms) in_optional_pause_ms = 10; // default
return jQuery.forEach(this, in_optional_pause_ms, in_callback); // run it
};
The first way you can use it is just like each():
$('your_selector').forEach( function() {} );
An optional 2nd parameter lets you specify the speed/delay in between iterations which may be useful for animations (the following example will wait 1 second in between iterations):
$('your_selector').forEach( function() {}, 1000 );
Remember that since this works asynchronously, you can't rely on the iterations to be complete before the next line of code, for example:
$('your_selector').forEach( function() {}, 500 );
// next lines of code will run before above code is complete
I wrote this for an internal project, and while I am sure it can be improved, it worked for what we needed, so hope some of you find it useful. Thanks -
Syntactic shorthand-sugar-thing--Cache an object collection and execute commands on one line:
Instead of:
var jQueryCollection = $("");
jQueryCollection.command().command();
I do:
var jQueryCollection = $("").command().command();
A somewhat "real" use case could be something along these lines:
var cache = $("#container div.usehovereffect").mouseover(function ()
{
cache.removeClass("hover").filter(this).addClass("hover");
});
I like declare a $this variable at the beginning of anonymous functions, so I know I can reference a jQueried this.
Like so:
$('a').each(function() {
var $this = $(this);
// Other code
});
Save jQuery Objects in Variables for Reuse
Saving a jQuery object to a variable lets you reuse it without having to search back through the DOM to find it.
(As #Louis suggested, I now use $ to indicate that a variable holds a jQuery object.)
// Bad: searching the DOM multiple times for the same elements
$('div.foo').each...
$('div.foo').each...
// Better: saving that search for re-use
var $foos = $('div.foo');
$foos.each...
$foos.each...
As a more complex example, say you've got a list of foods in a store, and you want to show only the ones that match a user's criteria. You have a form with checkboxes, each one containing a criteria. The checkboxes have names like organic and lowfat, and the products have corresponding classes - .organic, etc.
var $allFoods, $matchingFoods;
$allFoods = $('div.food');
Now you can keep working with that jQuery object. Every time a checkbox is clicked (to check or uncheck), start from the master list of foods and filter down based on the checked boxes:
// Whenever a checkbox in the form is clicked (to check or uncheck)...
$someForm.find('input:checkbox').click(function(){
// Start out assuming all foods should be showing
// (in case a checkbox was just unchecked)
var $matchingFoods = $allFoods;
// Go through all the checked boxes and keep only the foods with
// a matching class
this.closest('form').find("input:checked").each(function() {
$matchingFoods = $matchingFoods.filter("." + $(this).attr("name"));
});
// Hide any foods that don't match the criteria
$allFoods.not($matchingFoods).hide();
});
It seems that most of the interesting and important tips have been already mentioned, so this one is just a little addition.
The little tip is the jQuery.each(object, callback) function. Everybody is probably using the jQuery.each(callback) function to iterate over the jQuery object itself because it is natural. The jQuery.each(object, callback) utility function iterates over objects and arrays. For a long time, I somehow did not see what it could be for apart from a different syntax (I don’t mind writing all fashioned loops), and I’m a bit ashamed that I realized its main strength only recently.
The thing is that since the body of the loop in jQuery.each(object, callback) is a function, you get a new scope every time in the loop which is especially convenient when you create closures in the loop.
In other words, a typical common mistake is to do something like:
var functions = [];
var someArray = [1, 2, 3];
for (var i = 0; i < someArray.length; i++) {
functions.push(function() { alert(someArray[i]) });
}
Now, when you invoke the functions in the functions array, you will get three times alert with the content undefined which is most likely not what you wanted. The problem is that there is just one variable i, and all three closures refer to it. When the loop finishes, the final value of i is 3, and someArrary[3] is undefined. You could work around it by calling another function which would create the closure for you. Or you use the jQuery utility which it will basically do it for you:
var functions = [];
var someArray = [1, 2, 3];
$.each(someArray, function(item) {
functions.push(function() { alert(item) });
});
Now, when you invoke the functions you get three alerts with the content 1, 2 and 3 as expected.
In general, it is nothing you could not do yourself, but it’s nice to have.
Access jQuery functions as you would an array
Add/remove a class based on a boolean...
function changeState(b)
{
$("selector")[b ? "addClass" : "removeClass"]("name of the class");
}
Is the shorter version of...
function changeState(b)
{
if (b)
{
$("selector").addClass("name of the class");
}
else
{
$("selector").removeClass("name of the class");
}
}
Not that many use-cases for this. Never the less; I think it's neat :)
Update
Just in case you are not the comment-reading-type, ThiefMaster points out that the toggleClass accepts a boolean value, which determines if a class should be added or removed. So as far as my example code above goes, this would be the best approach...
$('selector').toggleClass('name_of_the_class', true/false);
Update:
Just include this script on the site and you’ll get a Firebug console that pops up for debugging in any browser. Not quite as full featured but it’s still pretty helpful! Remember to remove it when you are done.
<script type='text/javascript' src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'></script>
Check out this link:
From CSS Tricks
Update:
I found something new; its the the JQuery Hotbox.
JQuery Hotbox
Google hosts several JavaScript libraries on Google Code. Loading it from there saves bandwidth and it loads quick cos it has already been cached.
<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load jQuery
google.load("jquery", "1.2.6");
google.setOnLoadCallback(function() {
// Your code goes here.
});
</script>
Or
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript"></script>
You can also use this to tell when an image is fully loaded.
$('#myImage').attr('src', 'image.jpg').load(function() {
alert('Image Loaded');
});
The "console.info" of firebug, which you can use to dump messages and variables to the screen without having to use alert boxes. "console.time" allows you to easily set up a timer to wrap a bunch of code and see how long it takes.
console.time('create list');
for (i = 0; i < 1000; i++) {
var myList = $('.myList');
myList.append('This is list item ' + i);
}
console.timeEnd('create list');
Use filtering methods over pseudo selectors when possible so jQuery can use querySelectorAll (which is much faster than sizzle). Consider this selector:
$('.class:first')
The same selection can be made using:
$('.class').eq(0)
Which is must faster because the initial selection of '.class' is QSA compatible
Remove elements from a collection and preserve chainability
Consider the following:
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>
$("li").filter(function()
{
var text = $(this).text();
// return true: keep current element in the collection
if (text === "One" || text === "Two") return true;
// return false: remove current element from the collection
return false;
}).each(function ()
{
// this will alert: "One" and "Two"
alert($(this).text());
});
The filter() function removes elements from the jQuery object. In this case: All li-elements not containing the text "One" or "Two" will be removed.
Changing the type of an input element
I ran into this issue when I was trying to change the type of an input element already attached to the DOM. You have to clone the existing element, insert it before the old element, and then delete the old element. Otherwise it doesn't work:
var oldButton = jQuery("#Submit");
var newButton = oldButton.clone();
newButton.attr("type", "button");
newButton.attr("id", "newSubmit");
newButton.insertBefore(oldButton);
oldButton.remove();
newButton.attr("id", "Submit");
Judicious use of third-party jQuery scripts, such as form field validation or url parsing. It's worth seeing what's about so you'll know when you next encounter a JavaScript requirement.
Line-breaks and chainability
When chaining multiple calls on collections...
$("a").hide().addClass().fadeIn().hide();
You can increase readability with linebreaks. Like this:
$("a")
.hide()
.addClass()
.fadeIn()
.hide();
Use .stop(true,true) when triggering an animation prevents it from repeating the animation. This is especially helpful for rollover animations.
$("#someElement").hover(function(){
$("div.desc", this).stop(true,true).fadeIn();
},function(){
$("div.desc", this).fadeOut();
});
Using self-executing anonymous functions in a method call such as .append() to iterate through something. I.E.:
$("<ul>").append((function ()
{
var data = ["0", "1", "2", "3", "4", "5", "6"],
output = $("<div>"),
x = -1,
y = data.length;
while (++x < y) output.append("<li>" + info[x] + "</li>");
return output.children();
}()));
I use this to iterate through things that would be large and uncomfortable to break out of my chaining to build.
HTML5 data attributes support, on steroids!
The data function has been mentioned before. With it, you are able to associate data with DOM elements.
Recently the jQuery team has added support for HTML5 custom data-* attributes. And as if that wasn't enough; they've force-fed the data function with steroids, which means that you are able to store complex objects in the form of JSON, directly in your markup.
The HTML:
<p data-xyz = '{"str": "hi there", "int": 2, "obj": { "arr": [1, 2, 3] } }' />
The JavaScript:
var data = $("p").data("xyz");
data.str // "hi there"
typeof data.str // "string"
data.int + 2 // 4
typeof data.int // "number"
data.obj.arr.join(" + ") + " = 6" // "1 + 2 + 3 = 6"
typeof data.obj.arr // "object" ... Gobbles! Errrghh!

Categories