3

I've got a hopefully simple problem. I've got a function that I give a user message, it displays the message in a predefined div. However, if another message comes along too quickly it changes the message, but then fades out and back in again.

This is where I am right now;-

function readUserMessage(message) {

    if($('#userMessage').is(':visible')) {
        $('#userMessage').fadeOut(200).html("<span style=\"\">" + message + "</span>").fadeIn(300).delay(3000).fadeOut(300);
    } else {
         $('#userMessage').html("<span style=\"\">" + message + "</span>").fadeIn(300).delay(3000).fadeOut(300);
    }

}

Any help really appreciated.

waxical
  • 3,826
  • 8
  • 45
  • 69
  • Btw. I highly suggest checking different kind of template engines for generating html in the JS code. I have been using Mustache https://github.com/janl/mustache.js – Tx3 Feb 14 '12 at 10:15

4 Answers4

1

.html() is not automatically added to jQuerys fx queue so it won't "wait" until your animation stuff has finished. You can workaround that by manually adding a queue entry, like

$('#userMessage').fadeOut(200).queue(function(next) {
     $(this).html("<span style=\"\">" + message + "</span>");
     next();
}).fadeIn(300).delay(3000).fadeOut(300);

Reference: .queue()

jAndy
  • 231,737
  • 57
  • 305
  • 359
1

You can try this. fadeOut has a callback function, which gets called once fadeout is over. You can use this.

function readUserMessage(message) {
    if ($('#userMessage').is(':visible')) {
      $('#userMessage').fadeOut(200, function() {
        $(this).html("<span style=\"\">" + message + "</span>")
               .fadeIn(300).delay(3000).fadeOut(300);
      });
    } else {
       $('#userMessage').html("<span style=\"\">" + message + "</span>")
               .fadeIn(300).delay(3000).fadeOut(300);
    }
}

You can check the demo @ jsFiddle.net : http://jsfiddle.net/KZYbs/

Amar Palsapure
  • 9,590
  • 1
  • 27
  • 46
0

For such a problem, theoretically the best solution is to use a queue.

Basically, in you scenario, any times you read a user message, you perform an action. If you want to manage those actions, you can put them in a queue and then manage them.

The code jAndy posted is very interesting, and if you want to learn more on queues, they are excellently explained here on stackoverflow and here on jquery site .

Spending some time on this subject can be very helpful, as queues can come useful in a plethora of situations.

Community
  • 1
  • 1
Daniele B
  • 3,117
  • 2
  • 23
  • 46
0

You can force the queue to be finished before calling an other effect (fade, slide, etc) with the stop function.

Cyril N.
  • 38,875
  • 36
  • 142
  • 243