Вопрос

I made a notice system for my dashboard with javascript/jquery however when I insert 3 notices at the same time it will only hide the last inserted notice.

function NewNotice(title, message, bool){
                if(bool){
                    var color = "green";
                    var icon = "checkmark";
                } else {
                    var color = "red";
                    var icon = "cancel-2";
                }
                $('.notices').append('<div class="bg-color-'+ color +'">');
                $n = $('.notices').children().last();
                $n.append('<a href="#" class="close">');
                $n.append('<div class="notice-icon"> <i class="icon-'+ icon +' fg-color-white" style="font-size:32px;"></i> </div>');
                $n.append('<div class="notice-image"> <i class="icon-'+ title +' fg-color-white" style="font-size:48px;"></i> </div>');
                $n.append('<div class="notice-header fg-color-white">'+ title +'</div>');
                $n.append('<div class="notice-text">Message: "'+ message +'" was posted.</div>');

                $n.animate({right:'+=380'}, 500);
                var t = setTimeout(function(){
                   $n.animate({
                       right:'-=380'
                   }, 500, function(){
                       $n.hide();
                   });
                },5000);
            }

I would guess that it will only hide the last because I'm caching the selector but I don't know how to work around this.

Это было полезно?

Решение

The issue is that you're using the $n variable without declaring it the function, so it's getting auto-created at the global scope, which means that in your setTimeout function the $n is referring to the global variable which will be set by the most recent time that NewNotice is run.

To fix it, just add var to when you're creating your variables.

var $n2 = $(this);
var $n = $('.notices').children().last();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top