I want to create a notification when an event occurs on my site. The notification will be prepended into an element, and display a notification window. I then want to be able to control this element, in the sense, I want to be able to do more actions with it.
$('#footer_notification').prepend('<li>something happened</li>',
function(){$(this).delay('3000').fadeOut();}
)
i.e. when this event occurs a notification will show as an <li>
element within a <ul>
element. Then 3 seconds later the element will fade out.
My code above doesn't work, as there doesn't seem to be a callback feature for prepending. So how can I take control of this newly prepended element, bear in mind there could be multiple elements added simultaneously?
I guess this might help you:
let $li = $('<li>').text('something happened');
$('#footer_notification').prepend($li);
setTimeout(()=>{
$li.fadeOut();
}, 3000);
Just create the tag element you want to prepend and make a reference to it using a var (i.e. $li), after that, you can do whatever you want with it.
EDIT
Answering your other question, first, fadeOut method DOESN'T remove the item, it just hides it (adds css display prop to none). So, if you want to check for this, you need to get the children of footer_notification and check for elements with display:block, it means it has active notifications, if there's none, it means there's no active notifications, something like:
$(()=>{
let $foo = $('#footer_notification');
let $liNo = $('<li>').text('no notifications');
$foo.append($liNo);
$('#add').on('click',()=>{
$liNo.remove();
let $li = $('<li>').text('something happened');
$foo.prepend($li);
setTimeout(()=>{
$li.fadeOut({
done: ()=>{
if($foo.children().css('display')=='none'){
$foo.append($liNo);
}
}
});
}, 3000);
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="footer_notification">
</ul>
<button id="add" type="button">+ Notification</button>
Note I'm using the done option in fadeOut, this fires the given function after the animation ends, this is where you should put the code you want to execute after a notification hides. Hope I could help