views:

81

answers:

2

I've got this simple function which displays a message to the user. If I add the timeout parameter it will slide back up automatically if not the user has to click it to get rid. But the timeout bit isn't working.

function feedback(text, timeout){
    $('#feedback').text(text).slideDown('fast');

    $('#feedback').click(function(){
        $(this).slideUp();
    });
    if(timeout){
        setTimeout(function(){
            $('#feedback').slideup();
        }, timeout);
    }
}
+3  A: 

The problem is that $('#feedback').slideup(); needs a capital U in there (e.g. .slideUp()). You can also shorten it down a bit overall doing this:

function feedback(text, timeout){
    var fb = $('#feedback').text(text).slideDown('fast');
    if(timeout) fb.delay(timeout).slideUp();

    fb.click(function(){
        $(this).slideUp();
    });
}

This uses the built-in delay() functionality of jQuery to achieve the same effect in a more concise way.

Nick Craver
+1 Did not know about this new `delay()` function
Matt
A: 

Hi,

putting a whole function call inside a set timeout function is not valid. Your setTimeout will never trigger as you might want it to, as setTimeout will only accept a function reference.

setTimeout(function(){
  $('#feedback').slideup();
}, timeout);

Try the following code:

var ref = function() {
  $('#feedback').slideup();
};
setTimeout(ref, timeout);
cduke
This is incorrect as well, passing an entire function is perfectly valid. See for yourself: http://jsfiddle.net/XaEYx/
Nick Craver
Wrong. It is perfectly acceptable to pass an entire function construct as a parameter. It's called a `closure`
Matt