JQuery HowTo
JQuery HowTo
JQUERY HOWTO
B L O G I S A B O UT J Q UER Y J A V A S C R I P T L I B R A R Y. I C O L L EC T J A V A S C R I P T C O D E S N I P P ET S , H O W T O ' S , T I P S A ND
P ER FO R M A NCE O B S ER V A T I O NS .
In this post you will learn how to check if a specific jQuery Globalization plugin
language file is loaded or not. Globalization plugin saves localization data and all
information in jQuery.cultures object. By default English language is added.
So if you add "Inuktitut" language (code iu) the jQuery.cultures object will be
extended and will have jQuery.cultures.iu object in it.
if($.cultures.iu){
// Inuktitut jquery.glob.iu.js lang file is loaded
}else {
// Inuktitut language is not loaded, load it here
}
Some cultures have different alphabet, so they will have that appended in their
language and culture names. For example Inuktitut has Syllabics (iu-Cans ) and
Latin alphabets (iu-Latn ), So you will not be able to check the file existence
with the code above. Here is a syntax to do it:
if($.cultures.iu-Latin){
// Will not work
}
P O S T ED B Y UZ B EK J O N A T 1: 23 P M 0 C O M M ENT S
L A B ELS : B EG I NNER , J Q UER Y, P L UG I N, R EFER ENC E, T I P , T UT O R I A L
W ED NES D A Y, O C T O B ER 6 , 2 0 1 0
function isiPad(){
return (navigator.platform.indexOf("iPad") != -1);
}
You can also detect browser version and some other stuff by parsing user agent
string. Here is an iPad Safari’s user agent string for your reference:
Recently a friend of mine got himself an iPad and I couldn’t not notice how his
internet browsing device preferences are changing (PC & iPad). More and more
people are using hand held devices namely iPad to browse the internet. So it’s
about time to show your iPad visitors some love and display your website
designed specifically for iPad.
http://jquery-howto.blogspot.com/ 1/73
20/01/2011 JQuery HowTo
Let’s see how to do this. There are two way:
Most of the posts on the internet related to iPad user detection are suggesting
and showing you how to redirect (including myself in my previous iPhone & iPod
detection post). However, I would recommend the second option, applying
different CSS file.
You can apply the same technique described in applying different styling for
javascript enabled browser with CSS post and apply different CSS rules for iPad
visitors.
Sidenote: If you decide to redirect iPad users rather than apply different CSS
style rules, than I would recommend using server side detection and redirection.
You can see an example PHP code by David Walsh.
P O S T ED B Y UZ B EK J O N A T 1: 15 P M 0 C O M M ENT S
L A B ELS : CSS , HO W T O , J A V A S CR I P T , J Q UER Y, J Q UER Y M O B I L E, R EFER EN C E, T I P
T U ES D A Y, O C T O B ER 5 , 2 0 1 0
I will be post some jQuery globalization plugin tutorials in coming days, so bare
with me.
Before we jump into licensing and support issues, first things are first. What’s
up with the name? It’s confusing! When did we start calling localization (l10n) a
globalization?! I haven’t seen any g12n abbreviations lately, have you? When I
first came across it, I thought it was some wicked jQuery solution to "global
variables are evil" idea or solution to some other problem that I am not even
familiar with :) Don’t you agree, it’s confusing a bit.
So, there you go. One little improvement: "Don’t confuse, rename it!"
Before we talk about the jQuery globalization plugin license, let me mention that
this plugin is now officially supported by jQuery Project. Which means that it
will be under continues improvement by jQuery core team and will be compatible
with the future jQuery and jQuery UI releases. Also globalization plugin will
become a part of the jQuery UI project.
Now, the legal stuff – the license. Because jQuery project accepted the
globalization plugin as officially supported (and of course because Microsoft
agreed to its terms) jQuery Globalization plugin is distributed under the same
license as core jQuery.js. So you are safe to do pretty much anything.
After playing with the plugin for a while I realized that it does not do any DOM
manipulations and you certainly don’t expect any animations. So what’s the
point of having it as jQuery plugin and not a general JavaScript
globalization/localization library? This way a larger community could benefit from
it. I guess it was more of marketing decision rather than technical.
P O S T ED B Y UZ B EK J O N A T 3: 17 P M 0 C O M M ENT S
L A B ELS : I NS I G HT S , JQ UER Y, J Q UER Y UI , NEW S , P LUG I N
S A T UR D A Y, S EP T EM B ER 2 5 , 2 0 1 0
http://jquery-howto.blogspot.com/ 2/73
20/01/2011 JQuery HowTo
Russian CDN for jQuery
I recently discovered that the biggest Russian search engine Yandex (yeah, it’s
bigger than Google in Russia) is using jQuery on its home page. It also hosts all
previous jQuery versions on it’s fast gzip enabled servers just like Google and
MIcrosoft do.
Because most of the Russian internet users have visited Yandex already, they
already have it in their browser cache. I also did route tracing from Russian server
to Google CDN servers and I was directed to the server in California, USA and
pining the local Russian CDN server was at least 3 times faster.
Anyway, if you decide to use Russian CDN to host your jQuery files here are the
links:
Minified versions
http://yandex.st/jquery/1.2.6/jquery.min.js
http://yandex.st/jquery/1.3.0/jquery.min.js
http://yandex.st/jquery/1.3.1/jquery.min.js
http://yandex.st/jquery/1.3.2/jquery.min.js
http://yandex.st/jquery/1.4.0/jquery.min.js
http://yandex.st/jquery/1.4.1/jquery.min.js
http://yandex.st/jquery/1.4.2/jquery.min.js
jQuery UI links
http://yandex.st/jquery-ui/1.8.2/jquery-ui.min.js
Hosted versions
1.8.2, 1.8.1, 1.8.0, 1.7.3, 1.7.2, 1.7.1, 1.7.0, 1.6.0
Language files
http://yandex.st/jquery-ui/1.7.2/i18n/ui.datepicker-ru.js
http://yandex.st/jquery-ui/1.8.0/i18n/jquery.ui.datepicker-ru.min
.js
P O S T ED B Y UZ B EK J O N A T 10: 19 A M 2 C O M M ENT S
L A B ELS : JQ UER Y, L I NK , P ER FO R M A NC E, R ES O UR C E
The latest buzz around jQuery is upcoming jQuery mobile – support for mobile
devices. Current jQuery core work fine on iPhone and iPod touch browsers and
most of us have created a mobile version of our websites, developed or converted
websites for others. Basically, jQuery is already being used on iPhone and iPod
touch devices. Without any further ado…
http://jquery-howto.blogspot.com/ 3/73
20/01/2011 JQuery HowTo
You might wonder why do we even need to detect if our website is ran on iPhone
Safari or normal desktop Safar if jQuery works fine on both. Well, there are Safari
specific CSS features that you might want to utilize and you need to know if the
current browser is Safari, then you may also want to consider reducing resource
consuming features like animations for iPhone version of your site.
For example: if your website is www.example.com and you have a mobile version
at mob.example.com, then put the following script to your www.example.com.
/*
User Agent String for iPhone
Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/42
0+ (KHTML, like Gecko)
Version/3.0 Mobile/1A543a Safari/419.3
As final words, I would like to remind you that sometimes your visitors would not
like to be redirected to mobile versions of your websites. That’s why your mobile
version should always include a link to your non-mobile website. The above
scripts can be rewrote to check if user has chosen not to be redirected. Either
set cookie or a URL parameter.
P O S T ED B Y UZ B EK J O N A T 10: 36 A M 0 C O M M ENT S
L A B ELS : HO W T O , J A V A S CR I P T , J Q UER Y, J Q UER Y M O B I L E, R EFER ENC E, T I P
http://jquery-howto.blogspot.com/ 4/73
20/01/2011 JQuery HowTo
W ED NES D A Y, S EP T EM B ER 2 2 , 2 0 1 0
The jQuery Mobile source will not be in a separate jquery.mobile.js file. It will
be right in the jQuery core. This means that jQuery team is fixing and improving
jQuery core so that it works nicely in all major mobile phones and devices.
By the way, if you want to keep track of the jQuery mobile source code and be
the first one to download it, when it is available, you should watch jQuery on
GitHub.
The big part of the upcoming jQuery mobile is new UI components that work and
render nicely in all mobile devices and degrade gracefully. So, keep an eye on
jQuery UI as well. Here is the jQuery UI GitHub page.
P O S T ED B Y UZ B EK J O N A T 10: 30 A M 0 C O M M ENT S
L A B ELS : I NS I G HT S , JQ UER Y, J Q UER Y M O B I L E, J Q UER Y UI , NEW S
T U ES D A Y, S EP T EM B ER 2 1 , 2 0 1 0
I will try to keep this post short and will not explain what cookies are and how to
eat them. There are plenty of articles covering it already.
function setCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.len
gth,c.length);
}
return null;
}
function deleteCookie(name) {
setCookie(name,"",-1);
}
/*
Changed function names from readCookie(), createCookie()
and eraseCookie() to getCookie(), setCookie() and
deleteCookie().
*/
Here is an example that shows you how to use those functions in your javascript
to create, edit and delete your cookies:
http://jquery-howto.blogspot.com/ 5/73
20/01/2011 JQuery HowTo
setCookie('myCookie', 'myValue', 1);
// Get my cookie
getCookie('myCookie');
// Delete/erase my cookie
deleteCookie('myCookie');
These 3 javascript functions are all you need to manage your cookies, but if you
want to do it in “jQuery style” than you can use jQuery Cookie plugin or it’s
improved version.
// Setting a cookie
$.cookie('myCookie':'myValue');
// Get a cookie
$.cookie('myCookie');
// Delete a cookie
$.cookie('myCookie', null);
With an improved version of the plugin you can set and get multiple cookies in
one call. The improved version of the jQuery Cookie pluin only adds few additional
bytes. So it really worth it.
P O S T ED B Y UZ B EK J O N A T 3: 04 P M 0 C O M M ENT S
L A B ELS : B EG I NNER , J A V A SCR I P T , J Q UER Y, P LUG I N
S UN D A Y, A UG US T 2 9 , 2 0 1 0
jQuery Mobile
jQuery Mobile is an attempt to create a javascript framework that would work on
all major mobile browsers. In this post I will try to lay down all the facts that I
could find about jQuery Mobile, so that you are up to date.
jQuery team has mentioned that they were planning and started to work on
jQuery for Mobile devices when they announced jQuery 1.4. John Resig said that
they already had different mobile devices from sponsor for testing purposes.
Anyway, jQuery Mobile is officially announced now, but there is a very little
information about it.
That’s all I could find on jQuery Mobile for now. Subscribe to my RSS or follow
me on Twitter to stay updated about news related to jQuery Mobile.
P O S T ED B Y UZ B EK J O N A T 9: 38 A M 0 C O M M ENT S
L A B ELS : JQ UER Y M O B I LE, L I NK , NEW S
W ED NES D A Y, A U G U S T 1 1 , 2 0 1 0
http://jquery-howto.blogspot.com/ 6/73
20/01/2011 JQuery HowTo
elements
jQuery.live() function was introduced in jQuery version 1.3. It makes it easy
to dynamically bind events to DOM elements that have not yet been created. In
other words, it helps you to easily attach events to AJAX loaded elements that
match your criteria.
NOTE:
If for some reason you are using old versions of jQuery, prior to 1.3, you will need
to use event delegation or another method as they are described in my previous
post named “How to bind events to AJAX loaded elements in jQuery 1.2.x”.
You can also pass in additional data to your events to overcome some issues
caused by closure. This was introduced in jQuery 1.4. Also, it worth mentioning
that data is passed when the binding is made. Keep this in mind when you pass
in dynamic data.
NOTE:
Some events were not supported cross browser in jQuery 1.3. Events like
submit were supported in Firefox only. This is resolved in jQuery 1.4. Other
methods that were not supported cross browser in jQuery 1.3 include: focusin ,
focusout , mouseenter , mouseleave , etc.
NOTE:
.live() function also works with custom events.
http://jquery-howto.blogspot.com/ 7/73
20/01/2011 JQuery HowTo
// Remove ALL events attached using .live()
$('.mySelector').die();
function myFunk(){
alert("Clicked!");
}
If you have any questions or need any help, you can ask me on Facebook.
P O S T ED B Y UZ B EK J O N A T 10: 33 A M 0 C O M M ENT S
L A B ELS : A JA X , B EG I NN ER , EV ENT S , J Q UER Y, P ER FO R M A NC E, R EFER ENC E
M O ND A Y, J UL Y 1 2 , 2 0 1 0
// Alternatively
jQuery.ui.version
if($.ui.version){
// jQuery UI is loaded
}
P O S T ED B Y UZ B EK J O N A T 12: 10 A M 2 C O M M ENT S
L A B ELS : B EG I NNER , HO W T O , JQ UER Y UI , T I P
M O ND A Y, A P R I L 1 9 , 2 0 1 0
Here is an example:
By default the plugin will return URL of the video screenshot (480×360). If you
just need a video thumbnail (120×90) pass an optional second parameter
"small ".
http://jquery-howto.blogspot.com/ 8/73
20/01/2011 JQuery HowTo
P O S T ED B Y UZ B EK J O N A T 5: 51 A M 1 C O M M ENT S
L A B ELS : JQ UER Y, P L UG I N
S UN D A Y, F EB R U A R Y 2 8 , 2 0 1 0
In this release, I fixed a little bug that would not allow you request Tweets without
number of posts like this:
You can specify the number of posts you want to be fetched like so:
Also, I created a simple demo page for the plugin here. Please visit and see the
code and also note that with this plugin you can create a custom Twitter badge
with no design limitations!
P O S T ED B Y UZ B EK J O N A T 6: 10 A M 0 C O M M ENT S
L A B ELS : JQ UER Y, L I NK , NEW S , P LUG I N
T H UR S D A Y, F EB R UA R Y 1 8 , 2 0 1 0
function myFunction() {
...
}
If you want to publish your jQuery plugins following jQuery core code writing
guidelines is a good idea. This would make your code more easier to read to
other jQuery developers. Follow the link above and go through the guidelines (it
will only take a few minutes). The guidelines page shows gives you general
guidelines, but I went through the jQuery core code and found several
additional ones. I lay they out at the end of this post.
In short, the official guidelines are as follows: (Taken from official docs)
http://jquery-howto.blogspot.com/ 9/73
20/01/2011 JQuery HowTo
3. Use strict equality checks whenever possible (===)
4. Braces should always be used on blocks and statements should not be
on the same line as a conditionals:
// NO:
if ( true ) blah();
// YES:
if ( true ) {
blah();
}
Now let’s see other additional rules that I could spot reading the jQuery core
code.
1. The first thing that I noticed was multiline comments did not use common
/* comment */ syntax. In jQuery core all multiline comments use line
comment syntax // comment .
2. Local variables are declared and initialized on one line just below the
function declaration with no extra line:
function someFunction () {
var target = arguments[0] || {}, i = 1, name;
{
myName: "",
myFunc: function( ) {}
}
4. All strings are in double quotes " " , not single quotes ' ' :
P O S T ED B Y UZ B EK J O N A T 12: 06 P M 2 C O M M ENT S
L A B ELS : B EG I NNER , I NSI G HT S , J Q UER Y, R EFER ENC E, T I P
S A T UR D A Y, F EB R UA R Y 1 3 , 2 0 1 0
http://jquery-howto.blogspot.com/ 10/73
20/01/2011 JQuery HowTo
with iframes using jQuery. This post simply shows you how to dynamically
create iframes using jQuery and JavaScript and serves as a note.
Creating iframe is similar to creating any DOM element. All you need to do is to
use jQuery factory like this:
Don’t forget that the iframe source is just an iframe’s attribute. So you can set
that just like any other attribute.
UPDATE:
As BinaryKitten point’s out below, with jQuery 1.4 you can do it using the
following syntax:
P O S T ED B Y UZ B EK J O N A T 10: 19 A M 6 C O M M ENT S
L A B ELS : B EG I NNER , D O M , HO W T O , HT M L , M A NI P UL A T I O N, R EFER EN C E
T H UR S D A Y, J A NUA R Y 1 4 , 2 0 1 0
Also, if you want to learn more about what is new in jQuery 1.4 then you might
find the following resources useful:
1. 14 Days of jQuery
2. Official jQuery Blog
3. jQuery 1.4 Cheatsheet
4. jQuery on Tweeter
If you have any more resources related to jQuery 1.4 please share in comments.
P O S T ED B Y UZ B EK J O N A T 6: 49 A M 5 C O M M ENT S
L A B ELS : JQ UER Y, L I NK , NEW S , R ES O UR C E
FR I DA Y, NO V EM B ER 6, 2009
http://jquery-howto.blogspot.com/ 11/73
20/01/2011 JQuery HowTo
(besides the internet itself). When we mention Web2.0 first things that come into
our minds are AJAX, rounded corners, clean and light layouts and of course RSS
feeds. Nowadays, you either provide an RSS feed or consume it in your web app
using AJAX/JavaScript.
The only bad thing is that you can not request cross-site content with AJAX
requests. Requesting someone else’s RSS in your JavaScript falls into this
limitations. One way to overcome this problem is to apply a server-side proxy
workaround. However, there is even better solution and workaround – RSS to
JSON conversion.
Basically, using Google Feeds API service and jQuery plugin you can request
and get any RSS from different domain converted into the JSON object in your
javascript.
<script src="jquery.js"></script>
<script src="jquery.jgfeed.js"></script>
<script>
$.jGFeed('http://twitter.com/statuses/user_timeline/26767000.rss'
,
function(feeds){
// Check for errors
if(!feeds){
// there was an error
return false;
}
// do whatever you want with feeds here
for(var i=0; i<feeds.entries.length; i++){
var entry = feeds.entries[i];
// Entry title
entry.title;
}
}, 10);
</script>
In order to have universal client-side RSS to JSON converter you first need to
include jquery.js and Google Feeds API plugin jquery.jgfeed.js . Then use
jQuery plugin and Google Feeds API to get reliable and fast RSS to JSON(P)
converter.
The code above gets Twitter RSS feeds in JSON format and does whatever it
wants with it. Great workaround isn’t it :)
To see jGFeed() ’s argument lists and how to use it please read this post.
P O S T ED B Y UZ B EK J O N A T 8: 13 A M 9 C O M M ENT S
L A B ELS : A JA X , HO W T O , J Q UER Y, JS O N, P L UG I N, T I P , T O O L S, W O R K A R O UND
T U ES D A Y, NO V EM B ER 3 , 2 0 0 9
Let’s say our custom jQuery extension gets data by making some AJAX request.
$.extend({
myFunc : function(someArg){
var url = "http://site.com?q=" + someArg;
$.getJSON(url, function(data){
});
}
});
http://jquery-howto.blogspot.com/ 12/73
20/01/2011 JQuery HowTo
What is bad in this jQuery code is that the callback function is defined and
hardcoded right in the plugin itself. The plugin is not really flexible and its user
will have to change the plugin code, which is bad!
So the solution is to define your own custom callback function argument. Here is
how it is done:
$.extend({
myFunc : function(someArg, callbackFnk){
var url = "http://site.com?q=" + someArg;
$.getJSON(url, function(data){
});
}
});
$.myFunc(args, function(){
// now my function is not hardcoded
// in the plugin itself
});
The above code shows you how to create a callback function for AJAX load, but if
you want to create a simple callback function for your jQuery plugin, for
example the one that executes on your own custom events. To achive this you
can do the following:
$.extend({
myFunc : function(someArg, callbackFnk){
// do something here
var data = 'test';
$.myFunc(someArg, function(arg){
// now my function is not hardcoded
// in the plugin itself
// and arg = 'test'
});
P O S T ED B Y UZ B EK J O N A T 7: 54 A M 5 C O M M ENT S
L A B ELS : A JA X , B EG I NN ER , EV ENT S , HO W T O , I NSI G HT S , J Q UER Y, P L UG I N, R EFER ENC E,
T UT O R I A L, W O R K A R O UND
S UN D A Y, NO V EM B E R 1 , 2 0 0 9
However, it was not very handy for creating your own and custom Twitter Badge.
Well, right until now! I updated jTwitter plugin and now it can get you not only
Twitter user details but also any number of that user’s latest posts. And yes, all
these you can do without any Twitter API keys.
http://jquery-howto.blogspot.com/ 13/73
20/01/2011 JQuery HowTo
numberOfPosts - Number of user posts to get
callbackFunction - callback function to call
when data is loaded */
Let’s see a real life example now. In example below, we are fetching latest 3
posts of jQueryHowto Twitter user and appending those post messages to some
DOM element with an id=tweets .
$.jTwitter('jQueryHowto', 3, function(posts){
for(var i=0; i<posts.length; i++){
$('#tweets').append(posts[i].text);
}
});
To get a clear view of what data is returned and available in your callback function
here is an example of returned JSON data object:
/*
Example of returned object
*/
[
{
'in_reply_to_user_id':null,
'in_reply_to_screen_name':null,
'source':'web',
'created_at':'Fri Sep 18 06:11:15 +0000 2009',
'truncated':false,
'user':{
'profile_background_color':'9ae4e8',
'description':'jQuery and JavaScript howtos, tutorials, hac
ks, tips and performanace tests. Ask your jQuery questions here..
.',
'notifications':false,
'time_zone':'Central Time (US & Canada)',
'url':'http://jquery-howto.blogspot.com',
'screen_name':'jQueryHowto',
'following':true,
'profile_sidebar_fill_color':'e0ff92',
'created_at':'Thu Mar 26 14:58:19 +0000 2009',
'profile_sidebar_border_color':'87bc44',
'followers_count':2042,
'statuses_count':505,
'friends_count':1015,
'profile_text_color':'000000',
'protected':false,
'profile_background_image_url':'http://s.twimg.com/a/125320
9888/images/themes/theme1/bg.png',
'location':'',
'name':'jQuery HowTo',
'favourites_count':15,
'profile_link_color':'0000ff',
'id':26767000,
'verified':false,
'profile_background_tile':false,
'utc_offset':-21600,
'profile_image_url':'http://a3.twimg.com/profile_images/110
763033/jquery_normal.gif'
},
'in_reply_to_status_id':null,
'id':4073301536,
'favorited':false,
'text':'Host jQuery on Microsoft CDN servers http://retwt.me/
2N3P'
},
{
'in_reply_to_user_id':null,
'in_reply_to_screen_name':null,
'source':'<a href="http://www.hootsuite.com" rel="nofollow">H
http://jquery-howto.blogspot.com/ 14/73
20/01/2011 JQuery HowTo
ootSuite</a>',
'created_at':'Thu Sep 17 17:20:21 +0000 2009',
'truncated':false,
'user':{
'profile_sidebar_fill_color':'e0ff92',
'description':'jQuery and JavaScript howtos, tutorials, hac
ks, tips and performanace tests. Ask your jQuery questions here..
.',
'friends_count':1015,
'url':'http://jquery-howto.blogspot.com',
'screen_name':'jQueryHowto',
'following':false,
'profile_sidebar_border_color':'87bc44',
'favourites_count':15,
'created_at':'Thu Mar 26 14:58:19 +0000 2009',
'profile_text_color':'000000',
'profile_background_image_url':'http://s.twimg.com/a/125314
1863/images/themes/theme1/bg.png',
'profile_link_color':'0000ff',
'protected':false,
'verified':false,
'statuses_count':504,
'profile_background_tile':false,
'location':'',
'name':'jQuery HowTo',
'profile_background_color':'9ae4e8',
'id':26767000,
'notifications':false,
'time_zone':'Central Time (US & Canada)',
'utc_offset':-21600,
'followers_count':2038,
'profile_image_url':'http://a3.twimg.com/profile_images/110
763033/jquery_normal.gif'
},
'in_reply_to_status_id':null,
'id':4058535256,
'favorited':false,
'text':'jQuery Tip: Don't forget that you can load jQuery UI
files from Google servers as well http://bit.ly/fJs2r'
},
{
'in_reply_to_user_id':null,
'in_reply_to_screen_name':null,
'source':'web',
'created_at':'Thu Sep 17 05:44:30 +0000 2009',
'truncated':false,
'user':{
'profile_sidebar_fill_color':'e0ff92',
'description':'jQuery and JavaScript howtos, tutorials, hac
ks, tips and performanace tests. Ask your jQuery questions here..
.',
'friends_count':1015,
'url':'http://jquery-howto.blogspot.com',
'screen_name':'jQueryHowto',
'following':true,
'profile_sidebar_border_color':'87bc44',
'favourites_count':15,
'created_at':'Thu Mar 26 14:58:19 +0000 2009',
'profile_text_color':'000000',
'profile_background_image_url':'http://s.twimg.com/a/125304
8135/images/themes/theme1/bg.png',
'profile_link_color':'0000ff','protected':false,
'verified':false,
'statuses_count':503,
'profile_background_tile':false,
'location':'',
'name':'jQuery HowTo',
'profile_background_color':'9ae4e8',
'id':26767000,
'notifications':false,
'time_zone':'Central Time (US & Canada)',
http://jquery-howto.blogspot.com/ 15/73
20/01/2011 JQuery HowTo
'utc_offset':-21600,
'followers_count':2035,
'profile_image_url':'http://a3.twimg.com/profile_images/110
763033/jquery_normal.gif'
},
'in_reply_to_status_id':null,
'id':4048429737,
'favorited':false,
'text':'Added a demo page for my 'How to bind events to AJAX
loaded elements' blog post as requested by users http://bit.ly/q2
tWe'
}
]
As you can see, you get not only user’s latest posts but also all the information
about posts and user who posted it on Twitter.
P O S T ED B Y UZ B EK J O N A T 11: 08 P M 9 C O M M ENT S
L A B ELS : A JA X , J Q UER Y, J S O N, NEW S, P L UG I N, R EFER ENC E
T U ES D A Y, O C T O B ER 2 0 , 2 0 0 9
This function takes two parameters: integer value for password length and
optional boolean value true if you want to include special characters in your
generated passwords.
http://jquery-howto.blogspot.com/ 16/73
20/01/2011 JQuery HowTo
password(12, true);
//Outputs: C}4_ege!P&#M
// How to use
$.password(8);
$.password(12, true);
P O S T ED B Y UZ B EK J O N A T 6: 37 A M 2 C O M M ENT S
L A B ELS : JA V A S CR I P T , JQ UER Y, S EC UR I T Y, T O O LS
T H UR S D A Y, S EP T EM B ER 1 7 , 2 0 0 9
Anyway, intention of this post is not to discuss why Microsoft introduced its own
jQuery hosted servers, bu to share links to Microsoft hosted jQuery library. Here
we go:
jQuery 1.4.x
http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.js
http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js
http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.1-vsdoc.js
jQuery 1.3.2
http://ajax.Microsoft.com/ajax/jQuery/jquery-1.3.2.js
http://ajax.Microsoft.com/ajax/jQuery/jquery-1.3.2.min.js
http://ajax.Microsoft.com/ajax/jQuery/jquery-1.3.2-vsdoc.js
http://ajax.Microsoft.com/ajax/jQuery/jquery-1.3.2.min-vsdoc.js
Currently Microsoft AJAX CDN hosts only jQuery version 1.3.2, but they will add
more releases in the future. To see a full list of the JavaScript libraries and their
URLs that are already hosted on CDN cache go here: www.asp.net/ajax/cdn
P O S T ED B Y UZ B EK J O N A T 11: 05 P M 2 C O M M ENT S
L A B ELS : A JA X , J A V A S CR I P T , J Q UER Y, L I NK , NEW S, P ER FO R M A NC E
http://jquery-howto.blogspot.com/ 17/73
20/01/2011 JQuery HowTo
W ED NES D A Y, S EP T EM B ER 1 6 , 2 0 0 9
The function returns an array/object with your URL parameters and their values.
For example, consider we have the following URL:
http://www.example.com/?me=myValue&name2=SomeOtherValue
{
"me" : "myValue",
"name2" : "SomeOtherValue"
}
To make the script syntax to look more jQuery like syntax I rewrote it as an
extension for jQuery:
$.extend({
getUrlVars: function(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.
indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
getUrlVar: function(name){
return $.getUrlVars()[name];
}
});
Now, if you include the above code in your javascript file, you can get URL
parameter values in the following way:
http://jquery-howto.blogspot.com/ 18/73
20/01/2011 JQuery HowTo
// Get object of URL parameters
var allVars = $.getUrlVars();
That’s it! You might also find the following jQuery related articles on this blogs
interesting:
P O S T ED B Y UZ B EK J O N A T 12: 59 A M 13 C O M M ENT S
L A B ELS : B EG I NNER , HO W T O , HT M L , J A V A S C R I P T , JQ UER Y, T I P , W O R K A R O UND
T U ES D A Y, A UG US T 1 1 , 2 0 0 9
If you have a QR code reader on your mobile take a picture of it and it will open
this website. Cool ha?!
Anyway, there are plenty of free online QR code generator sites, but no
JavaScript and jQuery plugins/functions. So, I quickly searched for a free online
QR code generator sites with “friendly” URL’s and put together a javascript and
jQuery functions that generate QR barcode image’s URL for passed URLs. I used
Kaywa & University of Bath services.
// JavaScript function
function qrcode(url, size){
if(typeof(size) == 'undefined') size = 8;
return 'http://qrcode.kaywa.com/img.php?s='+size+'&d='+url;
}
qrcode('http://jquery-howto.blogspot.com');
// jQuery plugin
(function ($) {
$.fn.qrcode = function(url, size) {
if(typeof(size) == 'undefined') size = 8;
return 'http://qrcode.kaywa.com/img.php?s='+size+'&d='+url;
}
})(jQuery);
$().qrcode('http://www.google.com');
The code above utilizes Kaywa’s online QR code generator. You can specify
http://jquery-howto.blogspot.com/ 19/73
20/01/2011 JQuery HowTo
image site as the second argument to the function. The size argument mut be
between 1 and 40 and the generated image will 32 x your argument.
// JavaScript function
function qrcode(url){
return 'http://go.bath.ac.uk/qr/download?DATA='+url;
}
qrcode('http://jquery-howto.blogspot.com');
// jQuery plugin
(function ($) {
$.fn.qrcode = function(url) {
return 'http://go.bath.ac.uk/qr/download?DATA='+url;
}
})(jQuery);
$().qrcode('http://www.google.com');
NOTE: You can encode plain text messages. They are not limited to URLs...
P O S T ED B Y UZ B EK J O N A T 2: 43 A M 5 C O M M ENT S
L A B ELS : JA V A S CR I P T , JQ UER Y, P L UG I N, R ESO UR C E, T O O L S
T U ES D A Y, A UG US T 4 , 2 0 0 9
$('#myDiv').css('background-image', 'my_image.jpg');
// OR
$('#myDiv').css('background', 'path/to/image.jpg');
Solution to “background images are not being set” problem is to set them like
this:
$('#myDiv').css('background-image', 'url(my_image.jpg)');
// OR
$('#myDiv').css('background', 'url(path/to/image.jpg)');
P O S T ED B Y UZ B EK J O N A T 12: 36 A M 9 C O M M ENT S
L A B ELS : A T T R I B UT ES , B EG I NNER , C S S , ER R O R , J Q UER Y, T I P
T H UR S D A Y, J U L Y 2 , 2 0 0 9
When you call .noConflict() jQuery will return $() to it’s previous owner and
http://jquery-howto.blogspot.com/ 20/73
20/01/2011 JQuery HowTo
you will need to use jQuery() instead of shorthand $() function.
<html>
<head>
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
jQuery.noConflict();
// Use jQuery via jQuery(...)
jQuery(document).ready(function(){
jQuery("div").hide();
});
// Use Prototype with $(...), etc.
$('someid').hide();
</script>
</head>
<body></body>
</html>
You can also use the following code snippets to still use $() in your code, but
with one drawback, you will not have access to your other library’s $() method.
// Method 1
jQuery(document).ready(function($){
$("div").hide();
});
// Method 2
(function($) {
/* some code that uses $ */
})(jQuery);
TIP:
Don’t forget that you can always assign jQuery to any other variable name to use
it as your shorthand: var $_ = jQuery;
P O S T ED B Y UZ B EK J O N A T 7: 42 A M 5 C O M M ENT S
L A B ELS : B EG I NNER , HO W T O , I NS I G HT S , JQ UER Y, R EFER ENC E, T UT O R I A L , W O R K A R O UND
W ED NES D A Y, J UL Y 1 , 2 0 0 9
Example:
$().mousemove(function(e){
// e.pageX - gives you X position
// e.pageY - gives you Y position
});
The above jQuery code is binding a new ‘on mouse move’ event to the current
document and triggered every time mouse moves. The coordinates are calculated
in pixels from top left corner of the document. See the above code in action.
You may also want to know the coordinates of the mouse relative to some <div>
or an element. Since jQuery returns mouse position relative to the document
root, by subtracting element’s position from document root you get mouse
positions relative to that element. Long story short here is the code to do just
that:
$("#someDiv").click(function(e){
var relativeX = e.pageX - this.offsetLeft;
var relativeY = e.pageY - this.offsetTop;
});
http://jquery-howto.blogspot.com/ 21/73
20/01/2011 JQuery HowTo
Don’t forget that you can bind any mouse event to any element and then get
mouse positions. You can easily create a draggable object with click and
mousemove events by simply setting the CSS top and left values to .pageX and
.pageY.
Anyway, that’s how you locate and handle mouse positions in jQuery. As
always, you don’t need to worry about cross browser compatibility issues while
using jQuery. To learn more see more examples here.
P O S T ED B Y UZ B EK J O N A T 11: 20 P M 4 C O M M ENT S
L A B ELS : A T T R I B UT ES , B EG I NNER , EV ENT S , HO W T O , JQ UER Y, R EFER ENC E, T UT O R I A L
W ED NES D A Y, J UN E 2 4 , 2 0 0 9
Anyway, let’s create our own jQuery selector that takes arguments. The basic
syntax is the same:
$('a:test(argument)');
//meta would carry the following info:
[
':test(argument)', // full selector
'test', // only selector
'', // quotes used
'argument' // parameters
]
$('a:test("arg1, arg2")');
//meta would carry the following info:
[
':test('arg1, arg2')', // full selector
'test', // only selector
'"', // quotes used
'arg1, arg2' // parameters
]
Here as you can see, we can make use of the arrays fourth (meta[3] ) value to
get a hang of our parameters.
http://jquery-howto.blogspot.com/ 22/73
20/01/2011 JQuery HowTo
See it in action here.
P O S T ED B Y UZ B EK J O N A T 6: 42 A M 3 C O M M ENT S
L A B ELS : HO W T O , I NS I G HT S, J Q UER Y, R EFER ENC E, SEL EC T O R S , T I P , T UT O R I A L
T H UR S D A Y, J U NE 1 1 , 2 0 0 9
Actually, I had to select all external links and add an image that indicates it the
other day. So, I created a custom jQuery selector called :external that makes
finding external links easier for you. (Read “Custom jQuery Selectors” post to
learn how to create your own custom selectors)
Update: The return part was update to take into the account the mailto links as
suggested in comments by Phillipp and Karl below.
P O S T ED B Y UZ B EK J O N A T 1: 57 A M 5 C O M M ENT S
L A B ELS : HO W T O , J Q UER Y, P L UG I N, R EFER ENC E, S EL EC T O R S , T I P , T UT O R I A L
W ED NES D A Y, J UN E 1 0 , 2 0 0 9
And the best part is that jQuery lets you create and define your own custom
selectors using custom selector creation template below.
// Usage:
http://jquery-howto.blogspot.com/ 23/73
20/01/2011 JQuery HowTo
$('.someClasses:test').doSomething();
Let’s now create a very simple custom selector using the template above. Let’s
say we want a custom jQuery selector that will return elements with nonempty
rel attribute.
$.expr[':'].withRel = function(obj){
var $this = $(obj);
return ($this.attr('rel') != '');
};
// Usage:
$('a:withRel').css('background-color', 'yellow');
The code above creates a custom selector that will select only elements with not
empty rel attributes. Here is the above code’s demo page.
P O S T ED B Y UZ B EK J O N A T 3: 43 A M 13 C O M M ENT S
L A B ELS : HO W T O , I NS I G HT S, J Q UER Y, P L UG I N , R EFER ENC E, T UT O R I A L
S A T UR D A Y, J U NE 6 , 2 0 0 9
The bad news is that Jetpack is still in early developer testing stage, so it is not
available in Firefox yet. The good news is that Jetpack is using jQuery and you
can use it to do all kinds of stuff like responding to user click events, manipulate
any website DOM elements and use cross-site XMLHttpRequest object, etc.
Besides, Jetpack can be setted up to use other javascript libraries such as
prototype.js, dojo.js etc. and third party API libraries such as Twitter, Google,
etc. API libraries.
I am planning to post more Jetpack tutorials on this blog and try to show what
kind of things can be done using Jetpack and jQuery. Keep tuned by following
me on Twitter (@jQueryHowto) or subscribe to blog’s RSS.
P O S T ED B Y UZ B EK J O N A T 4: 04 A M 1 C O M M ENT S
L A B ELS : I NS I G HT S , JQ UER Y, L I NK , N EW S , P LUG I N, R EFER ENC E, R ES O UR C E
T H UR S D A Y, J U NE 4 , 2 0 0 9
http://jquery-howto.blogspot.com/ 24/73
20/01/2011 JQuery HowTo
tutorials on the blog.
1. People are finding this jQuery blog searching for jQuery basics
Analyzing my Google Analytics account I found that a lot of developers
who are landing on this blog through search are jQuery Beginners and
looking for basic jQuery method explanations. So publishing more
beginner tutorials would benefit them. They would get more relevant
information from the new Beginner category posts.
2. I am being asked more and more jQuery Beginner questions
I have been quite active on Twitter (@jQueryHowto) and other online
discussion boards lately answering and helping developers with their
jQuery problems. The jQuery community on twitter is quite active and
most of the jQuery problems I came across were jQuery beginners
questions. I could not squeeze my ideas or explanations of jQuery basics
in 140 characters, so I had to search the web for explanation and post a
link to the website.
I hope I will not lose intermediate and advanced jQuery developers with this
posts. I enjoy your insights and comments on my posts and actually learn a lot
more from your feedback. I will try to post no more than one beginner tutorial or
insight per my regular post. I hope for your understanding.
1. Using $.noConflict()
2. How to check if checkbox is checked
3. Identify how many elements were selected
4. Adding custom functions to jQuery
5. Identifying & locating mouse position in jQuery
6. How to load jQuery from Google CDN servers
7. Setting HTML tag’s attribute in jQuery
8. Getting HTML tag’s attribute in jQuery
9. Binding jQuery events to AJAX loaded elements
10. How to disable and enable an element
11. Quick tip to solve a problem with setting CSS background image to an
element
P O S T ED B Y UZ B EK J O N A T 6: 38 A M 1 C O M M ENT S
L A B ELS : B EG I NNER , N EW S , T UT O R I A L
T U ES D A Y, J UNE 2 , 2 0 0 9
It is clear without any performance tests that native javascript for loop is faster,
but I always used jQuery’s .each() utility with caution. It always felt like I will
get a performance penalty for using it. So I tried to never use it.
http://jquery-howto.blogspot.com/ 25/73
20/01/2011 JQuery HowTo
jQuery’s .each() iterator. All I did was just an iteration and no array
amendments or any other logic. I know it is very basic, but that’s exactly what I
want to know. How fast they iterate!
console.time('TestjQuery');
jQuery.each(myArray, function(i, val) {
val;
});
console.timeEnd('TestjQuery');
As you can see native for loop is never over 1ms. That’s probably because we
are not doing anything with our array and browser simply optimizes the code or
maybe its that fast :)
Usually we don’t have more than 1000 items in our arrays and objects, that is
why I guess it can be concluded that using .each() loop in our code will
not cause any performance penalties.
P O S T ED B Y UZ B EK J O N A T 7: 08 A M 10 C O M M ENT S
L A B ELS : I NS I G HT S , JA V A S CR I P T , J Q UER Y, P ER FO R M A NC E, R EFER ENC E, T ES T , T I P
Anyway, back to the topic. For whatever reasons you chose to use jQuery in
your application (I would suggest using plain javascript for better performance)
jQuery effects such as animation, hide and show, etc. most likely were probably
one of the reasons. Unfortunately, jQuery effects are process intensive and in
“slow” environments it is recommended to turn them off. Fortunately, jQuery
provides you with such a method. It lets you disable all animations and effects by
changing jQuery.fx.off setting to true .
// Shorthand
$.fx.off = true;
http://jquery-howto.blogspot.com/ 26/73
20/01/2011 JQuery HowTo
Now all your effects such as fadeIn() , fadeOut() , slideDown() , slideUp() ,
etc. will not be animated. They will simply be hidden and shown immediately (by
changing CSS rules display:none; display:block; ) to save CPU processing
time.
NOTE:
By setting the jQuery.fx.off back to false you enable all animations and
effects.
P O S T ED B Y UZ B EK J O N A T 6: 48 A M 3 C O M M ENT S
L A B ELS : A NI M A T I O N, HO W T O , I NS I G HT S, J Q UER Y, P ER FO R M A NC E, R EFER ENC E, T I P
W ED NES D A Y, M A Y 2 7 , 2 0 0 9
The plugin returns false if there was an error while AJAX loading your feed or the
following feed object on success:
{
"title":"Blog Title",
"link":"http://www.example.com",
"author":"Author Name",
"description":"Blog description.",
"type":"RSS type (atom10, etc.)",
"entries":[
{
"title":"Blog entry title 1",
"link":"http://www.example.com/entry-1.html",
"author":"Post Author Name",
"publishedDate":"Mon, 25 May 2009 07:07:00 -0700",
"contentSnippet":"Short blog post snippet ...",
"content":"Longer snippet of the blog post",
"categories":[
"category 1",
"category 2",
"category 3"
]
http://jquery-howto.blogspot.com/ 27/73
20/01/2011 JQuery HowTo
},
{
"title":"Blog entry title 2",
"link":"http://www.example.com/entry-2.html",
"author":"Post Author Name",
"publishedDate":"Mon, 25 May 2009 07:07:00 -0700",
"contentSnippet":"Short blog post snippet ...",
"content":"Longer snippet of the blog post",
"categories":[
"category 3",
"category 2",
"category 1"
]
},
...
}
If you don’t specify a URL it will also return false. If you want to use your own
Google Feed API key you can get one here.
P O S T ED B Y UZ B EK J O N A T 9: 45 A M 9 C O M M ENT S
L A B ELS : A JA X , J Q UER Y, J S O N, P L UG I N
M O ND A Y, M A Y 2 5 , 2 0 0 9
<div class="rounded">
<script type="text/javascript">
digg_url = "myURL.com";
</script>
<script src="http://digg.com/tools/diggthis.js" type="text/java
script"></script>
</div>
$(document).ready(function(){
$("div.rounded").wrap('<div></div>');
});
This code seems to crush those browsers. Another way to do this is to remove
the div that contains the script (.rounded ), then create a new <div> and then
insert the removed div (.rounded ) back into the newly created div like this:
$(document).ready(function(){
$("div.rounded").remove().wrap('<div></div>').appendTo("#some
where");
});
P O S T ED B Y UZ B EK J O N A T 7: 07 A M 0 C O M M ENT S
L A B ELS : DO M , ER R O R , J Q UER Y, M A NI P UL A T I O N, T I P , W O R K A R O UND
http://jquery-howto.blogspot.com/ 28/73
20/01/2011 JQuery HowTo
if(!col){ col = 1; }
$('tr td:nth-child('+col+'), tr th:nth-child('+col+')', this)
.remove();
return this;
};
Just add this code to your javascript file and use it in your jQuery code like this:
The function takes column number to delete as an argument and removes that
column. If you don’t supply any column number it removes the first table column
by default.
P O S T ED B Y UZ B EK J O N A T 6: 01 A M 7 C O M M ENT S
L A B ELS : HO W T O , HT M L, J Q UER Y, M A NI P UL A T I O N, P L UG I N, R EFER ENC E
T H UR S D A Y, M A Y 2 1 , 2 0 0 9
jQuery code to delete clicked table row came out to be surprisingly short,
only 3 lines of code.
Here, we are first selecting all table cells to bind our click event. On user click to
any table cell click event fires. In the click event we are removing <td> ’s parent,
which is <tr> , thus removing whole row.
By popular user demand I’m including an example that lets deleting a table
row on delete image click. Here is our HTML table:
<table>
<tr>
<td>row 1, cell 1</td>
<td><img class="delete" src="del.gif" /></td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td><img class="delete" src="del.gif" /></td>
</tr>
</table>
$('table td img.delete').click(function(){
$(this).parent().parent().remove();
});
http://jquery-howto.blogspot.com/ 29/73
20/01/2011 JQuery HowTo
$('table td').click(function(){
$.get('deleteRow.php', {id: $(this).parent().attr('id')},
function(){
$(this).parent().remove();
});
});
In the jQuery code above, instead of removing table row straight away we are
making an AJAX call to our server side code that also removes that row from our
database and then on AJAX call completion we removing table row.
P O S T ED B Y UZ B EK J O N A T 12: 35 A M 3 C O M M ENT S
L A B ELS : HO W T O , HT M L, J Q UER Y, M A NI P UL A T I O N
Couple of months ago I wrote a javascript function that does just that, gets
YouTube video’s thumbnail. Today, I am rewriting that code as a jQuery utility
function and releasing it as jQuery plugin called jYouTube.
It takes any YouTube video URL or video ID as first parameter and thumbnail size
(big or small) as the second parameter. Utility returns that video’s screenshot
URL.
So here is the final jQuery YouTube plugin code for those who are interested:
$.extend({
jYoutube: function( url, size ){
if(url === null){ return ""; }
results = url.match("[\\?&]v=([^&#]*)");
if(size == "small"){
return "http://img.youtube.com/vi/"+vid+"/2.jpg";
}else {
return "http://img.youtube.com/vi/"+vid+"/0.jpg";
}
}
});
http://jquery-howto.blogspot.com/ 30/73
20/01/2011 JQuery HowTo
P O S T ED B Y UZ B EK J O N A T 8: 43 A M 1 C O M M ENT S
L A B ELS : HO W T O , J Q UER Y, P L UG I N, T O O L S
T U ES D A Y, M A Y 1 2 , 2 0 0 9
So, before we continue, we need to define where our images are coming from.
Images URLs can be stored in javascript array or we could choose more elegant
way and simply read them from HTML document.
<div id="myGallery">
<img src="image1.jpg" class="active" />
<img src="image2.jpg" />
<img src="image3.jpg" />
</div>
We need to hide all images but class="active" one and overlay all of them on
one another. Here is a CSS to do that:
#myGallery{
position:relative;
width:400px; /* Set your image width */
height:300px; /* Set your image height */
}
#myGallery img{
display:none;
position:absolute;
top:0;
left:0;
}
#myGallery img.active{
display:block;
}
Now, lets write jQuery function that will fade out currently active image and fade
in the next image. Here is jQuery code:
function swapImages(){
var $active = $('#myGallery .active');
var $next = ($('#myGallery .active').next().length > 0) ? $('#m
yGallery .active').next() : $('#myGallery img:first');
$active.fadeOut(function(){
$active.removeClass('active');
$next.fadeIn().addClass('active');
});
}
And now all that’s left is to add setInterval() with our function and the time interval
we want our image to fade out and fade in.
Now we have gallery/slideshow with images changing every 5 seconds. You can
easily customize this jQuery script to create your own slideshow.
http://jquery-howto.blogspot.com/ 31/73
20/01/2011 JQuery HowTo
<script>
function swapImages(){
var $active = $('#myGallery .active');
var $next = ($('#myGallery .active').next().length > 0) ? $
('#myGallery .active').next() : $('#myGallery img:first');
$active.fadeOut(function(){
$active.removeClass('active');
$next.fadeIn().addClass('active');
});
}
$(document).ready(function(){
// Run our swapImages() function every 5secs
setInterval('swapImages()', 5000);
}
</script>
<style>
#myGallery{
position:relative;
width:400px; /* Set your image width */
height:300px; /* Set your image height */
}
#myGallery img{
display:none;
position:absolute;
top:0;
left:0;
}
#myGallery img.active{
display:block;
}
</style>
</head>
<body>
<div id="myGallery">
<img src="image1.jpg" class="active" />
<img src="image2.jpg" />
<img src="image3.jpg" />
</div>
</body>
</html>
P O S T ED B Y UZ B EK J O N A T 4: 42 A M 12 C O M M ENT S
L A B ELS : A NI M A T I O N, CS S, HO W T O , HT M L , J Q UER Y, T UT O R I A L
T H UR S D A Y, M A Y 7 , 2 0 0 9
So this Friday’s quick tip is disabling form submit button on its click or
preventing double form submission by disabling submit button.
$('#myform').submit(function(){
$('input[type=submit]', this).attr('disabled', 'disabled');
});
http://jquery-howto.blogspot.com/ 32/73
20/01/2011 JQuery HowTo
The above jQuery code binds a submit event to our #myform form, then finds its
submit button and disables it.
Want to disable any other elements using jQuery? Read my previous “Disabling
and enabling elements in jQuery” (very short) post.
P O S T ED B Y UZ B EK J O N A T 11: 45 P M 5 C O M M ENT S
L A B ELS : A T T R I B UT ES , EV ENT S , HO W T O , HT M L, T I P , T UT O R I A L , W O R K A R O UND
Recently I was asked to write a jQuery or JavaScript code that removes the
last/bottom row from the given table. The jQuery code I wrote was surprisingly
small.
http://jquery-howto.blogspot.com/ 33/73
20/01/2011 JQuery HowTo
/*
Remove the last/bottom table row
*/
function removeTableRow(jQtable){
jQtable.each(function(){
if($('tbody', this).length > 0){
$('tbody tr:last', this).remove();
}else {
$('tr:last', this).remove();
}
});
}
Also the above javascript function can easily be rewritten as a jQuery plugin.
Read this post to learn how to create jQuery plugins.
P O S T ED B Y UZ B EK J O N A T 7: 57 A M 2 C O M M ENT S
L A B ELS : DO M , HO W T O , HT M L , JA V A S C R I P T , JQ UER Y, M A NI P UL A T I O N, P L UG I N, T I P ,
T UT O R I A L
W ED NES D A Y, A P R I L 2 9 , 2 0 0 9
You might have noticed that I am talking and spending more time on Twitter
lately. I have been helping Twitter users with their jQuery related questions and
problems as well. If you are using Twitter and have some kind of jQuery related
question I will be happy to help.
Anyway, after I found a Twitter JSON(P) API url last week, I spent some time
playing with it and ended up with a jQuery plugin that when given a Twitter
username retrieves and returns javascript object with user detials such as
followers & following counts, full name, homepage URL, etc.
http://jquery-howto.blogspot.com/ 34/73
20/01/2011 JQuery HowTo
"profile_background_tile":false,
"profile_sidebar_border_color":"87bc44",
"profile_background_color":"9ae4e8",
"profile_text_color":"000000"
"profile_background_image_url":"http://static.twitter.com
/images/themes/theme1/bg.gif",
}
As you can see the jQuery Twitter API plugin returns Twitter user's avatar URL
as well. Using this jQuery plugin you could create another plugin that would
return Twitter user's avatar image.
The first parameter is a Twitter username and the second is a callback function
that will be called after jQuery gets user details from the Twitter servers.
P O S T ED B Y UZ B EK J O N A T 5: 29 A M 17 C O M M ENT S
L A B ELS : A JA X , J Q UER Y, J S O N, P L UG I N
T U ES D A Y, A P R I L 2 8 , 2 0 0 9
The plugin extends jQuery and adds two main functions called $.uiLock(); and
$.uiUnlock();
$.uiLock(); takes an HTML text argument that will be placed in the page
overlay. You can style the overlaying layer using CSS. You can change font
color, background color, etc. To style uiLocker use #uiLockId CSS selector.
For example:
#uiLockId{
background-color:red !important;
}
The plugin demo can be found in the plugin archive. Here is a screenshot of the
plugin at work:
http://jquery-howto.blogspot.com/ 35/73
20/01/2011 JQuery HowTo
User will not be allowed to interact with the website on the screenshot above.
Basically, we are blocking all user actions with an extra layer that uiLock jQuery
plugin adds.
P O S T ED B Y UZ B EK J O N A T 8: 26 A M 1 C O M M ENT S
L A B ELS : A JA X , HO W T O , J Q UER Y, P L UG I N, T O O L S , W O R K A R O UND
But for today, I would like to share Twitter’s JSON and JSONP API URL. I am
sharing it because it was hard to find it first. I actually wrote a jQuery plugin that
gets Twitter user details using my previous post on cross site AJAX querying
method. All Twitter API usage tutorials and articles I found on internet were
based on RESTful non JSONP API, so I though I'll share Twitter JSON(P) API
with you. Anyway...
http://twitter.com/status/user_timeline/USERNAME.json?count=10
&callback=?
We have put ? (question mark) for callback function name so jQuery could
replace it with a dynamic one that it has created.
P O S T ED B Y UZ B EK J O N A T 1: 06 A M 2 C O M M ENT S
L A B ELS : A JA X , J S O N, LI NK , R EFER ENC E, R ESO UR C E
T U ES D A Y, A P R I L 2 1 , 2 0 0 9
It is clear without saying that we are going to update our page content using
AJAX and of course we love AJAX in jQuery flavor. So key to this functionality is
http://jquery-howto.blogspot.com/ 36/73
20/01/2011 JQuery HowTo
JavaScript's built-in setInterval() function. It lets you to run some javascript
function every X seconds. For example, the following code would pop alert box
every five seconds:
function updateShouts(){
// Assuming we have #shoutbox
$('#shoutbox').load('latestShouts.php');
}
setInterval( "updateShouts()", 10000 );
The code above will run every 10 seconds (10,000 ms) and update the contents
of #shotbox with new shouts.
P O S T ED B Y UZ B EK J O N A T 8: 08 A M 2 C O M M ENT S
L A B ELS : A JA X , HO W T O , J Q UER Y, T I P , T UT O R I A L
T H UR S D A Y, A P R I L 1 6 , 2 0 0 9
{
'status':'ok',
'IP': '74.125.45.100',
'CountryCode': 'US',
'CountryName': 'United States',
'RegionName': 'California',
'ZipPostalCode': '94043',
'City': 'Mountain View',
'Latitude': '37.4192',
'Longitude': '-122.057'
}
// In case of an error
{
'status':'parent server not responding'
}
http://iplocationtools.com/ip_query.php?output=json&ip=80.80.214.9
3
And the great thing is, you can identify your website visitor’s IP and Geo location
by simply querying the API without any parameters like this:
http://iplocationtools.com/ip_query.php?output=json
Knowing your users’ IP and/or location, you might add a behavior to your website
that is specific to some location. For example, offering some advertising to US
only visitors, or popup with special offer to European users.
http://jquery-howto.blogspot.com/ 37/73
20/01/2011 JQuery HowTo
$.getJSON(url, function(data){
if(data['status'] == 'ok'){
// Do something with the data
$('#profile #ip')
.append(data['IP']);
$('#profile #country')
.append(data['CountryName']);
}
});
Here we are not specifying any IP address in the url variable that is why it is
getting current user’s data.
P O S T ED B Y UZ B EK J O N A T 3: 12 A M 14 C O M M ENT S
L A B ELS : A JA X , HO W T O , J A V A SC R I P T , J Q UER Y, R ES O UR C E, T I P , T O O LS , T UT O R I A L
W ED NES D A Y, A P R I L 1 5 , 2 0 0 9
The great thing about them is that they also provide you with an API. So I
thought that there is a way we can make a use of them in our jQuery code. One
of the most popular services is bit.ly. You can read more about its API here.
Here is an example:
(function($){
// set up default options
var defaults = {
version: '2.0.1',
login: 'bitlyapidemo',
apiKey: 'R_0da49e0a9118ff35f52f629d2d71bf07',
history: '0',
longUrl: ''
};
});
})(jQuery);
This code does not do much, but I hope you will find a good use of it in your own
applications.
P O S T ED B Y UZ B EK J O N A T 5: 50 A M 6 C O M M ENT S
L A B ELS : A JA X , HO W T O , J A V A SC R I P T , J Q UER Y, R EFER ENC E, T I P , T O O LS , T UT O R I A L
http://jquery-howto.blogspot.com/ 38/73
20/01/2011 JQuery HowTo
M O ND A Y, A P R I L 1 3 , 2 0 0 9
Using this method for cross site scripting you will be able to:
1. Make AJAX queries to any domain even those that differ from your own;
2. Use any of $.get() , $.post() , $.ajax() , $getScript() , etc. jQuery
AJAX functions as your query method.
But all these does not come free, you will need to put a proxy to between you
and the rest of the world. This cross domain querying solution works because
you actually loading the content from your own domain. You request the URL
and the proxy script on your server actually loading the content from the internet
and passing it over to you.
I created a sample PHP proxy that I used to get related news RSS feed for one
of my projects.
I named the file proxy.php and made my AJAX request to this url. Here is a
jQuery code example:
$("#rssFeeds").load("path/to/proxy.php", function(){
// Some callback functions
});
And this is how I overcame the jQuery cross site scripting problems. The bad
news is that not all web hosting companies allow fopen() to other domains, but
enable it on request. My web server was very strict on security but the script
above worked well on it.
P O S T ED B Y UZ B EK J O N A T 8: 05 A M 30 C O M M ENT S
L A B ELS : A JA X , ER R O R , HO W T O , J A V A S C R I P T , J Q UER Y, T I P , W O R K A R O UND
S A T UR D A Y, A P R I L 1 1 , 2 0 0 9
jQuery makes dynamic image swapping a peace of cake. All you need to do to
replace your image with another one is to replace its src attribute. The
browser will take care of the rest.
Here is an example:
$("#myImage").attr("src", "path/to/newImage.jpg");
TIP:
To avoid page jumping and improve user experience it is a good idea to preload
your images before you swap them.
P O S T ED B Y UZ B EK J O N A T 4: 18 A M 0 C O M M ENT S
L A B ELS : A T T R I B UT ES , HO W T O , HT M L , JQ UER Y, M A NI P UL A T I O N, T I P , T UT O R I A L
Selecting a text in your inputbox on focus is easy and actually 3 lines of jQuery
code, but it add a nice usability touch to your site. This “select all” behavior is
default in browser when you browse through form fields using TAB key, but when
you click on to the input text field it does not behave like that.
TIP:
Change the selector in the second example and get this behavior to password
fields, textarea fields, etc.
Also we can add a little spice into our code and only select the contents of our
text field or textarea if it has not been changed from its default original value.
The code above selects all text content of textareas if and only if it’s value has
http://jquery-howto.blogspot.com/ 40/73
20/01/2011 JQuery HowTo
changed from the original one. This behavior would probably be more useful on
input fields :)
P O S T ED B Y UZ B EK J O N A T 7: 27 A M 1 C O M M ENT S
L A B ELS : EV EN T S, HO W T O , HT M L , J Q UER Y, R EFER ENC E, T I P , W O R K A R O UND
T H UR S D A Y, A P R I L 9 , 2 0 0 9
<html>
<head>
<title>User</title>
</head>
<body>
User Information:<br />
Name: {$name}
</body>
</html>
Smarty will replace the {$name} with the variable that you set in your PHP code.
Anyway, do you see the problem that might arise when you try to embed your
jQuery code or any other javascript library (like Prototype, MooTools, Extjs, etc.)
that uses $ as a function name in the <head> ?
Smarty parses the file and whenever it encounters the {$ it would try to parse it
and replace with the PHP variable like in this example here:
<html>
<head>
<title>User</title>
<script type="text/javascript">
$(document).ready(function(){
$(".clazz").css("color", "red");
});
</script>
</head>
<body>
User Information:<br />
Name: {$name}
</body>
</html>
The problem:
Smarty would not care that { and $ are on different lines and would see it like
{$(".clazz... . The code above would cause this Smarty error:
Fatal error: Smarty error: [in templateFile.tpl line 5]: syntax error:
unreco gnized tag: $(".clazz").css("co lor", "red");
(Smarty_Co mpiler.class.php, line 455 ) in
C:\PHP\smarty\libs\Smarty.class.php on line 1 092
The solution:
There are couple of things you can do about this problem:
1. Move your javascript (jQuery, Prototype, etc.) code into the external .js
file.
2. Use jQuery() instead of $() .
3. Use Smarty’s {literal}...{/literal} directives to tell Smarty parsing
engine that it should not interpret the code within the block.
Example:
http://jquery-howto.blogspot.com/ 41/73
20/01/2011 JQuery HowTo
Here is how we can rewrite our javascript code above using the 3rd tip:
<html>
<head>
<title>User</title>
<script type="text/javascript">
{literal}
$(document).ready(function(){
$(".clazz").css("color", "red");
});
{/literal}
</script>
</head>
<body>
User Information:<br />
Name: {$name}
</body>
</html>
P O S T ED B Y UZ B EK J O N A T 12: 24 A M 6 C O M M ENT S
L A B ELS : ER R O R , HO W T O , J Q UER Y, T I P , W O R K A R O UND
M O ND A Y, A P R I L 6 , 2 0 0 9
Now, let's see how can we display a loading image while requested content is
being loaded by one of the jQuery's AJAX functions. Here is what happens:
To make it more apparent, imagine we have HTML page with this markup:
We want to load content when a user clicks on the "Load Content" button. So we
need to bind a click event to that button first and make AJAX request only after
it is fired.
$("#btnLoad").click(function(){
// Make AJAX call
$("#content").load("http://example.com");
});
The above code loads contents from http://example.com into the <div
id="content"> . While the page is being loaded we want to display our animated
GIF image in the "content". So we could further improve our code like so:
$("#btnLoad").click(function(){
http://jquery-howto.blogspot.com/ 42/73
20/01/2011 JQuery HowTo
$("#content").load("http://example.com");
});
The .load() function would replace our loading image indicator with the loaded
content.
Final note:
You might be using jQuery’s other AJAX functions like $.ajax() , $.get() ,
$.post() , in this case use their callback function to remove loading image/text
and append your loaded data.
P O S T ED B Y UZ B EK J O N A T 5: 23 A M 17 C O M M ENT S
L A B ELS : A JA X , HO W T O , HT M L , T I P , T UT O R I A L
T H UR S D A Y, A P R I L 2 , 2 0 0 9
The problem:
When you have mouseover and mouseout events bound to some element on you
page with children elements. Hovering over children element fires parent’s
mouseover and/or mouseout event.
The solution:
The solution to this error is to use mouseenter and mouseleave events instead of
mouseover and mouseout .
The reason:
This solution works because mouseover and mouseout events do not bubble from
child to parent element.
P O S T ED B Y UZ B EK J O N A T 4: 56 A M 24 C O M M ENT S
L A B ELS : EV EN T S, J Q UER Y, T I P , W O R K A R O UND
W ED NES D A Y, A P R I L 1 , 2 0 0 9
This problem is common in Mozilla Firefox (FF). Internet Explorer (IE) users I
believe, do not experience this problem. Usually it occurs when you use jQuery
AJAX functions in javascript setInterval() method. Basically, what happens is that
Firefox can not see the changes been made to the page and thinks it’s the same
with the old one. So Firefox loads it from cache and you don’t see the new
version of your page. To resolve this issue, you should simply add a random
string to the request like below.
The solution:
http://jquery-howto.blogspot.com/ 43/73
20/01/2011 JQuery HowTo
{
// Minimized code, suggested by Kovacs
$('#mydiv').load("mypage.htm?" + 1*new Date() );
}, 5000);
P O S T ED B Y UZ B EK J O N A T 3: 29 A M 11 C O M M ENT S
L A B ELS : A JA X , ER R O R , HO W T O , I NS I G HT S , J A V A S C R I P T , J Q UER Y, T I P , W O R K A R O UND
M O ND A Y, M A R C H 3 0 , 2 0 0 9
document.getElementsByTagName("body")[0].setAttribute("class", "j
s");
.someClass{
display:block;
}
.js .someClass{
display:none;
}
Similar to previous example, we can use difference CSS style for jQuery enabled
browsers.
if(jQuery){
jQuery("body").addClass("jq");
}
.someClass{
display:block;
}
.jq .someClass{
display:none;
}
P O S T ED B Y UZ B EK J O N A T 7: 18 A M 4 C O M M ENT S
L A B ELS : CSS , HO W T O , HT M L , J A V A S C R I P T , J Q UER Y, T I P , W O R K A R O UND
S UN D A Y, M A R C H 2 9 , 2 0 0 9
Twitter is a great place to build your community of interest. For example if you
are interested in jQuery than you can follow people who share tweets about
http://jquery-howto.blogspot.com/ 44/73
20/01/2011 JQuery HowTo
jQuery/JavaScript and follow them. Examples could be the official jQuery and
jQuery HowTo accounts.
Also, you can use WeFollow service to find people to follow by their interests.
There are lots of other services that utilize Twitter API and provide great services.
I added retweet button to my posts. If you like them, please retweet.
P O S T ED B Y UZ B EK J O N A T 10: 34 P M 0 C O M M ENT S
L A B ELS : NEW S
T H UR S D A Y, M A R C H 2 6 , 2 0 0 9
if(jQuery().pluginMethod) {
//jQuery plugin exists
} else {
//jQuery plugin DOES NOT exist
}
As you know from previous post on namespacing javascript plugins are created
as an additional namespace within jQuery namespace. All you have to do to
check if plugin exists is to check if it’s namespace / function is defined.
For example, let’s assume that my plugin depends on jQuery Validation plugin.
To check if validation plugin is loaded I would do the following:
if(jQuery().validate) {
// Validation plugin exists
// Now I can use $('#someId').validate()
} else {
// Validation plugin DOES NOT exist
}
P O S T ED B Y UZ B EK J O N A T 4: 06 A M 7 C O M M ENT S
L A B ELS : HO W T O , I NS I G HT S, J Q UER Y, P L UG I N , T I P , W O R K A R O UND
W ED NES D A Y, M A R C H 2 5 , 2 0 0 9
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jq
uery.min.js" type="text/javascript"></script>
NOTE:
You don’t even need to upload jquery.js file on any other hosting Google will host
it for your.
P O S T ED B Y UZ B EK J O N A T 5: 19 A M 5 C O M M ENT S
L A B ELS : HO W T O , J Q UER Y, T I P , W O R K A R O UND
http://jquery-howto.blogspot.com/ 45/73
20/01/2011 JQuery HowTo
T U ES D A Y, M A R C H 2 4 , 2 0 0 9
Anyway, jQuery() or $() functions will only be defined if they are already loaded
into the current document. So to test if jQuery is loaded we can use 2 methods.
Method 1:
if (jQuery) {
// jQuery is loaded
} else {
// jQuery is not loaded
}
Method 2:
NOTE:
Here we are checking for jQuery function being defined or not. This is a safe way
to check for jQuery library being loaded. In case you are not using any other
javascript libraries like prototype.js or mootools.js, then you can also check for $
instead of jQuery .
P O S T ED B Y UZ B EK J O N A T 7: 07 A M 4 C O M M ENT S
L A B ELS : HO W T O , J A V A S CR I P T , J Q UER Y, T ES T , T I P , W O R K A R O UND
M O ND A Y, M A R C H 2 3 , 2 0 0 9
What you need to do when you are creating a new checkbox or radio button set
with jQuery is to define the type attribute while creating like so:
Problem:
Can not create a new input form fields using jQuery or newly created checkboxes
and radio buttons are not displayed/created.
Solution:
To solve the problem you need to create an input field with type attribute
already defined.
http://jquery-howto.blogspot.com/ 46/73
20/01/2011 JQuery HowTo
P O S T ED B Y UZ B EK J O N A T 7: 59 A M 5 C O M M ENT S
L A B ELS : DO M , ER R O R , HO W T O , HT M L , J Q UER Y, M A NI P ULA T I O N, T I P , W O R K A R O UND
Uncompressed:
http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.js
Compressed: http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-
ui.min.js
P O S T ED B Y UZ B EK J O N A T 5: 44 A M 0 C O M M ENT S
L A B ELS : JQ UER Y UI , NEW S
M O ND A Y, M A R C H 1 6 , 2 0 0 9
There is no obvious code syntax nor logical problem in this code. But you still
will get last li’s id in alert window whichever li you click.
The solution to this problem is to rewrite your code similar to this one:
This solves the problem of all items in the loop getting the last
arrays/elements/etc. attribute value (id/class/etc.).
P O S T ED B Y UZ B EK J O N A T 6: 03 A M 5 C O M M ENT S
L A B ELS : EV EN T S, HO W T O , I NS I G HT S , J A V A S C R I P T , J Q UER Y, T I P , W O R K A R O UND
T H UR S D A Y, M A R C H 5 , 2 0 0 9
http://jquery-howto.blogspot.com/ 47/73
20/01/2011 JQuery HowTo
probably got an idea that it’s better to work with arrays for better javascript
performance.
The only problem is that jQuery returns an object not an array when you select
elements. Consider you have an object with lots of entries and you have to
perform some manipulations that are available in javascript array such as
reverse , sort , join , etc. Using built in methods is much faster then those you
might write yourself. So the best thing would be converting your objects to arrays
and jQuery provides utility method that does exactly this –
jQuery.makeArray(obj) .
P O S T ED B Y UZ B EK J O N A T 10: 29 P M 3 C O M M ENT S
L A B ELS : HO W T O , J A V A S CR I P T , J Q UER Y, M A NI P UL A T I O N, P ER FO R M A NC E, T I P ,
W O R K A R O UND
jQuery makes creation and loading DOM elements (in our case images) very
easy. If you need to preload an image you can use this jQuery script here:
First jQuery creates a image DOM element and setting the src attribute of the
image element would tell the user browser to load that image. Thus preloading
the image.
Next you should insert your DOM element into the DOM tree using one of the
many jQuery DOM manipulation methods.
Here are some examples of how you could insert preloaded image into your
website:
But the best way is to use a callback function, so it inserts the preloaded image
into the application when it has completed loading. To achieve this simply use
.load() jQuery event.
P O S T ED B Y UZ B EK J O N A T 6: 27 A M 16 C O M M ENT S
L A B ELS : EV EN T S, HO W T O , J Q UER Y, M A NI P UL A T I O N, T I P , W O R K A R O UND
W ED NES D A Y, F EB R UA R Y 2 5 , 2 0 0 9
http://jquery-howto.blogspot.com/ 48/73
20/01/2011 JQuery HowTo
How to add more items to the existing jQuery
selection
There are occasions when you have already selected elements and need to add
more items to it. Imagine you have selected different items and have jQuery
selection object. For example:
Now, you need to add more new items (DOM nodes) to your section. Let’s say
you want to add .otherItems to your elms selection. You could achieve it by
using one of these methods:
elms.add('.otherItems');
$('.otherItems').add(elms); // The same as above
The post title for the second method would be “How to add jQuery
object/selection to the existing selection”. Anyway, it’s just wording :)
P O S T ED B Y UZ B EK J O N A T 6: 12 A M 0 C O M M ENT S
L A B ELS : HO W T O , J Q UER Y, S ELEC T O R S, T I P , W O R K A R O UND
T U ES D A Y, F EB R U A R Y 2 4 , 2 0 0 9
Method 1: You can run this code to make jQuery available in Firebug:
var s = document.createElement('script');
s.setAttribute('src', 'http://ajax.googleapis.com/ajax/libs/jquer
y/1.3.1/jquery.min.js');
document.body.appendChild(s);
s.onload=function(){
/*Your Code Here*/
};
void(s);
Load jQuery – When you click on this link it will load jQuery from
Google’s server and make it available in Mozilla add-on Firebug.
P O S T ED B Y UZ B EK J O N A T 6: 13 A M 1 C O M M ENT S
L A B ELS : FI R EB UG , HO W T O , I NS I G HT S , JQ UER Y, P L UG I N, T I P , T O O L S , W O R K A R O UND
M O ND A Y, F EB R UA R Y 2 3 , 2 0 0 9
Notable changes:
http://jquery-howto.blogspot.com/ 49/73
20/01/2011 JQuery HowTo
and now selectors return elements in their document appearance order;
read release notes for more information on changes.
P O S T ED B Y UZ B EK J O N A T 11: 37 P M 0 C O M M ENT S
L A B ELS : JQ UER Y, NEW S, P ER FO R M A NC E
function addTableRow(jQtable){
jQtable.each(function(){
var $table = $(this);
// Number of td's in the last table row
var n = $('tr:last td', this).length;
var tds = '<tr>';
for(var i = 0; i < n; i++){
tds += '<td> </td>';
}
tds += '</tr>';
if($('tbody', this).length > 0){
$('tbody', this).append(tds);
}else {
$(this).append(tds);
}
});
}
addTableRow($('#myTable'));
addTableRow($('.myTables'));
P O S T ED B Y UZ B EK J O N A T 4: 35 A M 2 C O M M ENT S
L A B ELS : DO M , HO W T O , HT M L , JA V A S C R I P T , JQ UER Y, M A NI P UL A T I O N, T I P ,
W O R K A R O UND
W ED NES D A Y, F EB R UA R Y 1 8 , 2 0 0 9
Your file will be compressed and saved to path you specified as the last
parameter (in our case minimized.file.js).
Links:
1. Download YUICompressor
2. Download JRE (required to run java applications)
3. Online version of YUICompressor
P O S T ED B Y UZ B EK J O N A T 3: 58 A M 3 C O M M ENT S
http://jquery-howto.blogspot.com/ 50/73
20/01/2011 JQuery HowTo
L A B ELS : CSS , HO W T O , I NS I G HT S, J A V A S C R I P T , J Q UER Y, L I NK , R EFER ENC E, R ES O UR C E,
T I P , T O O LS
M O ND A Y, F EB R UA R Y 1 6 , 2 0 0 9
For example:
// This causes this text glich
$("#message").fadeIn();
Screenshots:
You need to remove the filter attribute after fadeIn() function has completed its
job. In other words, as a function callback. Otherwise, fadeIn()/fadeOut()
functions would change the opacity of the element, which in turn would cause the
filter attribute to be attached yet again. So, remove the attribute in function
callback like this:
$('#message').fadeIn(function(){
this.style.removeAttribute("filter");
});
P O S T ED B Y UZ B EK J O N A T 6: 56 A M 23 C O M M ENT S
L A B ELS : A NI M A T I O N, ER R O R , HO W T O , HT M L, I NS I G HT S, J A V A S C R I P T , J Q UER Y,
M A NI P UL A T I O N, R EFER ENCE, T I P , W O R K A R O UND
S A T UR D A Y, F EB R UA R Y 1 4 , 2 0 0 9
function JavascriptFunction() {
// Comment example
var myVariable;
return myVariable;
}
http://jquery-howto.blogspot.com/ 51/73
20/01/2011 JQuery HowTo
// jQuery code sample
$.extend({
myNamespaced: function(myArg){
return 'namespaced.' + myArg;
}
});
$.myNamespaced('A'); // Another comment
P O S T ED B Y UZ B EK J O N A T 3: 42 A M 3 C O M M ENT S
L A B ELS : NEW S
The script takes into consideration your table header's row and column spans.
Features:
Gracefully degrade for those browsers that do not support javascript
Lets you keep your HTML mark up clean
Make your tabular data more usable and readable
Example code:
// Add row count
$('.myTables').rowCount();
Both options are optional. The only requirement is that you have to have
<thead> and <tbody> tags in your table HTML.
Here is the original table (to the left) and new table (to the right) with row columns
automatically added.
P O S T ED B Y UZ B EK J O N A T 3: 26 A M 2 C O M M ENT S
L A B ELS : HO W T O , HT M L, J Q UER Y, M A NI P UL A T I O N, P L UG I N
T H UR S D A Y, F EB R UA R Y 1 2 , 2 0 0 9
http://jquery-howto.blogspot.com/ 52/73
20/01/2011 JQuery HowTo
what if you don't want to embed a flash video player and you only need an image
of the video. The following function returns a YouTube video's thumbnail URL.
Nothing more, nothing less.
results = url.match("[\\?&]v=([^&#]*)");
if(size == "small"){
return "http://img.youtube.com/vi/"+vid+"/2.jpg";
}else {
return "http://img.youtube.com/vi/"+vid+"/0.jpg";
}
}
You can pass a YouTube video URL or video id and the function will return a
path to the video image. The second function argument is optional. You can
specify the size of returned image. It can be big (320x240) or small (128x96),
defaults to big .
P O S T ED B Y UZ B EK J O N A T 3: 59 A M 22 C O M M ENT S
L A B ELS : HO W T O , J A V A S CR I P T , R EFER ENC E, T I P , W O R K A R O UND
W ED NES D A Y, F EB R UA R Y 1 1 , 2 0 0 9
jQuery Validation is a very flexible plugin and provides a way to easily define your
own validation rules. You can read more about jQuery Validation plugin and
custom validation rules here. It is quite straight forward.
Anyway, I was working on a project that requires the use of custom rules and I
had no control over the generated HTML code and used CSS selectors. So I had
to work with CSS classes that had period "." symbol in their names. My first
attempt failed.
Here is the code that failed. Pay attention to the selector name with the (.) in it's
name.
rules: {
user.email: {
required: true,
email: true
}
}
http://jquery-howto.blogspot.com/ 53/73
20/01/2011 JQuery HowTo
It is common in Java programming world that your form fields have periods (.) in
their names and this is an example of that. So to solve the problem all you
have to do is to make the object key a string like this:
rules: {
"user.email": {
required: true,
email: true
}
}
This will solve your problem and let you get on with your project. Happy coding...
P O S T ED B Y UZ B EK J O N A T 7: 11 A M 1 C O M M ENT S
L A B ELS : ER R O R , HO W T O , I NS I G HT S , JQ UER Y, P L UG I N, T I P , W O R K A R O UND
M O ND A Y, F EB R UA R Y 9 , 2 0 0 9
Native browser functions are always faster then any other helper functions
that were built to add an abstraction layer. In case you are looping through
an object that you have received as JSON, I highly recommend you
rewrite your JSON to contain an array rather than an object.
This one is probably one of the most important tips that will significantly
improve your code performance. It is so important that I will repeat myself.
Do not append a new element to the DOM in your loop statement. Instead
store it in a variable as text and append it to the DOM after your loop
finishes like this:
// DO NOT DO THIS
for (var i=0; i<=rows.length; i++)
{
$('#myTable').append('<tr><td>'+rows[i]+'</td></tr>');
}
// INSTEAD DO THIS
var tmp = '';
for (var i=0; i<=rows.length; i++)
{
tmp += '<tr><td>'+rows[i]+'</td></tr>';
}
$('#myTable').append(tmp);
When you have a lot of elements to insert into the DOM tree it takes time
to add them all. Somehow adding one element with 1000 children is faster
than adding 1000 children separately. You can search this site for
performance tests that prove it.
So, to improve our previous example's performance let's cover <tr> 's with
<tbody> tag like this:
http://jquery-howto.blogspot.com/ 54/73
20/01/2011 JQuery HowTo
var tmp = '<tbody>';
for (var i=0; i<=rows.length; i++)
{
tmp += '<tr><td>'+rows[i]+'</td></tr>';
}
tmp += '</tbody>';
$('#myTable').append(tmp);
5. And the last but not least use setTimeout() function for your long list
looping and concatenation functions.
This will make sure that page does not freeze while it loops through the
long list of data and lets users to work with your page meanwhile.
function myFunk(data){
// do processing
if(!has_finished)
setTimeout("myFunk()", 100);
}
P O S T ED B Y UZ B EK J O N A T 7: 20 A M 16 C O M M ENT S
L A B ELS : DO M , HO W T O , I NS I G HT S , J A V A SC R I P T , J Q UER Y, M A NI P ULA T I O N,
P ER FO R M A NCE, R ES O UR CE, T I P , W O R K A R O UND
S A T UR D A Y, F EB R UA R Y 7 , 2 0 0 9
Anyway, here are two ways you can check the current jQuery version.
P O S T ED B Y UZ B EK J O N A T 12: 33 A M 4 C O M M ENT S
L A B ELS : HO W T O , I NS I G HT S, J Q UER Y, R EFER ENC E, T I P , W O R K A R O UND
W ED NES D A Y, F EB R UA R Y 4 , 2 0 0 9
http://jquery-howto.blogspot.com/ 55/73
20/01/2011 JQuery HowTo
disables all jQuery animations effective immediately when you set it's value to
true .
jQuery.fx.off = true;
$("input").click(function(){
$("div").toggle("slow");
});
P O S T ED B Y UZ B EK J O N A T 4: 29 A M 1 C O M M ENT S
L A B ELS : A NI M A T I O N, EV ENT S, HO W T O , J Q UER Y, P ER FO R M A NC E, R EFER ENC E, T I P
T U ES D A Y, F EB R U A R Y 3 , 2 0 0 9
TIP:
Include all your CSS files before jQuery file.
P O S T ED B Y UZ B EK J O N A T 2: 25 A M 4 C O M M ENT S
L A B ELS : I NS I G HT S , JQ UER Y, R EFER ENC E, T I P
M O ND A Y, F EB R UA R Y 2 , 2 0 0 9
<div id="top">
<div id="inner">
Some content
</div>
More content
</div>
And you need to get not only <div id="inner">Some con... but <div
id="top"><div id="inner">Some con...
Here is the code to get jQuery selector's HTML including its own:
Here we are:
This is a little trick you can use to select self HTML with jQuery's .html()
function. But if you can you should surround your markup with some dummy div
and avoid this workaround all together. This would be much faster since jQuery
http://jquery-howto.blogspot.com/ 56/73
20/01/2011 JQuery HowTo
would not need to do all the DOM manipulations.
P O S T ED B Y UZ B EK J O N A T 3: 59 A M 13 C O M M ENT S
L A B ELS : DO M , HO W T O , JQ UER Y, M A NI P UL A T I O N, S EL EC T O R S , T I P , W O R K A R O UND
First, rounded corners were done using CSS, but it got our code cluttered and it
introduced a lot of unnecessary HTML markup. Since we had full control of our
target audience's browsers and we were sure that they had JavaScript enabled
browser we chose jQuery to do all the dirty work. All we have to do to define a
box/table/anything to be in a rounded box is to give it a class "boxed" and the
rest is done with jQuery.
(function($){
$.fn.extend({
box: function() {
return $(this).each(function(){
$(this).wrap('<div class="box"><div></div><div class="tl"
></div><div class="tr"></div><div class="bl"></div><div class="br
"></div></div>');
});
}
})
})(jQuery);
/* -- Rounded Box -- */
.box{position:relative;background-color:#eee;margin-bottom:25px;p
adding:10px;}
.box .tl,.box .tr,.box .bl,.box .br{position:absolute;width:10px;
height:10px;}
.box .tl{background-image:url(images/box-tl.gif);top:0;left:0;}
.box .tr{background-image:url(images/box-tr.gif);top:0;right:0;}
.box .bl{background-image:url(images/box-bl.gif);bottom:0;left:0;
}
.box .br{background-image:url(images/box-br.gif);bottom:0;right:0
;}
.box .bg-white{background-color:#fff;padding:10px;}
P O S T ED B Y UZ B EK J O N A T 11: 25 P M 6 C O M M ENT S
L A B ELS : HO W T O , J Q UER Y, P L UG I N
W ED NES D A Y, J A N UA R Y 2 8 , 2 0 0 9
For example plugin users could provide a CSS class to set to the added column
or change the default "#" in the column header to some other meaningful text.
This is all possible by letting users of your plugin to provide their setting.
For example, in our table row count plugin, users could do this:
$('table').addCount({colName : 'Number'});
http://jquery-howto.blogspot.com/ 57/73
20/01/2011 JQuery HowTo
$.fn.addCount = function(options) {
// set up default options
var defaults = {
colName: '#',
colWidth: 100,
addCssClass: true,
colClass: 'mycolumn',
};
/*
If user provided only "colName"
option then default options for
other 3 variables will be added
to "options" variable.
*/
return this.each(function() {
/* Now you can use
"options.colWidth", etc. */
console.log(options);
});
};
The key line here is var options = $.extend({}, defaults, options); This
line merges options and defaults variables adding missing properties in
options variable from defaults variable.
var empty = {}
var defaults = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
var settings = $.extend(empty, defaults, options);
P O S T ED B Y UZ B EK J O N A T 3: 32 A M 0 C O M M ENT S
L A B ELS : HO W T O , I NS I G HT S, J Q UER Y, P L UG I N , T I P
M O ND A Y, J A NU A R Y 2 6 , 2 0 0 9
$.fn.extend({
myNamespaced: function(myArg){
return 'namespaced.' + myArg;
}
});
jQuery().myNamespaced('A');
$().myNamespaced('A'); // Shorthand $()
// Outputs: namespaced.A
Now my functions are namespaced and would not conflict with any other already
declared functions with the same name. This is great, but to access my
functions or variables I have to call jQuery() . The code still looks like chaining
not namespacing. To declare your variables or functions in jQuery namespace
you can extend the core jQuery object itself using jQuery.extend() rather than
jQuery.fn.extend() .
http://jquery-howto.blogspot.com/ 58/73
20/01/2011 JQuery HowTo
$.extend({
myNamespaced: function(myArg){
return 'namespaced.' + myArg;
}
});
jQuery.myNamespaced('A');
$.myNamespaced('A'); // Shorthand
// Outputs: namespaced.A
As you can see, now I can call my functions and properties without parenthesis
after jQuery object. Now my functions have a jQuery namespace and will not
conflict with other functions that might have the same name.
TIP:
Use $.extend({}) to namespace your fields and methods.
P O S T ED B Y UZ B EK J O N A T 6: 18 A M 8 C O M M ENT S
L A B ELS : HO W T O , J A V A S CR I P T , J Q UER Y, O O P , T I P
Recently on jQuery mailing list a user asked how he/she could add a row count
in their table automatically. So I wrote a code snippet which looks like this:
$(document).ready(function(){
$("table").each(function(){
if($(this).is('table')){
$('thead th:first-child, thead td:first-child', this).each(
function(){
if($(this).is('td'))
$(this).before('<td>#</td>');
else if($(this).is('th'))
$(this).before('<th>#</th>');
});
$('tbody td:first-child', this).each(function(i){
$(this).before('<td>'+(i+1)+'</td>');
});
}
});
});
This code was for specific case, where there is only one table on the page and it
has only one row in its header. That is why I took into the account the possibility
of row spans and multi line rows in header and rewrote the code. Then made a
plugin out of it.
(function($){
$.fn.extend({
addCount: function() {
return $(this).each(function(){
if($(this).is('table')){
$('thead th:first, thead td:first', this).each(function
(){
if($(this).is('td'))
$(this).before('<td rowspan="'+$('thead tr').length
+'">#</td>');
else if($(this).is('th'))
$(this).before('<th rowspan="'+$('thead tr').length
+'">#</th>');
});
$('tbody td:first-child', this).each(function(i){
$(this).before('<td>'+(i+1)+'</td>');
});
}
});
http://jquery-howto.blogspot.com/ 59/73
20/01/2011 JQuery HowTo
}
});
})(jQuery);
$('table').addCount();
$('.some-table-class').addCount();
$('#some-table-id').addCount();
P O S T ED B Y UZ B EK J O N A T 11: 30 P M 5 C O M M ENT S
L A B ELS : HO W T O , J A V A S CR I P T , J Q UER Y, M A NI P UL A T I O N, P L UG I N, T I P
W ED NES D A Y, J A N UA R Y 2 1 , 2 0 0 9
function User() {
// Private property
var name = '';
return {
// Public property
classVersion: '1.3',
prevVersions: ['1.2.3', '1.2', '1'],
setName: function(newName) {
name = newName;
},
getName: function() {
return name;
}
};
}
var user = new User();
user.classVersion; // 1.3
user.prevVersions; // ['1.2.3', '1.2', '1']
NOTE:
Define an object property name in your return statement and it will be accessible
from outside. In other words - public field.
Basically:
function User() {
// Private variable
var name;
// Private method
var privateMethod = function(){
// Access to private fields
name += " Changed";
};
return {
// Public methods
setName: function(newName) {
name = newName;
privateMethod();
},
http://jquery-howto.blogspot.com/ 60/73
20/01/2011 JQuery HowTo
getName: function() {
return name;
}
};
}
var user = new User();
user.setName("My Name");
user.getName(); // My Name Changed
As you can see, privateMethod and name are declared outside the return
object and thus they are made private. Variables declared inside the return object
are public and accessible using dot notation.
P O S T ED B Y UZ B EK J O N A T 6: 34 A M 6 C O M M ENT S
L A B ELS : HO W T O , J A V A S CR I P T , O O P , T I P
I had a page with one unordered list with 1000 items each with a class
(class="1", class="2", etc).
console.time("testClass");
for(i=0;i<100;i++){
$('.'+i);
}
console.timeEnd("testClass");
/** /**
* jQuery 1.2.6 * jQuery 1.3
1235 ms 54 ms
1326 ms 52 ms
1342 ms 53 ms
======= =======
1301 ms 53 ms
*/ */
As you can see the new selector engine is freakishly fast :) Actually with this
specific test it is 25 times fast. Taking into the consideration that class selection
is one of the most used selectors, we can assume that our code will work
considerably faster.
NOTE:
I have performed the same tests with selection with id's. The result were exactly
the same (9 ms). Taking into the consideration that both versions of jQuery use
browser's built in getElementById() function for ID selections, there is not
much one can do to beat that.
P O S T ED B Y UZ B EK J O N A T 5: 18 A M 4 C O M M ENT S
L A B ELS : JQ UER Y, P ER FO R M A NCE, S ELEC T O R S , T EST
T H UR S D A Y, J A NUA R Y 1 5 , 2 0 0 9
http://jquery-howto.blogspot.com/ 61/73
20/01/2011 JQuery HowTo
Attributes
1. event.type
2. event.target
3. event.relatedTarget
4. event.currentTarget
5. event.pageX/Y
6. event.result
7. event.timeStamp
Methods
1. event.preventDefault()
2. event.isDefaultPrevented()
3. event.stopPropagation()
4. event.isPropagationStopped()
5. event.stopImmediatePropagation()
6. event.isImmediatePropagationStopped()
Anonymous functions that were bind to your elements will receive this new
(jQuery.Event) event object and can utilize it's new attributes and methods. So
your previous code will work fine (most of the time :) ).
$("a").click(function(event) {
alert(event.type);
});
The fun part starts when you trigger events with jQuery.Event. You can create
new jQuery.Event object and give it to the trigger() 'er to trigger that event.
Example:
NOTE:
You don't have to use new to create a new jQuery.Event object. It is optional.
$("a").trigger({
type:"click",
user:"username",
pass:"password"
});
Try to play with the new event attributes and methods. You can do all kinds of
fun things with them. Example: event.result , event.relatedTarget.
P O S T ED B Y UZ B EK J O N A T 7: 14 A M 2 C O M M ENT S
L A B ELS : EV EN T S, HO W T O , I NS I G HT S , J Q UER Y, R EFER ENC E
W ED NES D A Y, J A N UA R Y 1 4 , 2 0 0 9
Notable changes:
http://jquery-howto.blogspot.com/ 62/73
20/01/2011 JQuery HowTo
.hide() and .show() are now much faster (~2.5x faster)
[@attr] syntax deprecated, use [attr]
and many many more. Please read release notes.
P O S T ED B Y UZ B EK J O N A T 7: 04 A M 0 C O M M ENT S
L A B ELS : JQ UER Y, NEW S
According to general opinion of developers on the net (and jQuery official site)
you should use Yahoo's YUI Compressor to compress your jQuery and
JavaScript code.
P O S T ED B Y UZ B EK J O N A T 6: 05 A M 5 C O M M ENT S
L A B ELS : HO W T O , J A V A S CR I P T , J Q UER Y, L I NK , P ER FO R M A NC E, R ESO UR C E, T I P
M O ND A Y, J A NU A R Y 1 2 , 2 0 0 9
For cases like that you can use online JavaScript code validator JSLint.
P O S T ED B Y UZ B EK J O N A T 4: 37 A M 0 C O M M ENT S
L A B ELS : ER R O R , HO W T O , J A V A S C R I P T , LI NK , R ES O UR C E, T ES T
FR I DA Y, J A NUA R Y 9, 2009
To access HTML image map area attributes and properties use something like
this:
$('area').click(function() {
var url = $(this).attr('href');
var coords = $(this).attr('coords').split(',');
http://jquery-howto.blogspot.com/ 63/73
20/01/2011 JQuery HowTo
});
P O S T ED B Y UZ B EK J O N A T 5: 14 A M 5 C O M M ENT S
L A B ELS : HO W T O , HT M L, J Q UER Y, R EFER ENC E, S EL EC T O R S , T I P
T H UR S D A Y, J A NUA R Y 8 , 2 0 0 9
<div>Outermost element
<div>Some Text
<div>Evenmore text
<div>Who cares anymore?
<div>Innermost Element</div>
</div>
</div>
</div>
</div>
So I needed to select the innermost div and append another div to it. There is no
jQuery selector but you can use selectors that exist to achieve this goal. The
innermost element would be the last div with the only-child.
$('div:only-child:last');
P O S T ED B Y UZ B EK J O N A T 3: 01 A M 2 C O M M ENT S
L A B ELS : HO W T O , J Q UER Y, S ELEC T O R S, T I P
W ED NES D A Y, J A N UA R Y 7 , 2 0 0 9
function User() {
var name = '';
return {
setName: function(newName) {
name = newName;
},
getName: function() {
return name;
}
}
}
var user = User();
user.setName("My Name");
user.getName(); // My Name
The User() class we just created could be considered a bean in Java. Using this
template you can have as many private fields and public methods as you want.
P O S T ED B Y UZ B EK J O N A T 6: 51 A M 2 C O M M ENT S
L A B ELS : HO W T O , J A V A S CR I P T , O O P , R EFER ENC E, T I P
T U ES D A Y, J A NU A R Y 6 , 2 0 0 9
http://jquery-howto.blogspot.com/ 64/73
20/01/2011 JQuery HowTo
How jQuery's plugin/extension system works
Recently I was reading about extending jQuery's functionality and plugin system.
I wrote two articles on extending jQuery functionality with your own custom
functions. To extend you write $.fn.myFunction and then your function. It was
interesting what $.fn is, so I look through the jQuery code and on line 33 found:
jQuery.fn = jQuery.prototype = {
So jQuery's fn is just a synonym for its prototype. I know this is not a discovery
of the century but it gives you some understanding of how jQuery's plug-in
system works and its insights.
P O S T ED B Y UZ B EK J O N A T 2: 28 A M 0 C O M M ENT S
L A B ELS : I NS I G HT S , JQ UER Y, P L UG I N, R EFER ENC E
M O ND A Y, J A NU A R Y 5 , 2 0 0 9
Now back to JavaScript code performance testing. I have an unordered list with
1000 items. First test will have list items with class attributes and the second
list will have id attributes set to its items.
console.time('test');
for (i = 0; i < 500; i++) {
$('.'+i);
}
console.timeEnd('test');
// ~8204ms
console.time('test');
for (i = 0; i < 500; i++) {
$('#'+i);
}
console.timeEnd('test');
// ~32ms
As you can see selecting with element's #id is much faster. In our case 256
times (8204/32).
P O S T ED B Y UZ B EK J O N A T 3: 16 A M 0 C O M M ENT S
L A B ELS : JQ UER Y, P ER FO R M A NCE, S ELEC T O R S , T I P
T U ES D A Y, D EC EM B ER 3 0 , 2 0 0 8
Exam ple:
// To disable
$('.someElement').attr('disabled', 'disabled');
In order to enable any disabled element you need to set the disabled attribute
to empty string or remove it entirely like in the code below.
// To enable
$('.someElement').removeAttr('disabled');
And that’s basically how to disable and enable HTML / DOM elements on your
website using jQuery. You can see this code in action in real life example of
http://jquery-howto.blogspot.com/ 65/73
20/01/2011 JQuery HowTo
Disabling submit button on form submission post.
P O S T ED B Y UZ B EK J O N A T 1: 58 A M 15 C O M M ENT S
L A B ELS : A T T R I B UT ES , B EG I NNER , HO W T O , J Q UER Y, M A NI P ULA T I O N, R EFER ENC E, T I P
M O ND A Y, D EC E M B ER 2 9 , 2 0 0 8
Caching in jQuery
What is great about jQuery is its simplicity in selecting elements. We all use it
here and there, basically everywhere. This simplicity comes with its drawbacks.
jQuery traverses through all elements every time we use selectors. So to boost
up your jQuery application you should always cache your selections to some
variable (if you find yourself using the same selection more than once). In case
you are not selecting an element more than once you should not cache your
selection by assigning it to some variable.
console.time('test');
for (i = 0; i < 1000; i++) {
$('.the').text(i + ' ');
}
console.timeEnd('test');
// ~260ms
console.time('test2');
var the = $('.the');
for (i = 0; i < 1000; i++) {
the.text(i + ' ');
}
console.timeEnd('test2');
// ~30ms
P O S T ED B Y UZ B EK J O N A T 9: 47 P M 7 C O M M ENT S
L A B ELS : HO W T O , J Q UER Y, P ER FO R M A NC E, S EL EC T O R S , T I P
M O ND A Y, D EC E M B ER 2 9 , 2 0 0 8
// First way
$('#checkBox').attr('checked');
// Second way
$('#edit-checkbox-id').is(':checked');
http://jquery-howto.blogspot.com/ 66/73
20/01/2011 JQuery HowTo
);
// Third way == UPDATE jQuery 1.3
$("input[type=checkbox][checked]").each(
function() {
// Insert code here
}
);
First two methods return true or false . True if that particular checkbox was
checked or false if it is not checked. The third method iterates though all
checkboxes with checked attribute defined and performs some action.
See the latest jQuery tips. They are sho rt, very sho rt!
Want to learn how to check if jQuery.js is loaded into the current document?
Also learn how to work with jQuery 1.3's new Event object.
P O S T ED B Y UZ B EK J O N A T 4: 18 A M 19 C O M M ENT S
L A B ELS : A T T R I B UT ES , B EG I NNER , HO W T O , HT M L , J Q UER Y, R EFER ENC E, T I P
console.time('timerName');
console.timeEnd('timerName');
You can use this script to test your JavaScript code. timerName in the code can
be any name for your timer. Don't forget to end your timer using the same name
for timeEnd() .
P O S T ED B Y UZ B EK J O N A T 4: 26 A M 0 C O M M ENT S
L A B ELS : FI R EB UG , HO W T O , JA V A S C R I P T , P ER FO R M A NC E, R EFER ENC E, T ES T , T I P
T H UR S D A Y, D EC EM B ER 2 5 , 2 0 0 8
I came across this feature of JavaScript recently and thought I would share it with
you. So every object I tried to use had capabilities of array. I could refer to
object/class members and properties using array syntax. For example:
function myFunk(){
this.name = "My Name";
http://jquery-howto.blogspot.com/ 67/73
20/01/2011 JQuery HowTo
}
alert( obj["newMethod"]() );
TIP:
In case you want your methods to be available to all class instance use
prototype .
P O S T ED B Y UZ B EK J O N A T 5: 28 A M 0 C O M M ENT S
L A B ELS : HO W T O , J A V A S CR I P T , T I P
T U ES D A Y, D EC EM B ER 2 3 , 2 0 0 8
(function ($) {
// code goes here
})(jQuery)
Little research shows that this allows the use of $ within this function without
conflicting with other JavaScript libraries who are using it. Basically, since we are
setting $ as a parameter, $ will overwrite any globally defined
variables/references of $ in that particular anonymous function.
So basically it’s an anonymous function that lets jQuery play nicely with other
javascript libraries that might have $ variable/function. Also if you notice, all
jQuery plugins code is wrapped in this anonymous function.
NOTE:
The following two javascript codes are equivalent:
// Code 1:
(function ($) {
// Javascript code
})(jQuery)
// Code 2:
var myFunction = function ($) {
// Javascript code
};
myFuntion(jQuery);
P O S T ED B Y UZ B EK J O N A T 11: 40 P M 2 C O M M ENT S
L A B ELS : HO W T O , J Q UER Y, R EFER ENC E, T I P
M O ND A Y, D EC E M B ER 2 2 , 2 0 0 8
$.fn.myFunction = function() {
return $(this).addClass('changed');
}
http://jquery-howto.blogspot.com/ 68/73
20/01/2011 JQuery HowTo
And now, use it like this:
$('.changePlease').myFunction();
P O S T ED B Y UZ B EK J O N A T 9: 55 P M 7 C O M M ENT S
L A B ELS : HO W T O , J Q UER Y, P L UG I N, R EFER ENC E, T I P
M O ND A Y, D EC E M B ER 2 2 , 2 0 0 8
<script src="http://www.google.com/jsapi">
</script>
<script type="text/javascript">
google.load("jquery", "1.2.6");
google.setOnLoadCallback(function() {
// Your code goes here.
});
</script>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min
.js"
type="text/javascript"></script>
http://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js
http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js
http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js
http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js
http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js
http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js
<script src="http://www.google.com/jsapi">
</script>
<script type="text/javascript">
google.load("jquery", "1.3.2");
google.load("jqueryui", "1.7.2");
google.setOnLoadCallback(function() {
// Your code goes here.
});
</script>
<!-- OR -->
<script
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-u
i.min.js"
http://jquery-howto.blogspot.com/ 69/73
20/01/2011 JQuery HowTo
type="text/javascript"></script>
P O S T ED B Y UZ B EK J O N A T 9: 43 P M 8 C O M M ENT S
L A B ELS : HO W T O , J Q UER Y, L I NK , P ER FO R M A N C E, R EFER ENC E, T I P
M O ND A Y, D EC E M B ER 1 5 , 2 0 0 8
(function($){
$.fn.extend({
myFunk: function() {
// You must return jQuery object
return $();
},
myPunk: function() {
return this.addClass('punked')
.bind('click', function(){
alert('You were punked!');
});
}
});
})(jQuery);
$('.select').myFunk();
$('.select').myPunk();
jQuery uses method chaining pattern so you need to return jQuery object from
your newly created methods.
P O S T ED B Y UZ B EK J O N A T 3: 19 A M 2 C O M M ENT S
L A B ELS : HO W T O , J Q UER Y, P L UG I N, R EFER ENC E, T I P
S UN D A Y, D EC EM B ER 1 4 , 2 0 0 8
NOTE:
Make sure you don't bind the same event to the elements with this event already
bound.
TIP:
You should somehow separate newly created elements and then bind event in
callback of an AJAX function.
Regarding the tip above. Here are two ways of separating AJAX loaded content:
http://jquery-howto.blogspot.com/ 70/73
20/01/2011 JQuery HowTo
Update: A dded a demo page that show s how to bind events to
A JA X lo aded elements here.
P O S T ED B Y UZ B EK J O N A T 1: 03 A M 7 C O M M ENT S
L A B ELS : A JA X , EV ENT S , HO W T O , JQ UER Y, T I P , W O R K A R O UND
S A T UR D A Y, D EC EM B ER 1 3 , 2 0 0 8
$('.someClass').length;
Also, you can use built in jQuery helper function called .size() . It returns the
same value as .length property but it is slightly slower, however the difference
is insanely small. So you can use .length or .size() depending on your
choice.
P O S T ED B Y UZ B EK J O N A T 1: 40 A M 2 C O M M ENT S
L A B ELS : A T T R I B UT ES , B EG I NNER , HO W T O , I NSI G HT S , J Q UER Y, R EFER ENC E,
S EL ECT O R S , T I P
The error occurs when my application tries to do an AJAX request call to local
resource. In other words, 'Access to restricted URI denied" code: "1012' error
occurs when javascript tries to load a file from my hard drive. The file type let it
be CSS, HTML, javascript does not matter.
Reason:
1. The reason for the error is Firefox's security model that does not allow
retrieving/accessing localhost resources.
2. Also Firefox does not allow accessing resources from other domains
(NOTE: www.example.com and example.com are considered two different
domains as well).
Solution:
1. So, to solve this problem you need to deploy your files to your web server
or run one locally. You can run XAMPP or lightweight Denwer (similar to
XAMPP, but it is in Russian).
2. To access resources from other domains you can put a simple proxy
script, as it is described in this “Cross domain AJAX scripting” post.
P O S T ED B Y UZ B EK J O N A T 1: 17 A M 23 C O M M ENT S
L A B ELS : A JA X , ER R O R , FI R EB UG , JA V A S C R I P T , R EFER ENC E, W O R K A R O UND
S A T UR D A Y, N O V EM B ER 1 , 2 0 0 8
http://jquery-howto.blogspot.com/ 71/73
20/01/2011 JQuery HowTo
Set HTML tag’s / element’s attribute
In our previous post about “How to get an element’s / tag’s attribute” I described
how to get element’s attribute. In this post I would like to show you how to set
any HTML tag’s or element’s attributes. Don’t forget, jQuery can set any
attributes like id, class, style, name, title, etc.
NOTE:
You are not limited to W3 Consortium defined set of HTML attributes. So you
can also set your own attributes with their own values.
Here is an example:
You can use .attr("myAttr") to get the set attribute value. Cool ha?!
P O S T ED B Y UZ B EK J O N A T 7: 31 A M 3 C O M M ENT S
L A B ELS : A T T R I B UT ES , B EG I NNER , HO W T O , J Q UER Y, M A NI P ULA T I O N
Example:
Consider we have the following HTML tags on our page with corresponding
attributes:
And to get container's id attribute and the link's title attributes, we would use
the following jQuery code:
NOTE:
If your jQuery selection returns more than once element, .attr() function would
return only the first element’s attribute.
P O S T ED B Y UZ B EK J O N A T 7: 11 A M 2 C O M M ENT S
L A B ELS : A T T R I B UT ES , HO W T O , JQ UER Y
http://jquery-howto.blogspot.com/ 72/73
20/01/2011 JQuery HowTo
© jQuery How to. jQuery is a javascript framew ork or javascript library that abstracts common javascript tasks and gives developers
tools to get on w ith their lives. This blog - "jQuery How To" is a collection of jQuery How tos and resources related to
jQuery library.
http://jquery-howto.blogspot.com/ 73/73