jQuery function that modifies a DIV

Posted on


How can I shorten and optimize this code which displays then hides a DIV?

setTimeout(function () {

function callback() {
  setTimeout(function() {
    $( '.updateNotification' ).fadeOut();
  }, 10000 );

My first thought was to combine the functions. However, I would like them to remain separate because at a later date I will additionally incorporate a button which will trigger callback() in addition to the timer.


I’m not sure how you would shorten this code. However I think that callback is a terrible name for a function that fades a CSS class. Remember that a function signature should represent what a function does and with that said I would rename it to something like fadeUpdateNotification().

And in the fashion of fading you could replace .show() with .fadeIn() to have the div fade in and out – I dunno how your styling/website looks like but that might look nice…

There’s not much here to optimize mostly because there’s very little here. A few things you could do:

Store your selection to a variable outside both functions (bad idea if you may have multiple notificationDivs).

var notificationDiv = $( '.updateNotification' )

You could save 1 character by adding the callback to the show animation (not really an improvement):


I’m more confused about why you’re doing the setTimeouts the way you are. Why do you need a 2 second delay to show the div? Also if you plan to call callback later, I think it’d confuse most people if the div takes 10 seconds to start to disappear.

Here’s a fiddle I used while tinkering.

if you want to combine them you can just do it like this



or to keep the callback function something like this

var notifications= $('.updateNotification'); //store the selection like Daniel Cook said
setTimeout(function () {
    //if you use the no-arguments form of .show()
    //you can just add display:block on the class .heightener

function callback() {
    notifications.delay(10000).fadeOut();//if you only want to fadeOut you can use delay


Leave a Reply

Your email address will not be published. Required fields are marked *