July 2009 - Posts

Quick poll: which color scheme for blog posts?
Thu, Jul 30 2009 22:30

Guys, which one of these do you prefer: the light one or the black one? For working I do really prefer darker schemes, but it seems like they don’t work very well with the JS editor…

by luisabreu | 12 comment(s)
Filed under:
JQuery: DOM 0 level event model
Thu, Jul 30 2009 13:49

Today we’re going to start talking about JQuery event’s propagation. Before delving into JQuery’s behavior, I guess that we need to make a small detour and talk about JAvascript and DOM events levels compatibility. By now, most of us have already heard the terms DOM level 0 event compatible or DOM level 2 event compatible. But what does this mean? The first thing you should keep in mind is that there are several levels and that each level specifies several features that should be implemented by all compatible browsers.

The first level is know as DOM Level 0 and was based on the event model introduced by the first browsers (notice that there really isn’t a DOM level 0 standard). Currently, this level is supported by all existing browsers. Level 0 gives you two options for handling events. You can hook up an event and a function by using an attribute on the form onXXX, where XXX is the event you want to handle. Take a look at the following snippet:

<input type="button" value="Say hi!" id="bt" onclick="sayHi()" />
<script type="text/javascript">
 function sayHi(evt) {
  alert("hi!");
 }
</script>

I guess that we’ve all written this code in the past, right? Not really good quality code, but hey, it works in all browsers, right? The second option for this level relies on the mappings that exist between HTML attributes and properties on JS objects that represent HTML elements (we’ve already talked about this in a previous post). The next snippet is equivalent to the previous one, but relies on JS code:

<input type="button" value="Say hi!" id="bt" />
<script type="text/javascript">
 $("#bt")[0].onclick =  function(evt) {
                          alert("hi!");
                         }
</script>

Now, even though this option is better than the previous one (notice that we removed the JS code from the markup), there are still some problems. For instance, if anyone else hooks an event that has been previously set, it will end up removing the previous handler.

Even at this level, there are still some differences between browsers. For instance, if you look at the previous examples, you’ll notice that the function receives an evt parameter. That parameter should automatically references the event object that contains information about the current event. Unfortunately, IE doesn’t comply with this and you’ll find a reference to the current event object on the window’s event property.

Now, level 0 event introduced another very interesting feature: event bubbling. Whenever an event is generated at an element, it will propagate until it reaches the top level element. That’s why it’s called bubbling: it goes in a bottom-up direction. Take a look at the following example:

<div id="top">
    <div id="inner">
        <p id="paragraph">Just some text</p>
    </div>
</div>
<script type="text/javascript">
    $("*").each(function() {
        this.onclick = function(evt) { alert(this.id); };
    });
</script>

The previous example will use DOM 0 level code for setting up the click event of all existing DOM nodes. If you run the code, you’ll see that you’ll get an alert starting and the p element and then the event will propagate until it reaches the top HTML element (to see this you’ll probably need to replace the this.id with this.tagName expression in the alert invocation).

Now, this is really cool because it means you can handle a specific event by hooking up that event at a top level. Cancelling the default bubbling is possible: just call the event’s stopPropagation method.

function(evt) { alert(this.id); evt.stopPropagation();  };

Notice that this really isn’t a level 0 feature (in fact, it’s a level 2 feature). As you might expect by now, IE uses a different method for cancelling propagation: the event’s cancelBubble property must be set to true (don’t forget that in IE you need to use window.event to get to the event object).

There’s still one more thing you need to know before we call it a day: some events have predefined default actions assigned to them. I guess that the most known example is submitting a form. Form submission generates a submit event which, by default, ends up sending the form’s data through a post or get request. Notice that this will happen even if you set up an event handler:

<form method="post" id="frm">   
    ´<input type="submit" value="submit form" />
</form>
<script type="text/javascript">
    $("#frm")[0].onsubmit = function(evt) {
        alert("submitting");
        //how to cancel default action?
    };
</script>
If you run the previous code, you’ll always get a post request. The question is: how can I cancel that form submission? In these cases, most people will simply return false from this method. By doing that, you’re saying that you’re not interesting in getting the default behavior associated with that event. DOM 2 level introduces a preventDefault method you can use to signal the cancellation of the default action associated with an event. Notice that this method won’t cancel event bubbling. I guess that we’re already starting to go into DOM level 2 event land, so we’ll stop here. On the next post we’ll look at what DOM level 2 introduced so that we can finally take a look at how JQuery protects us from knowing all this stuff. Keep tuned!
by luisabreu | 8 comment(s)
Filed under:
JQuery: binding handlers for current and future element’s events
Wed, Jul 29 2009 22:24

The latest version of JQuery (1.3 at the time of writing) added a really cool feature: binding a function to current and future elements’ events. Until now, we’ve seen how we can use the bind method for setting up an event handler. For instance, the following snippet will hook up the click event of all existing spans:

$("span").click(function() { alert("clicked"); });

Now, the problem is that if you add any new span to the page, then you’ll also need to add code for hooking up the event. The live method solves this problem and will bind all existing and future elements that match the initial criteria to a specific function. Its syntax is really similar to the bind method, as you can see from the next snippet:

$("span").live("click", function() { alert("clicked"); });

There are some gotchas that might affect the use of this method. For instance, currently the method will only work against selectors. So, if you have something like this:

$("span").parent().live("click", function() { alert("clicked"); });

then you’d be disappointed because things won’t work as expected. There’s also the bubbling thingy, but that will only make sense after we discuss event propagation (which we’ll leave for a future post). Unlike bind, where the first parameter can be a space delimited string with the name of several events, with live you can only pass an event at a type. And finally, you should also keep in mind that live supports only a subset of all the existing events (take a look at the docs for the complete list).

As you might expect, there’s also a method for cancelling the work performed by live. Canceling live events depends on the invocation of the die method. It works in similar fashion to the unbind method. If you call it without parameters, you’ll cancel all the live events that have been previously setup.

If you pass the name of the event, then all live events of that type will be cancelled. You can also pass a function reference as a second parameter. In that case, you’ll end up cancelling only that handler. It’s important to keep in mind that the die method will only affect handlers that have been previously setup through the live method (ie, all handlers previously setup with the bind method will still keep firing in the future).

by luisabreu | 1 comment(s)
Filed under:
JQuery: triggering events
Wed, Jul 29 2009 21:42

[I’ve updated the text for JQuery 1.3]

In the previous post we’ve seen that JQuery introduces a couple of methods which reduce the code you need to write to handle events. At the time, we’ve seen that calling those methods without parameters would result in invoking the handlers associated with that event. Now, as you’re probably wondering, there’s also a general way of achieving that which will even let you do the same for the events that don’t have a  specific shortcut method: I’m talking about the trigger method.

Take a look at the following code:

$("#bt").click(function() { alert("hi2"); });
$("#cancel").click(function() { $("#bt").trigger("click"); });

As you can see, we’re using an anonymous function to handle the #bt’s click event. Now take a look at the anonymous method that handles the click event for the #cancel button…in that case, we’re getting a reference to a JQuery object that wraps the #bt button and we’re “triggering” the click event. Notice that we’re not really generating the event (keep this in mind when we talk about event propagation in future posts)…to be honest, we’ll only be executing all the functions that handle the event.

Notice that from v1.3 onwards, you’ll get bubbling when you call the trigger method.

I guess that you can see this as way to stop introducing global named functions because you could always add named functions and call them directly instead of using JQuery’s trigger method. I guess that it’s all for today! Keep tuned for more on JQuery.

by luisabreu | 3 comment(s)
Filed under:
JQuery: shortcuts for the most used events
Wed, Jul 29 2009 13:56

This is another quick post on events. In the previous posts, we’ve met the bind and unbind method which is used for subscribing and unsubscribing HTML element’s events. So, if you’re interested in subscribing one of the most common events, then you’ll be pleased to know that JQuery introduces several “shortcut” methods. The interesting thing about these methods is that they work in “two modes”: when you pass a function, you’re effectively setting up an event handler; on the other hand, when you call the function without the parameter, you end up executing the previous handlers that have been hooked up.

Here’s a small snippet that shows how to handle the click event:

$("#bt").click(function() { alert("hi"); });
$("#bt").click();

As I’ve said, the first line sets up an event handler. In fact, it produces exactly the same result as the bind method (but with less key presses:)). Whenever someone clicks over the #bt element, the anonymous method we’ve passed to the click method will be fired.

The second line ends up executing all the methods that have been set up as an event handler. Notice that there’s no unclick method so if you need to cancel an existing subscription, you’ll still need to use the unbind method. And that’s all for today. Keep tuned for more on JQuery.

by luisabreu | 4 comment(s)
Filed under:
Book review: The Nomadic Developer
Tue, Jul 28 2009 10:46

This was one of the books I’ve read while I was on vacations. It’s really an interesting book which gives you several valuable advices that you should follow if you intend to work as a consultant. It starts by giving you several clues on how to identify the firms you’re interviewing for so that you don’t end up working in a bad place. To help you know the company you’re interviewing for, there’s a chapter with a list of questions that you should ask. These questions cover different areas and should give you a really good idea about the way that company works.

After that it goes into explaining how consulting firms work so that you can have a good understanding of why things happen the way they do. As I said, there’s lots of advices on what you should and shouldn’t do to thrive as a consultant.

If you know me, you know that I’m not a consultant (at least, not yet! I guess I need to try it in the future to see how I get along :)). However, I did find lots of value in the recommendations that the author has made along the book: I’d say that most of it (if not all) does apply to your work as an employee too (especially the advice on what you should and shouldn’t do at work). Final score: 8/10.

by luisabreu | with no comments
Filed under:
Resharper 4.5.1 is out
Mon, Jul 27 2009 0:33

You can get it from here. I’m still waiting for the version that will work with VS 2010 though…

by luisabreu | 1 comment(s)
Filed under:
NHibernate LINQ is out!
Sun, Jul 26 2009 14:22

Ayende has all the details here.

by luisabreu | with no comments
Filed under: ,
JQuery: one-shot event handlers
Sun, Jul 26 2009 14:17

In the previous posts, we’ve started looking at how you can use JQuery to simplify event handling. As we’ve seen, we can use the bind method to hook up a method as an event handler. When we’re no longer interested in receiving more notifications, we can always call the unbind method to “unsubscribe” ~from that event.

There are several times where we’re only interested in handling the event for the first time.  We already know how to do that (by using unbind through the function that is called when the event is raised), but JQuery simplifies things a bit by introducing  the one method. Here’s how you’d hookup a method for a one time event handling:

$("#bt").one("click", function() {alert("hi"); })
      .bind("click", function() { alert("hi2"); });

Internally, JQuery hooks up everything and then removes the binding so that future events won’t result in having the method executed again. Running the previous snippet produces the same result as the one we saw in the previous post. If you look at the docs, you’ll notice that the behavior is really similar to the one we’ve seen for bind. And that’s all for today. There’s still more to come on JQuery. Stay tuned!

by luisabreu | with no comments
Filed under:
JQuery: unbinding with anonymous functions
Sun, Jul 26 2009 10:53

In the last post of the JQuery  series, we’ve seen how to “cancel” the subscription of an event fired by an HTML DOM node. At the time, I said that when you want to cancel a specific handler, you needed to create a function and pass a reference to it when you can the unbind method. I even said that you needed to create a named function and that you couldn’t use anonymous functions.

After publishing the post, I started thinking about that and then I remembered about the arguments.callee property. If you’re not familiar with it, then don’t worry because it’s really simple. From within a function, you can access the arguments object. This object works like an array that allows the argument values passed to the function to be retrieved by position instead of by name. Besides letting you access the passed in parameters, it also exposes two interesting properties: callee and caller. callee returns a reference to the current function object that is being executed. On the other hand, caller returns a reference to the arguments object of the calling function.

The callee property is what we’re interested in. Take a look at the following snippet:

$("#bt").bind("click", function() {
                      var fn = arguments.callee;
                      alert("hi"); 
                      $("#bt").unbind("click", fn); })
      .bind("click", function() { alert("hi2"); });

If you run the previous snippet (assuming you’ve got, for instance, a button #bt), they you’ll see that the hi alert will only be show once. That happens because the anonymous function which shows that message is simply a one time event handler (more about this in future posts). As you can see, we start by getting a reference to the function through the arguments.callee property. After getting that reference, we only need to pass it to the unbind method in order to cancel the current event binding. Notice that since we’re passing a reference to the function, we’re not cancelling any other events.

And that’s all for now. Keep tuned for more on JQuery.

by luisabreu | 1 comment(s)
Filed under:
Pico do Arieiro to Pico Ruivo and back
Sat, Jul 25 2009 22:22

I’ve just returned from a Pico do Arieiro to Pico Ruivo and back walk. It’s really a demanding walk (just check the 3D plot), but it’s also very beautiful and I do recommend it for those that are visiting Madeira (if you’re interested in knowing more about this walk, take a look here). I guess this explains why there won’t be any technical posts today, right? btw, here the link for the facebook album. Now, I guess  I need my bed :)

by luisabreu | with no comments
Filed under:
JQuery: more on events
Fri, Jul 24 2009 21:45

In the previous post, we’ve met the bind method and saw how it can be used to simplify the code needed for event hookup. One of the questions you’ve might ask is how do you “unsubscribe” from a specific event. And yes, JQuery does introduce a method for doing that: it’s called…unbind. What a big surprise, right?

You’ve got several options here. If you call this method and pass no argument, then you’ll be removing all existing event hookups from the wrapped set. Take a look at the following code:

$("#bt").bind("click mouseover", "howdy", function(evt) { 
alert(evt.data);
$(
this).unbind();});

This is a really interesting example…As you can see, we’re passing the same anonymous function and we’re hooking it up for the click and mouseover events. In the body of that function we’re calling the unbind method over a new JQuery object which wraps the “current” node responsible for the event. Since we’re not passing any parameters, all previous event hookups will be eliminated. In practice, this means that we’ll only see the alert once because we’re removing all event handlers from within the method that handles those events.

There’s also the option of passing an event name. For instance, say that we' replace the previous unbind call with the following method invocation:

$(this).unbind("mouseover");

With this call, you’ll just be removing the mouseover hookups: whenever you click over the button you’ll still get the alert.

There’s still one more option here: you can remove a single function from the list associated with an event. In order to do that, you can’t use anonymous functions though. Here’s a quick example that shows how this feature works:

<input type="button" value="wrap items" id="bt" />
<input type="button" value="cancel bind" id="cancel" />
<script type="text/javascript">
  function sayHiOnce() {
    alert("Hi once!");
  }
  $(function() {
    $("#bt").bind("click", sayHiOnce);
    $("#cancel").bind("click", function() { 
$(
"#bt").unbind("click", sayHiOnce);
}); }); </
script>

As you can see, you do have some granularity for unbinding events. There’s still one more interesting option, but I’ll leave it for a future post. Keep tuned for more on JQuery.

by luisabreu | 9 comment(s)
Filed under:
JQuery: getting started with events
Fri, Jul 24 2009 16:26

Now that we’ve covered several methods for interacting with the wrapped set, it’s time to keep going and we’ll start looking at how JQuery simplifies event handling. As we’ll see, JQuery introduces several methods which reduce and simplify the code we need to write for handing events across different browsers. Most of the time, you’ll end up using the bind method for hooking up an event.

Take a look at the following code:

<input type="button" value="wrap items" id="bt" />
<script type="text/javascript">
  $(function() {
    $("#bt").bind("click", function(evt) { alert("someone clicked on #bt"); });
  }  );
</script>

Many of you might asking something like “Hum, what about the click method?”. It’s a fair question…The truth is that internally the click method relies on the bind method for hooking up the event with a function. Typically, you’ll use the bind method in a similar fashion to the one you’ve seen in the previous snippet: you start by getting a JQuery object and then you call the bind method passing the event you’re interested in and a function that will be called. For a complete list of events, consult the documentation on JQuery’s site.

Notice that there’s also a variation of the previous form:

$("#bt").bind("click", "howdy", function(evt) { alert(evt.data); });

In the previous snippet, we’re passing some custom data that can be recovered from within the anonymous function that was hooked up with the click event. Notice how we can recovered the passed object (which, in the previous example was a simple string) by accessing the data property of the evt object that is passed to that anonymous function.

Ok, but what is that evt parameter I’ve used in the previous examples? Glad you ask…it’s a JQuery Event object which contains info related with the current event! If you’re doing web development for some time, then this is the event object standard browsers pass to the functions that handle events; on the other hand, if you’re thinking IE, then this is the IE event object which you get when you access the global window.event property.

Before passing the object to the method, JQuery makes sure that several properties are safe to be used in a platform independent manner. For instance, if you’re handling a keyup or keydown event, then you can get he code of the pressed key by accessing the keyCode field of the JQuery’s Event object instance. Take a look at the docs for a complete description of the JQuery Event object.

Another interesting feature of the bind method is that you can hook up several methods for a specific event. Here’s how you’d do that:

$("#bt").bind("click", "howdy", function(evt) { alert(evt.data); })
       .bind("click", function(evt) { alert("howdy 2"); });

As you can see, to achieve that goal you only need to call bind multiple times over the wrapped set. Btw, you can also hook up several events with a single function by writing a simple JQuery code line:

$("#bt").bind("click mouseover", "howdy", function(evt) { alert(evt.data); });

The previous snippet ends up calling the anonymous function when you pass the mouse over the #bt element or when you click on it. This is really great, isn’t it? There’s still a lot more to say about JQuery and events, but we’ll leave that for future posts. Keep tuned!

by luisabreu | 2 comment(s)
Filed under:
Let’s do it
Fri, Jul 24 2009 14:47

I guess that if Estonians can do it, so can we!

Update: Alberto has given me the link for the Portuguese movement page.

by luisabreu | with no comments
Filed under:
JQuery – interacting with the wrapped set – part IX
Wed, Jul 22 2009 11:03

Even though we’ve looked at several interesting JQuery methods for interacting with the DOM, we’re still missing some interesting methods which we’ll try to cover in this post. We’ll start by looking at the wrap methods. These methods allow us to wrap one or more elements with other element(s). For instance, take a look at the following HTML snippet:

<span>hi</span>
<span>hi</span>
<span>hi</span>
<input type="button" value="wrap items" />

Lets assume that we want to wrap all span elements with divs. Here’s how we can do that with a simple line of JQuery code:

$("span").wrap("<div>");

Instead of passing a string, we can also pass a reference to an existing HTML element. For instance, we can create a new element on the fly and pass it to the method, as you can see in the next snippet:

$("span").wrap(document.createElement("div"));

If you apply a style to the divs, then you’ll see that the previous example will wrap each span in a div. There might be some cases where you’re interested in wrapping all elements inside a single element. In those cases, you should use the wrapAll method:

$("span").wrapAll(document.createElement("div"));

The final result is that all span elements will end up being wrapped in a single div. btw, the wrap method implementation relies in wrapAll for producing the correct result. There’s also a variation of this method which relies on wrapping the contents of the wrapped set elements. The wrapInner method is what you want if you need to do that:

$("span").wrapInner("<i></i>");

The previous snippet wraps the contents of the span elements in a i element.

Replacing elements with others is also a common operation. And that’s why JQuery offers you two methods for doing that: you’ve got the replaceWith and a replaceAll methods. The replaceWith method expects a string or a reference to an HTML element and ends up replacing the elements of the wrapped set with the new content. Here’s an example based on the previous snippet:

$("span").replaceWith("<div>replaced span</span>");

The previous snippet is probably useless…In that kind of scenario, you’d probably want to replace the span with a div but you’d probably like to keep the original span’s content. That can also be easily achieved with JQuery with code similar to this:

$("span").each(function(pos) {
       $(this).replaceWith("<div>" + $(this).text() + "</div>");
     })

This couldn’t be easy, right? The replaceAll method expects a selector and replaces all matched elements with the JQuery’s wrapped set element. For instance, the next snippet replaces all span elements with input elements (notice that in this case, the “order of replacement” is inverted):

$("input").replaceAll("span");

I’d say that this post wouldn’t be completed without mentioning the clone method. You’ll use this method for cloning an existing wrapped set. Take a look at the following snippet:

$("span").clone().each(function(pos) {
                          $(this).text($(this).text() + " cloned");
                        }).insertAfter("input");

The previous snippet clones all span elements, changes each of its text and then inserts them after the only input element we’ve got in our page. There’s also an “overload” of this method which receives a boolean: passing true means that the event handlers of the original elements will also be cloned. And that’s it for today. Keep tuned for more on JQuery.

by luisabreu | with no comments
Filed under:
JQuery: interacting with the wrapped set – part VIII
Mon, Jul 20 2009 13:06

In the previous post, we’ve met several basic operations that affect the DOM of the current page. However, there will be times when we’re interested in getting the contents of one or more elements. When that happens, we’re probably interested in getting the text or in getting the inner HTML of those items. JQuery helps in these cases too by introducing two methods: text and html.

The html method can be used for getting the inner HTML of a DOM element. For instance, the following snippet will show you the inner HTML of the first div of the wrapped set:

$("div").html()

Setting the inner HTML is as easy as passing a string to the html method. As you might expect, doing this affects all the items of the wrapped set:

$("div").html("<p>hi</p>")
The previous snippet replaces the content of all the div elements of the current page.

The text method is similar, but concentrates on getting the text from within the element. Notice that, unlike the html method, using this method returns the text of all elements maintained on the wrapped set. take a look at the following snippet:

$("div").text()

The previous expression concatenates all text nodes placed inside of all of the divs of the current page. For instance, if you had the following HTML:

<div id="body" style="border: solid 1px red">
    <p>Today is a beautiful day for more JQuery learning.</p>
    <p>I'd say that it's also a good day to hit the beach.</p>
</div>
<div id="b" class="main secondary">something</div>
then the previous snippet would return something like “Today is a beautiful day for more JQuery learning. I'd say that it's also a good day to hit the beach. something.”.

Setting the text through the text method means that you’ll end up replacing the inner HTML of the items of the wrapped set with the text you’re passing.  And that’s it for this post. Keep tuned for more on JQuery.

by luisabreu | 1 comment(s)
Filed under:
JQuery: interacting with the wrapped set – part VII
Mon, Jul 20 2009 12:52

Now that we now how to create new HTML elements, it’s time to go on and see how we can interact with the page’s DOM. We’ll start with something basic: adding new elements to an existing element. Suppose we’ve got the following HTML:

<div id="body">
    <p>Today is a beautiful day for more JQuery learning.</p>
    <p>I'd say that it's also a good day to hit the beach.</p>
</div>

And now, let’s also assume that we want to add another paragraph to our top DIV element with the text hello. Here’s one way to do it with JQuery:

$("div").append("<p>Hello</p>");

The append method adds the “inferred” reference to the children collection of each element of the wrapped set. In the previous example, we’re passing a string with an HTML snippet. We could also pass a JQuery object. Consider the next snippet:

$("div").append($("<p>Hello</p>"));

It produces exactly the same result as the first example we saw: it creates a new paragraph, wraps it in a JQuery object and adds it to each of the wrapped set elements’ children collection. Notice that in the previous examples append really means “adding” something to the children collection of an existing HTML element (or elements). If the JQuery object we’ve passed wrapped elements that belong to the current page’s DOM, then the results would be different: we’d be moving instead of copying. Look at the following snippet:

$("div").append($("select"));

In this case, we’d be moving all the select elements of the current page from their predefined position and we’d be copying them into all the divs that exist in the page. This is a good way of moving elements from one container to another. There’s still one more way to use the append method: you can pass it a reference to a DOM node. Here’s an example that shows how to copy the 1st select into all div elements:

var firstSelect = $("select")[0];
$("div").append(firstSelect);
We start by getting a reference to the first select of the page and then we add copies of it into all the existing divs.

Instead of appending to the children collection of all the elements in the wrapped set, we can also do the opposite, ie, append all the elements of the current wrapped set to another element(s). To do that, we need to use the appendTo method. Here’s an example:

$("select").appendTo("div:first");

The previous example moves all selects into the first div of the page. append and appendTo aren’t the only available methods for changing the current DOM. For instance, if you need to add the items at the beginning of the children collection, then you should use the prepend or prependTo methods (they’re similar to the append and appendTo methods). here’s how you can move the existing select items to the beginning of the first div’s children collection:

$("div:first").prepend($("select") );

There will also be times when you need to add one or more elements before an existing item (and not in that item’s children collection). That kind of operation is supported by the before, insertBefore, after and insertAfter methods. These methods work  in a similar fashion to the append and appendTo methods (in the sense that they “invert” the arguments"). For instance, both these instructions move the selects of the current page and positions them before the first div:

$("div:first").before($("select") );
$("select").insertBefore($("div:first") );

The after and insertAfter methods are similar, but end up putting the items after  (instead of before!) the indicated target. Adding/moving elements of the DOM is a necessary and recurrent operation. Removing is also something which we need to do often. That’s why JQuery offers a remove method. Calling remove over a JQuery object ends up removing all the elements of the wrapped set from their current position in the DOM. Notice that these “removed” elements are still wrapped on the JQuery objecty that is returned from the method. This means that you can use chaining to perform other interesting operations on that set of elements (for instance, you can remove several items from one place and put then on another).

Notice that you can also “clean” the children nodes of all the elements of the wrapped set by using the empty method. For instance, let’s assume that we want to clear the contents of the first div. here’s how you’d do that:

$("div:first").empty();
And that’s all for this post. There’s still a couple of interesting DOM operations we’ll be covering in the next posts. Stay tuned for more on JQuery.
by luisabreu | 3 comment(s)
Filed under:
JQuery: creating new HTML snippets
Sun, Jul 19 2009 22:19

Even though I’ve said that you could use the jQuery method for creating new HTML elements from strings, we still haven’t really seen how to achieve that. And that’s what we’ll do in this post. As you’ll  see, it’s really easy! We just need to pass the HTML snippet we’re interested in creating to the jQuery method. For instance, the next snippet creates a new div element with the text hello (since I’m lazy, I’ll just end up using the :

var html = $("<div>Hello</div>");

If we didn’t had any content for our div, we could even get away with less code:

var html = $("<div>");

In both cases, we’d end up with a new JQuery object which wraps the new HTML element. Unfortunately, you cannot create new script elements with this approach! (for those scenarios, you can use one of the patterns mentioned here).

As you’ve probably guessed, the power of creating new elements in this way is that you get a JQuery object and then you can use chaining for performing several actions. One of those actions is adding elements to the page’s DOM. And that’s what we’ll do in the next post. Keep tuned for more on JQuery!

by luisabreu | 1 comment(s)
Filed under:
JQuery: interacting with the wrapped set- part VI
Sun, Jul 19 2009 22:01

Today we’re going to concentrate on styles. JQuery offers us several methods that help when we need to style our elements. Lets start with the css method. This method can be used to get or set a specific style. In fact, it’s really similar to the attr method we’ve met in the previous post. Lets assume that we want to change the color of the text of  all div elements. Here’s how I’d do it with JQuery:

$("div").css("color", "red");

Notice that setting a CSS property means that all the elements on the wrapped set will have that property set. Again, if you want, you can also pass a function which will be called  for each of the wrapped elements. And, of course, inside the function  this points to the current element. It’s so similar that I won’t be putting any code for it here. And yes, there’s also the possibility of  setting multiple CSS property and values through an anonymous object. Again, this works in exactly the same way as the attr method and that’s why we won’t repeat ourselves here.

If you want to get a value of a CSS property, then you should only pass the name of the property. As you might expect by now, doing this means that you’ll get that value for the first element on the wrapped set.

JQuery has also a nice set of helper methods for those simple cases which, in plain truth, aren’t really that simple. For instance, getting the width and height of an element is something that seems simple, right? How do you do that? I mean, how would you get the width and height of an element if you didn’t had JQuery? Unfortunately, using the style.width won’t do it because it will only when you’ve previously set it up…

Fortunately, JQuery’s width and height methods solve all those problems for you and return a number  with the correct values for those properties. You can also pass a number to these methods.  As you might expect, this means that you’re changing the width or height of each element of the wrapped set.

If you’re into CSS and styles, then I’d say that you’ll probably end up using CSS classes lots of times. JQuery has some methods which help you get info about and interact with CSS classes that have been applied to DOM nodes. You can see if a CSS class has been applied to one of the wrapped element by using the has method. Here’s a quick example:

$("div").hasClass("red")

Setting the current CSS class can be done through the addClass. Calling this method results in adding the specified class name to all the elements of the wrapped set. Here’s an example:

$("div").addClass("red");

There are many people that don’t get this method until they understand that you may apply several classes to an HTML node (not sure why, but many expect a way to apply a single class to an HTML element and I guess that’s why they search for a setClass method when they start using JQuery). For instance, the following HTML is perfectly valid:

<div id="b" class="main secondary">something</div>

The final result is that the styles defined by both classes are merged and applied to the DIV element. Calling the addClass will simply add one more class to the list of CSS classes that have been applied to that element. Removing CSS classes is also possible: just call the removeClass method. The next snippet shows how to remove the main class from the previous DIV element:

$("#b").removeClass("main");

Notice that removing a class name means getting the value of the class attribute and parsing it. Not sure on what you think, but I do enjoy this  cool JQuery feature. Btw, and since we’re talking about cool stuff, I’d like to point out that JQuery also has another useful method: toggleClass. This method ends up adding the passed class name to the list of class names applied to the element if that name isn’t on the list or it will simply remove it from the class’ list if it’s already there. I guess that’s why they called the method toggle :)

And that’s it. I believe this should be enough for your JQuery’s CSS interactions. Keep tuned for more on JQuery.

by luisabreu | 1 comment(s)
Filed under:
PontoNETPT is up and running again
Sun, Jul 19 2009 12:56

When I started blogging and discussing technical stuff, I started writing in Portuguese on the PontoNETPT community. After several years, things started to slow down and I ended up writing only in English. Well, I’m really glad to say that PontoNETPT has been reborn from the ashes! It’s using CS for the blogs and it’s looking a lot better than it used to. I guess that congrats are in order for the guys that have lost several hours configuring the new site!

Since I want to keep writing in English and since writing in English is now permitted, I’ll be cross-posting from this blog to my PT blog. If you can read Portuguese, then why not subscribe its RSS now? And if you want to write for PontoNETPT, then just create a new account on the site and you should be ready to go. If anything goes wrong, you can always leave a message in the forums and someone will help you with that.

by luisabreu | 1 comment(s)
Filed under:
More Posts Next page »