views:

116

answers:

2

i try to rich flash like effect when changing window location, but there is a small problem, i can't solve.

look at the script please

 $(document).ready(function(){

            $('a.flash').click(function(e) {
                e.preventDefault();
                $('body').fadeOut(1500);
                setTimeout("", 1500);
                window.location=this.href;
            }); 
      });

window.location=this.href must be done after 1500ms, but it doesn't happen. could you explain why? what is strange, when i try to write alert("something"); instead of window.location=this.href, it works fine. Could you explain why?

Thanks

+6  A: 
$(document).ready(function(){

            $('a.flash').click(function(e) {
                var el = this;
                e.preventDefault();
                $('body').fadeOut(1500);
                setTimeout( function() {  location=el.href }, 1500 );
            }); 
      });

You're supposed to provide a callback function as the first param of setTimeout which is invoked after 1500 ms.

meder
+3  A: 

setTimeout is not equivalent to a Thread.sleep(1500); in other languages. setTimeout schedules a piece of code to be run at some point in the future and does not block. Execution immediately passes the setTimeout call and continues on.

The first parameter is either a reference to a function or a string that will be evaluated.

See meder's answer for the appropriate way to use setTimeout, avoiding evaluation using an anonymous function.

Jonathon
quotes=eval=badbad, use lambdas instead
meder
setTimeout("window.location=this.href;", 1500); doesn't work, i tried.but i inderstand the logic, thanks. but why it works fine, when i wrote alert(); ???
Syom
`this` in that context is probably to `window` and not the `a` element. Have you tried my answer?
meder
it works, but doesn't understand this.href! so it was redirected to unknown page.
Syom
Did you change the code to `el.href` as in my example and not `this.href` ? You need to cache the `href` because the context in which you provide to setTimeout becomes window and not `a`.
meder
@meder your script works, thanks much. i thought the comment was written by Jonathon :DDD
Syom
@meder and what about alert???
Syom