Notification popup on click of a button in jQuery?

I’m trying to create a notification popup (similar to YouTube’s when you add a video to your watch-later or something). This is my attempt:


$('body').on("click", "#enableSuspension", function(){
	  $('#notification-box').append('<p>Client suspension enabled.</p>').show().fadeTo(2000, 1, function(){
        $('#notification-box, #notification-box p').hide().fadeTo(1000, 0);


However, it doesn’t function well at all. I want each individual notification to stay visible for 1 second and then fade out. Currently, if you click the button 5 times in 2 seconds, ALL the notifications fade out after only 1 second.

Also, the notifications should actually be removed once they fade out:I tried remove() but then the notification wouldn’t appear the next time the button is clicked.

Can anyone tell me where I’m going wrong in trying to make this function work the way YouTube’s does?

Well, to accomplish your task at the most basic level:

  1. Attach notification
  2. Wait for some time
  3. Remove it

Apparently, you are missing step #2 and #3.
Your code immediately hides the notification as soon as the notification is fully visible.
Your code only hides the element rather than removing it.
Furthermore, your JQuery can be simplified too.

Add this JS code and fiddle it around

const notifier = selector => {
  const $target = $(selector)

  return (msg, ms) => {
    // Error handling omitted
      .then($msg => {
        return $msg
      .then($msg => {
        window.setTimeout(() => {
          $msg.fadeOut(1000, () => $msg.remove())
        }, ms)

const makeNotice = notifier('#notification-box')

$('#enableSuspension').on('click', function() {
  makeNotice('Suspension enabled.', 2000)

(You don’t really have to use Promise, but it makes the code cleaner, and async more predictable)

One caveat here is that adding a new notification triggers re-render. So, consecutive clicks result blinking.
You can work this around by text replacement or having more sophisticated notification system.

1 Like

Thanks a lot for taking your time to answer my question, however I really wanted something a lot more concise… Just a beginner here ^.^ So I have absolutely no idea what was Promise and Then, etc…

In fact, someone wrote an excellent solution here: with just a few lines of code. Thanks Jake :star:

Cool that works well too. I didn’t think of using this.