What is wrong?


#1

var $target = $('ol li:last-child');

$(document).ready(function() {

$target.fadeOut('fast');

});

what is wrong ?


#2

Have you considered that what takes place inside the ready handler happens at a different time than what is outside of it?

There is no disputing that $target exists inside the handler function. It is global (in the OP) after all. One problem that arises is that the variable most likely references an empty collection, meaning, nothing.

The purpose of the ready event listener is to defer JavaScript execution until the DOM elements are in place. Then the script has something to work with and the collection is not empty. We have to wait until the HTML finishes loading before we run script on it.

In other words...

move this line inside the ready handler.


#3

Yeh i did that and finished that step. But i even tried it with setting the id's and classes but failed and was it the same reason ?


#4

Without actually seeing what you did, any answer would be speculation. What is evident here is that you need to be aware of the timing of load events and when it is safe to run a certain portion of script.

We can run some script before the HTML (body) of the page loads. This might involve setting of global variables and other environment parameters. Once the page is loaded these will come into play, and having them in place ahead of time is a sure guarantee they are there once needed.

Script runs immediately upon loading, unless deferred. We all know that script at the end of the BODY element is naturally deferred since it loads last, after all the HTML. But as preferable as this is, it still goes against the grain of keeping behaviour separated from structure. What is a script element doing in the body element? It belongs with the meta data in the HEAD, and explictit deferral is the solution that allows this.


#5

I was facing same issue but now step finished Thanks for better answer, But I am not clear why var is not working outside?


#6

Because it is in a part of the namespace with no deferral so runs immediately, before any of the HTML has loaded. Hence, no LI's are present onto which a binding may be registered. Be sure to declare the variable inside the ready() handler.