jQuery Tips and Tricks

I have been busy dealing with jQuery lately with a project in hand which has given me a lot of hands on with jQuery. Therefore, I would like to share some of the things I came across when I was working with jQuery. If you still confuse what i am talking about you may want to visit my previous post on jQuery.

1.     jQuery id and class selector.

jQuery selector can only selects one id but is able to select multiple classes. For example, you have a multiple id with the same name,

<div id='sameid'></div>
<div id='sameid'></div>

with a declaration of selector as follow,

$('div#sameid')

jQuery will only retrieve the first id it sees. However, if your declaration is a class instead of id,

<div class='sameid'></div>
<div class='sameid'></div>

with a declaration of selector as follow,

$('div.sameid')

it will provide you with a set of jQuery object that contains the two object above.

2.     jQuery animation lag during hover on multiple objects.

jQuery has an event 'hover' which act exactly similar to 'hover' in CSS. However, when we try to render hover on multiple set of elements, an animation lag may occur that doesn't seem smooth. This may be a problem with the way the code has been written. Let me show you what i meant here, take a look at playgroundblues.com, notice they have a nice navigation bar on the left hand side which display nicely on the left corner. The problem with this navigation bar is when you try to move very fast across the multiple objects several times, you will notice the animation continues to perform although your hover has already ended.

If we look at his code written for the menu,

playgroundbluescom-source-code

You will notice that there are two selector of $('#navigation > li') where one assign the hover function while the other perform the nice welcome sliding when visitor enters their side. There are no problems with the logic on the code above but because the codes for animation are being separated to two assignments, it created the lag during the animation. If all the assignment is done on a single selector of $('#navigation > li') through chaining, the animation lag will be eliminated.

3.  $(this) and 'this' .

Often enough i find myself getting confuse with when to use $(this) and 'this' in jQuery. The differences are $(this) refers to ALL jQuery objects while 'this' refers to the calling object in javascript.  For example, we want to use .each and fadeIn() of jQuery after a selector such as below,

$('div#product').each(function(){
$(this).fadeIn()
})

since fadeIn() is a jQuery effect function, we use $(this) but if we are not dealing with jQuery objects we used 'this' instead.

$('div.product').each(function(){
var myClass = this.className; // provided you have multiple class product
})

The reason why 'this' can be used here is due to the function of jQuery .each which look into each DOM object. Simple to say, this refer to the normal DOM object while when you have the extra $(xxxx), it will refer it to a jQuery object which allows you to use jQuery method.

4. find() function in jQuery

Being a forgetful person (which is why i have this blog), i often find myself forgetting what does the code $('a', this) in jQuery means. It basically means, find anchor object in 'this'. It is just a shortcut for jQuery to subsitute find () method.

5. ',' in jQuery selector.

You may have a chance to see $("div#idx, div#idc") and confuse got confuse with it as this doesn't look like anything on the api of jQuery! It is just another quick function in jQuery to do a selector in a single declaration instead of multiple statement. The ',' comma represent the 'OR' condition which is similar to '||' in java or javascript. So the selector i wrote means "select div with id idx or div with id idc".

That is all I can remember from what had happen during my coding with jQuery. If there are any more tips that I have come across during my coding, i will update here! Hope these helps! Cheers!

How CSS containers overlap and float on each other

We all know containers that web designers or even programmers used on the web! If we ignore all the coding you will find that all these things are actually done by CSS! i created two container with the following code,

<html>
<head>

<style>
#box1 {
width:450px;
height:338px;
background:#23e;
float: left;

}
#box2 {
width:450px;
height:338px;
background:#000;
padding: 5px 5px;
margin: 10px 10px;
position: absolute;
float: left;
z-index: 1;
}
</style>
<script>

</script>
</head>

<body>
<div id='box1'></div>
<div id='box2'></div>
</body>
</html>

You can have a look at the example HERE, notice that the black box is overlapping the blue box? The blue box has the CSS of box1 while the black box has the CSS of box2. The reason why it is overlapping was because of the following declaration,

<pre class="brush: php; title: ; notranslate" title="">  position: absolute;
 float: left;
 z-index: 1;

position absolute must be there to tell the page that the position must absolutely be obey and only with this declaration, z-index can be used. z-index tells the box to go 1 up (float upward) while negative means it will go downwards. So if i want the blue box to be overlapping the black instead, i will place z-index:-1, this way it will go below the blue box. While float:left tells the box to appear on the left side. If i do not want them to be overlapped, i will remove the declaration of position:absolute, this way z-index will not be valid and it will become side by side as shown HERE.

CSS is capable of styling and perform layout for your site! If i have another box name box3 and wanted the box to be place below the two box what do i do? assume the code declaration is as below,

<pre class="brush: php; title: ; notranslate" title=""><html>
<head>

<style>
#box1 {
width:250px;
height:338px;
background:#23e;
float: left;

}
#box2 {
width:250px;
height:338px;
background:#000;
padding: 5px 5px;
margin: 10px 10px;
float: left;

}

#box3 {
width:250px;
height:338px;
background:#23e;
float: left;
clear: left;
}
</style>
<script>

</script>
</head>

<body>
<div id='box1'></div>
<div id='box2'></div>
<div id='box3'></div>
</body>
</html> 

in box3, there is a new declaration, clear:left. This tells the page that box3 left side shall not have any other element which makes box3 move down to a new line. Click Here for example.Notice that this kind of layout is called a fixed layout where the boxes width cannot be more than the user screen width. If a liquid layout is being applied, the boxes will resize according to the user screen size. In order to change the fixed layout to a liquid layout, we just have to change the width to % instead of px.

Introduction to jQuery basic 2

There are many powerful methods used by the wrapper of jQuery. But i can't really discuss it right here as it will take too long to read. However, i will explain the api of each section of jQuery! This way it will make life easy for us when we are searching the api at jQuery official site!

jQuery Core:

jQuery Core contain all the functions available in jQuery that you need to extend, create, manipulate jQuery objects

Selectors:

It's like what the section name said! This section give you all the functions used by jQuery wrapper to filter its selection!

Attributes:

Attributes section provide you with all the functions available in jQuery to manipulate Attributes of DOM. This include CSS, attributes and properties.

Traversing:

This section provides all the functions jQuery have when chaining with jQuery.

Manipulation:

jQuery text/DOM Manipulation functions.

CSS:

jQuery CSS functions that manipulate the data in or css file.

Events:

All the add-on event that developers can use with jQuery other than the default javascript events available.

Effects:

All the special effects available in jQuery.

Ajax:

jQuery ajax functions that help reduce the risk of using Ajax technology and shorten the need to write lengthy codes for it.

Utilities:

jQuery Utilities function which provides extra feature other than the one given in JavaScript.

jQuery UI:

This is the official documentation for jQuery UI, jQuery's visual controls. jQuery UI features a wide range of core interaction plugins as well as many UI widgets. The project homepage is located at jqueryui.com. Please visit these pages for downloading UI and many demos. (taken from the offical site)

Well, i believe once you guys have read the first basic tutorial of jQuery, this is basically just a lookup for people who want to know what each individual api is for. And seriously speaking, once you have done the first part of jQuery, working with jQuery isn't that difficult as long as you can read the api provided by jQuery team. For people who have foundation of such api from Java, this is a piece of cake!

Introduction to jQuery basic for beginners

Introduction

jQuery is one of the many framework provided online to help developers to minimize the time needed to write advance coding. It provides many useful feature to help developers to overcome cross browser issues. Best of all, it is extremely light-weight for optimization! jQuery has a large community and available plugin for different purposes. What jQuery can do for you? Powerful stuff! Check out their plugin made by other developers all over the world!

Since i am also new to jQuery, i believe there will always be new comer entering new technology and feature. So here i am writing this article to introduce some of the basic i learn in jQuery and hope it will help others too. Please bear in mind before we start, jQuery selection will always return you a set of jQuery object which you can use to do a chain operation(chaining is the powerful part of jQuery).

Element Manipulation

Let's start with jQuery element manipulation. For starters, jQuery is written in the following two ways,

$(selector)

or

$jQuery(selector)

This is the basic thing a jQuery programmer will need to know when dealing with jQuery. This is more like a declaration for jQuery.  The '$' symbol and jQuery is the namespace used in jQuery. With just this knowledge, you can do a lot of things in jQuery. Below listed different way of manipulating the element in jQuery.

$("p a")

retrieve the group of links nested inside a

element

$("div.notLongForThisWorld").fadeOut();

fade out all

elements with the CSS class notLongForThisWorld

$("div.notLongForThisWorld").fadeOut().addClass("removed");

add a new CSS class, removed, to each of the elements in addition to fading them out. The fadeOut() is a function in jQuery that will fade the element out of the screen while addClass(css class name) adds a new class to the element.

$("#someElement").html("I have added some text to an element");

or

$("#someElement")[0].innerHTML ="I have added some text to an element");

add the text 'I have added some text to an element' to the element which hold the id 'someElement'. The first adds to all elements that contain this id the second only place the text into the first element it sees. The .html('') is similar to innerHTML.

$("p:even");

This selector selects all even

elements. even is one of the Filter in jQuery

$("tr:nth-child(1)");

This selector selects the first row of each table.nth-child(index/even/odd/equation) is one of jQuery Child Filter.

$("body > div");

This selector selects direct

children of <body>. the symbol '>' is one of jQuery Hierarchy

$("a[href$=pdf]");

This selector selects all links to PDF files. the [attribute$=value] is one of jQuery Attribute Filter

$("body > div:has(a)")

This selector selects direct

children of <body>-containing links. The above combine different Filter and Hierarchy.

$('img[alt],img[title]')

match all elements that have either an alt or a title attribute.

if you haven't notice, the syntax used in the string are mostly used in CSS too which is used to select the specify element to apply the style on. This is also being used in jQuery during selection. jQuery has its own advance selection too which are the filters and hierarchy example shown above. jQuery uses some form of regular expression to perform its selection but the author had made it very abstract for the developers(great!). You guys can visit http://docs.jquery.com/Selectors for more selector manipulation functions and example.

Utility Functions

jQuery itself has many other Utility functions that can be used by developers. An example to use a function 'Trim' is as follow,

$.trim(" testing ")

the above will provide a trimmed version of 'testing' without spaces in between the word. It can also be

jQuery.trim(" testing ")

There are many other function that can be found in http://docs.jquery.com/Utilities which is useful when dealing with application.

Document Ready Handler

Traditionally we have the onload method given in javascript. However, the onload event handler  is evil because it not only wait for the DOM tree to be fully created, it also waited for all other element in the page to finish loaded. This means that only when the page has fully loaded, will the function in the onload event handler starts activating. Most of the time the user will long be gone before your page has loaded(images loaded last and longest). Speed is everything nowadays.

jQuery provided a event handler called 'ready' which is very handle. It is not only cross browser compatibility, it also eliminate the 'problem' caused by onload function. The ready event handler will load once the DOM tree has fully loaded. This way, both the images and functions of javascript can be proceed. This promote synchronisation. Furthermore, the jQuery ready event handler is able to be nested in the script unlike onload handler which only allow a single function.

Example,

$(document).ready(function() {$("table tr:nth-child(even)").addClass("even");});

This is a formal syntax when calling .ready event handler.

$(function() {$("table tr:nth-child(even)").addClass("even");});

While this is an shorthand form. (By passing a function to $())

Making DOM Element

Making DOM element for cross browser is never an easy task. Most programmers will face issues when dealing with IE in making DOM element. jQuery helps to eliminate all these problem by simplifying it.

Example,

$("<p>Just like this</p>")

To create a DOM element in jQuery is as simple as writing a tag in HTML!

Extending jQuery

Wish to extend the Capability of jQuery? You can, by writing the following code.

$.fn.disable = function() {	return this.each(function() {	if (typeof this.disabled != "undefined") this.disabled = true;	});}

The above code tells jQuery that we are defining a new method 'disabled' by extending the $ wrapper by using the sentence '$.fn'.

Conclusion

From the above we can see how powerful jQuery is. Learning more about it and working with this existing library will help alot in the future! Especially when it comes to cross browser and file size, jQuery is one of the best among the framework available. Furthermore, there is a very large community for this framework that can assist your growth in jQuery. Of course, there are alternative such as MooTool that also provided the same competitive advantages similar to jQuery.Unfortunately, I have not a chance to experience MooTool yet. Hopefully i will in the future! The above example mostly has been taken in the book 'jQuery in Action' by Bear Bibeault and Yehuda Katz. Great book for people who has a understanding on DOM, CSS and javascript.

Tutorial: Basic Horizontal Type Tools Function

Here are some of the way you can work with Horizontal Type Tools.

If you wish to split the character after you have finish typing, you can do this by right click your text layer and select 'Convert to Shape'. Once it has been converted, you can use 'Path Selection Tool' or 'Direct Selection tool' to move and manipulate your text.

untitled126

untitled127

Well..If you would like your text to follow a path you can select your pen tools and draw the path. Next, use the Horizontal Type Tool and lookout for the symbol 'I' when your mouse go near the starting path drawn by your pen tools. Once you get it, click on it and start typing your text.

untitled128

untitled129

If you would like to extract the background of your written text, you can do this by using the Horizontal Type Mask Tool. Use that and type your text on the image you wish the text to have(Make sure the layer you used this tools have the background on it). Since our selection is still there, we have to reverse it, so we go to select->inverse and duplicate the layer. Finally, we click delete button on our keyboard to delete away all other text other than the text itself.

untitled130

untitled131

untitled132

If you would like your text to contain shape you can do click ont he icon 'Create Wraped Text' and it will give you a list of function you can do to wrap your text nicely.

untitled133

Other than the one mention above, you can style your text such as changing size,font etc. etc. It's all up to you~