Nelson Nelson - 2 days ago 4
Javascript Question

Show messages with different color with delay in same div?

I want to modify this code with two buttons, if I click on first button the message should should show in red color and if i click second button it should show green colored message. I want show both in the same div with delay

function showAlertBarMessages(type) {
var msg = msgQueue[0];
if (!$('#msg-sequentially').find(':visible').length) {
var el = $('<div />').html(msg).addClass('msg').appendTo('#msg-sequentially');
el.fadeIn(500).promise().done(function () {
$(this).delay(2000).fadeOut().promise().done(function () {
$(this).remove();
msgQueue.splice(0,1);
if(msgQueue.length) showAlertBarMessages(type);
});
});
}
}


thank you

Answer

Try to check if THIS is what you want

var msgQueue = [];
//var timeout;

function addMessage(color){
		msgQueue.push({message: "Message number " + (i + 1), color: color});
    showAlertBarMessages();
    i++;
}
var i = 0;

function showAlertBarMessages() {
    var msg = msgQueue[0];
    if (!$('#msg-sequentially').find(':visible').length) {
         var el = $('<div />').html(msg.message).addClass('msg ' + msg.color).appendTo('#msg-sequentially');
        el.fadeIn(500).promise().done(function () {
            $(this).delay(2000).fadeOut().promise().done(function () {
                $(this).remove();
                msgQueue.splice(0,1);
                if(msgQueue.length) showAlertBarMessages();
            });
        });
    }
}
.msg {
    display:none;
    padding:20px;
}
.blue{
  background: #00abff;
}
.red{
  background: #F00000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="msg-sequentially"></div>
<button id="add-msg" onclick="addMessage('red')">Add red message</button>
<button id="add-msg" onclick="addMessage('blue')">Add blue message</button>

EDIT: I edited your queue with an object array, containing each message and the relative color

msgQueue.push({message: "Message number " + (i + 1), color: color});
Comments