Facebook has this nice little chat box that doesn’t take up much space, and people can instantly interact with their friends, it is a cool feature to have in any website. Let’s get inspired and create an similar shoutbox which will look similar to Facebook chat box.
Here’s the CSS, I’ve tried to make it look close as possible to Facebook chat box. Should work in Chrome, Firefox and ie8+. Let me know if it requires some tweaking in other browsers.
Have a look at Shout box markup, you can see username and message fields, also the div with “message_box” class attribute, where user messages are loaded from the database.
Using setInterval(), we will refresh chat every 1000 milliseconds, it sends ajax call to shout.php and loads returned data into the element, updating shout-box with any newly added message.
When user writes something and hit enter key, we need to send entered data to shout.php. The keypress() method triggers when a button is pressed down, and (evt.which == 13) condition makes sure key pressed is Enter key, then we can proceed with ajax $.post() method, as shown in example below. You can replace keypress() with .click() method, but you need to add button in your HTML.
Example below slides up or down shout box, when user clicks close or open icon.
Here’s PHP file shout.php, as you can see I have sanitized post variables using PHP filter_var(), and performed some MySQL query. Since I don’t want to grow this database table large, I am keeping only 10 recent rows in the database, everything else will be deleted. It is up to you to decide how many rows you want to keep.
That’s it! I hope this tutorial has helped you understand how shoutbox works and how we can make it look like Facebook chat box. By the way, I do want to see it working live in your website, so if you are using this example, please do share your links here and good luck!