How to create a Twitter-style alert with jQuery, CSS, and PHP

Reading time: About 2 minutes

If you’re into taking apart code, skip all this and see the end result or download the source!

In this tutorial you will learn how to display an alert to your users with jQuery and CSS similar to the one used by Twitter. The alert drops down from the top of the screen to display what is in a PHP $_SESSION variable.

The Twitter alert I’m referring to is shown in the following video: (don’t mind the music, I just happened to be listening to Seal at the time)

CSS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#alert
{
	overflow: hidden;
	z-index: 999;
	width: 100%;
	text-align: center;
	position: absolute;
	top: 0;
	left: 0;
	background-color: #fff;
	height: 0;
	color: #000;
	font: 20px/40px arial, sans-serif;
	opacity: .9;
}

jQuery

  • Check if<div id="alert">
  • Use setTimeout to collapse the alert after 3 seconds
  • Expand the alert to CSS line-height or 50px if line-height is not set
  • If the user clicks alert before 3 seconds, collapse the alert early
1
2
3
4
5
6
7
8
9
10
11
12
13
14
$(function () {
	var $alert = $('#alert');
	if($alert.length)
	{
		var alerttimer = window.setTimeout(function () {
			$alert.trigger('click');
		}, 3000);
		$alert.animate({height: $alert.css('line-height') || '50px'}, 200)
		.click(function () {
			window.clearTimeout(alerttimer);
			$alert.animate({height: '0'}, 200);
		});
	}
});

Put CSS and jQuery in an HTML page

Some things to note:

  • Line 1: Turn on session with PHP
  • Line 13: There’s our alert CSS
  • Line 30: If $_SESSION['alert'] exists (set in submit.php in step 2)
  • Line 40: Use jQuery hosted by Google
  • Line 42: There’s our alert jQuery
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php session_start(); ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<title>Twitter-like alert message</title>
		<style type="text/css">
		body
		{
			background-color: #ccc;
			color: #000;
			padding: 30px;
		}
		#alert
		{
			overflow: hidden;
			width: 100%;
			text-align: center;
			position: absolute;
			top: 0;
			left: 0;
			background-color: #fff;
			height: 0;
			color: #000;
			font: 20px/40px arial, sans-serif;
			opacity: .9;
		}
		</style>
	</head>
	<body>
		<?php
		if(!empty($_SESSION['display']))
		{
			echo '<div id="alert">' . $_SESSION['display'] . '</div>';
			unset($_SESSION['display']);
		}
		?>
		<form method="post" action="submit.php">
			<label for="message">Message</label> <input type="text" name="message"> <input type="submit" value="Alert me!">
		</form>
		<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
		<script type="text/javascript">
		$(function () {
			var $alert = $('#alert');
			if($alert.length)
			{
				var alerttimer = window.setTimeout(function () {
					$alert.trigger('click');
				}, 3000);
				$alert.animate({height: $alert.css('line-height') || '50px'}, 200)
				.click(function () {
					window.clearTimeout(alerttimer);
					$alert.animate({height: '0'}, 200);
				});
			}
		});
		</script>
	</body>
</html>

Use PHP to add the alert to the $_SESSION

Save this file as submit.php

1
2
3
4
5
6
7
8
9
10
11
12
<?php
session_start();
 
$themessage = get_magic_quotes_gpc() ?
	stripslashes(trim($_POST['message'])) :
	trim($_POST['message']);
 
$_SESSION['display'] = $themessage;
 
header('Location: ' . $_SERVER['HTTP_REFERER']);
exit;
?>

You’re done!

You’ve created a twitter-style alert that uses jQuery to create the rollout style upon page load and displays a PHP $_SESSION variable.

See the end result or download the source

28 comments skip to comment form

  1. Jason said— 2 hours later

    Ok, this is genius. Thanks for such a clear and concise tutorial. I’m thinking of possible uses on my blog right now.

    Also, digging your site. Nice clean navigation and presentation of info.

    #1
  2. Brian Cray said— 3 hours later

    Thanks for the comments on my article and my site Jason! Rock on!

    #2
  3. ulwan said— 7 hours later

    i was wondering.can this be possibly done using a Blogspot platform?

    #3
  4. Barry Roodt said— 11 hours later

    In agreement with Jason; great work Brian, on both the post and the site.

    #4
  5. mightyuhu said— 17 hours later

    nice effect, but i think for usuability reasons it is much better to have something like in the middle of the screen, something like a centered window or so.

    #5
  6. Brian Cray said— 17 hours later

    MIGHTYUHU:
    I think that would be true in some circumstances but centered errors disrupt the user’s cognition by covering important elements that signal to the user what the new page has to offer. The user will recognize the error even at the top of the page because it rolls down—an animation that attracts the users attention while keeping all important elements of the page clear of blockage. What are your thoughts on that?

    #6
  7. Brian Cray said— 17 hours later

    ULWAN:

    I’m sorry, I’m not familiar with the Blogspot platform, but this should work on any PHP-powered platform and potentially any scripting platform given the right code modifications for session handling.

    #7
  8. mightyuhu said— 18 hours later

    BRIAN CRAY: You are right. Havent thought about the covering aspect. But that really depends on the actual message / error.

    #8
  9. James said— 2 days later

    Why does the page reload when I click the button? (that’s not how it works on Twitter)

    #9
  10. Brian Cray said— 2 days later

    James:
    True, it doesn’t use AJAX to prevent page reloading, but I wanted to keep it simple and I wanted to use the $_SESSION so any script could put something in the alert

    #10
  11. Zack Kitzmiller said— 5 days later

    If you are trying to replicate Twitter’s functionality, you’d have to incorporate AJAX, using prototype or jQuery it would have only take another half dozen lines of code.

    No sure why it was ideal to leave it incomplete, even for the sake of ‘simplicity.’

    #11
  12. Sam said— 2 weeks later

    Great article Brian, really nice effect, clear and easy to understand!

    #12
  13. Srinath said— 3 weeks later

    Here is my version which uses only ajax.

    function tester(val)
    {
    document.getElementById(“alert”).innerHTML= val;

    $(function () {
    var $alert = $(‘#alert’);
    if($alert.length)
    {
    var alerttimer = window.setTimeout(function () {
    $alert.trigger(‘click’);
    }, 3000);
    $alert.animate({height: $alert.css(‘line-height’) || ’50px’}, 200)
    .click(function () {
    window.clearTimeout(alerttimer);
    $alert.animate({height: ’0′}, 200);
    });
    }
    });

    }
    –%>

    #13
  14. Brian Cray said— 3 weeks later

    SRINATH:

    Thanks for sharing your script, but it’s not AJAX.

    I think you may be confusing animation with AJAX. AJAX makes a call to a server-side script without refreshing the browser.

    #14
  15. Nick said— 2 months later

    It there any way to do this without the use of jQuery?

    #15
  16. Joe Devon said— 3 months later

    Thanks Brian, it works like a charm!

    #16
  17. margoha said— 4 months later

    Мы подготовили современный журнал про актеров сериала маргоша. Только тут можно бесплатно скачать увлекательный сериал маргоша. Мы предлагаем Вам актуальные новости про маргошу. Здесь лучшие фотографии из сериала маргоша.

    #17
  18. 1 1 said— 5 months later

    видео, качать, скачать, фильмы, отечественные, русские, на русском, зарубежные, оригинальный язык, сериал, мелодрама, драма, боевик, комедия, история, исторический, мюзикл,BDrip, DVDrip, TS, CAMRip, Blue Ray, HDTVrip, HDTV, Игры, эмулятор, RPG, Arcada, PSP, экшен, ролевые, мини игры, приключения, стратегии, квест, Шаблоны фотошоп, photoshop, уроки фотошоп, клипарты, картинки, обои, фон, рамки для фото, wallpapers, программы, антивирус, Nod32, DrWeb, WinRAR, архиваторы, система, CD, DVD, прожиг, Nero, портативные, альбомы, сборники, mp3, скачать, исполнитель, исполнители, металл, хард, попса, поп, жанры музыки, клипы, исполнители, видеоклипы, книги, литература, художественная литература, журналы, газеты, аудиокниги, фотожурналы, вязание и др…

    #18
  19. Andy said— 5 months later

    No. Bad usability, it blocks user interaction on twitter and other app developers might do the same. A better example is Zendesk which centers the message and does a background color yellow fade to white. This does not block user interaction and leaves the message there until the next request.

    #19
  20. Web Design Talk said— 6 months later

    Great article, very useful for admin systems.

    #20
  21. AMereServant said— 7 months later

    Thank you very much for the great info! I think the sample files are by far the most helpful thing someone can add to their tutorial and you did a great job!

    #21
  22. Zane said— 8 months later

    Is there anyway to get this script to display on a page load with a pre-set message. For example a site announcement saying “website undergoing updates” or something?

    Thanks!

    #22
  23. Rob said— 9 months later

    Great article, have been looking for something like this for admin areas to warn users they are in admin mode :) Just personal preference, but I added a simple blink effect too:

    $(‘#alert’).hide().animate({height: ’51px’}, 200).fadeOut().fadeIn();

    #23
  24. Alan Takushi said— 10 months later

    The wheels are spinning on how I can integrate this feature into my projects. Great tutorial Brian. Thanks!

    #24
  25. bharat khiani said— 11 months later

    hi,

    thanks for the plugin…its very easy to integrate in applications and your example serves well.

    Just one problem, when i use IE 6, i do not see anything. infact i see that the script is generating errors. i’m using jquery 1.3.2 fyi. can u please look it up and let me know whats the issue…

    thanks,

    #25
  26. Antonds said— on May 6, 2009 later

    great thanks for this very simple decision :)

    #26
  27. comprare viagra generico said— on May 6, 2009 later

    . aquista viagra generico .

    #27
  28. brian mosby de la torre said— on May 6, 2009 later

    can we freely use your code? under what liense is that code? under cc?

    #28
  29. Respond to this post—

Return to navigation
513