QNimate

  • CoursesVideos
  • WP PremiumPlugins
  • DemosLab
  • BlockClusterBuild Private Blockchains
  • Home
  • QIdea
  • QTrack
Home Home Facebook Style Chat Box Popup using JavaScript and CSS

Facebook Style Chat Box Popup using JavaScript and CSS

facebook-chat-popup

In this article I will show you the logic and code behind facebook chat box popups. Many other websites like freelancer.com are using this kind of similar popups for implementing chat design. Therefore if you are planning to have a chatting functionality in your website then this article provide you the best help for designing it.


CSS Implementation

Screen Shot 2014-09-25 at 12.20.43 pm
We need enough room for chat boxes and sidebar therefore we only display those if viewport width is greater than 540px. Even facebook does the same. Popup boxes and sidebar are fixed to the viewport.

Here is the CSS code:

            @media only screen and (max-width : 540px)
            {
                .chat-sidebar
                {
                    display: none !important;
                }
               
                .chat-popup
                {
                    display: none !important;
                }
            }
           
            body
            {
                background-color: #e9eaed;
            }
           
            .chat-sidebar
            {
                width: 200px;
                position: fixed;
                height: 100%;
                right: 0px;
                top: 0px;
                padding-top: 10px;
                padding-bottom: 10px;
                border: 1px solid rgba(29, 49, 91, .3);
            }
           
            .sidebar-name
            {
                padding-left: 10px;
                padding-right: 10px;
                margin-bottom: 4px;
                font-size: 12px;
            }
           
            .sidebar-name span
            {
                padding-left: 5px;
            }
           
            .sidebar-name a
            {
                display: block;
                height: 100%;
                text-decoration: none;
                color: inherit;
            }
           
            .sidebar-name:hover
            {
                background-color:#e1e2e5;
            }
           
            .sidebar-name img
            {
                width: 32px;
                height: 32px;
                vertical-align:middle;
            }
           
            .popup-box
            {
                display: none;
                position: fixed;
                bottom: 0px;
                right: 220px;
                height: 285px;
                background-color: rgb(237, 239, 244);
                width: 300px;
                border: 1px solid rgba(29, 49, 91, .3);
            }
           
            .popup-box .popup-head
            {
                background-color: #6d84b4;
                padding: 5px;
                color: white;
                font-weight: bold;
                font-size: 14px;
                clear: both;
            }
           
            .popup-box .popup-head .popup-head-left
            {
                float: left;
            }
           
            .popup-box .popup-head .popup-head-right
            {
                float: right;
                opacity: 0.5;
            }
           
            .popup-box .popup-head .popup-head-right a
            {
                text-decoration: none;
                color: inherit;
            }
           
            .popup-box .popup-messages
            {
                height: 100%;
                overflow-y: scroll;
            }

JavaScript Implementation

We do the following using JavaScript

  • Calculate the maximum number of popups can be displayed for the current viewport width.
  • Close popups
  • Newly opened popups overwrite the space given to the older popups.
  • Repositioning popups when viewport is resized.
  • Calculate the width and position of each popup.
  • Displaying popups when a item in sidebar is clicked.

This is the JavaScript code for these functionality.

            //this function can remove a array element.
            Array.remove = function(array, from, to) {
                var rest = array.slice((to || from) + 1 || array.length);
                array.length = from < 0 ? array.length + from : from;
                return array.push.apply(array, rest);
            };
       
            //this variable represents the total number of popups can be displayed according to the viewport width
            var total_popups = 0;
           
            //arrays of popups ids
            var popups = [];
       
            //this is used to close a popup
            function close_popup(id)
            {
                for(var iii = 0; iii < popups.length; iii++)
                {
                    if(id == popups[iii])
                    {
                        Array.remove(popups, iii);
                       
                        document.getElementById(id).style.display = "none";
                       
                        calculate_popups();
                       
                        return;
                    }
                }  
            }
       
            //displays the popups. Displays based on the maximum number of popups that can be displayed on the current viewport width
            function display_popups()
            {
                var right = 220;
               
                var iii = 0;
                for(iii; iii < total_popups; iii++)
                {
                    if(popups[iii] != undefined)
                    {
                        var element = document.getElementById(popups[iii]);
                        element.style.right = right + "px";
                        right = right + 320;
                        element.style.display = "block";
                    }
                }
               
                for(var jjj = iii; jjj < popups.length; jjj++)
                {
                    var element = document.getElementById(popups[jjj]);
                    element.style.display = "none";
                }
            }
           
            //creates markup for a new popup. Adds the id to popups array.
            function register_popup(id, name)
            {
               
                for(var iii = 0; iii < popups.length; iii++)
                {  
                    //already registered. Bring it to front.
                    if(id == popups[iii])
                    {
                        Array.remove(popups, iii);
                   
                        popups.unshift(id);
                       
                        calculate_popups();
                       
                       
                        return;
                    }
                }              
               
                var element = '<div class="popup-box chat-popup" id="'+ id +'">';
                element = element + '<div class="popup-head">';
                element = element + '<div class="popup-head-left">'+ name +'</div>';
                element = element + '<div class="popup-head-right"><a href="javascript:close_popup(\''+ id +'\');">&#10005;</a></div>';
                element = element + '<div style="clear: both"></div></div><div class="popup-messages"></div></div>';
               
                document.getElementsByTagName("body")[0].innerHTML = document.getElementsByTagName("body")[0].innerHTML + element; 
       
                popups.unshift(id);
                       
                calculate_popups();
               
            }
           
            //calculate the total number of popups suitable and then populate the toatal_popups variable.
            function calculate_popups()
            {
                var width = window.innerWidth;
                if(width < 540)
                {
                    total_popups = 0;
                }
                else
                {
                    width = width - 200;
                    //320 is width of a single popup box
                    total_popups = parseInt(width/320);
                }
               
                display_popups();
               
            }
           
            //recalculate when window is loaded and also when window is resized.
            window.addEventListener("resize", calculate_popups);
            window.addEventListener("load", calculate_popups);

Live Demo and Complete code

Here is the complete code of the example:

View Demo

<!doctype html>
<html>
    <head>
        <title>Facebook Style Popup Design</title>
        <style>
            @media only screen and (max-width : 540px)
            {
                .chat-sidebar
                {
                    display: none !important;
                }
               
                .chat-popup
                {
                    display: none !important;
                }
            }
           
            body
            {
                background-color: #e9eaed;
            }
           
            .chat-sidebar
            {
                width: 200px;
                position: fixed;
                height: 100%;
                right: 0px;
                top: 0px;
                padding-top: 10px;
                padding-bottom: 10px;
                border: 1px solid rgba(29, 49, 91, .3);
            }
           
            .sidebar-name
            {
                padding-left: 10px;
                padding-right: 10px;
                margin-bottom: 4px;
                font-size: 12px;
            }
           
            .sidebar-name span
            {
                padding-left: 5px;
            }
           
            .sidebar-name a
            {
                display: block;
                height: 100%;
                text-decoration: none;
                color: inherit;
            }
           
            .sidebar-name:hover
            {
                background-color:#e1e2e5;
            }
           
            .sidebar-name img
            {
                width: 32px;
                height: 32px;
                vertical-align:middle;
            }
           
            .popup-box
            {
                display: none;
                position: fixed;
                bottom: 0px;
                right: 220px;
                height: 285px;
                background-color: rgb(237, 239, 244);
                width: 300px;
                border: 1px solid rgba(29, 49, 91, .3);
            }
           
            .popup-box .popup-head
            {
                background-color: #6d84b4;
                padding: 5px;
                color: white;
                font-weight: bold;
                font-size: 14px;
                clear: both;
            }
           
            .popup-box .popup-head .popup-head-left
            {
                float: left;
            }
           
            .popup-box .popup-head .popup-head-right
            {
                float: right;
                opacity: 0.5;
            }
           
            .popup-box .popup-head .popup-head-right a
            {
                text-decoration: none;
                color: inherit;
            }
           
            .popup-box .popup-messages
            {
                height: 100%;
                overflow-y: scroll;
            }
           


        </style>
       
        <script>
            //this function can remove a array element.
            Array.remove = function(array, from, to) {
                var rest = array.slice((to || from) + 1 || array.length);
                array.length = from < 0 ? array.length + from : from;
                return array.push.apply(array, rest);
            };
       
            //this variable represents the total number of popups can be displayed according to the viewport width
            var total_popups = 0;
           
            //arrays of popups ids
            var popups = [];
       
            //this is used to close a popup
            function close_popup(id)
            {
                for(var iii = 0; iii < popups.length; iii++)
                {
                    if(id == popups[iii])
                    {
                        Array.remove(popups, iii);
                       
                        document.getElementById(id).style.display = "none";
                       
                        calculate_popups();
                       
                        return;
                    }
                }  
            }
       
            //displays the popups. Displays based on the maximum number of popups that can be displayed on the current viewport width
            function display_popups()
            {
                var right = 220;
               
                var iii = 0;
                for(iii; iii < total_popups; iii++)
                {
                    if(popups[iii] != undefined)
                    {
                        var element = document.getElementById(popups[iii]);
                        element.style.right = right + "px";
                        right = right + 320;
                        element.style.display = "block";
                    }
                }
               
                for(var jjj = iii; jjj < popups.length; jjj++)
                {
                    var element = document.getElementById(popups[jjj]);
                    element.style.display = "none";
                }
            }
           
            //creates markup for a new popup. Adds the id to popups array.
            function register_popup(id, name)
            {
               
                for(var iii = 0; iii < popups.length; iii++)
                {  
                    //already registered. Bring it to front.
                    if(id == popups[iii])
                    {
                        Array.remove(popups, iii);
                   
                        popups.unshift(id);
                       
                        calculate_popups();
                       
                       
                        return;
                    }
                }              
               
                var element = '<div class="popup-box chat-popup" id="'+ id +'">';
                element = element + '<div class="popup-head">';
                element = element + '<div class="popup-head-left">'+ name +'</div>';
                element = element + '<div class="popup-head-right"><a href="javascript:close_popup(\''+ id +'\');">&#10005;</a></div>';
                element = element + '<div style="clear: both"></div></div><div class="popup-messages"></div></div>';
               
                document.getElementsByTagName("body")[0].innerHTML = document.getElementsByTagName("body")[0].innerHTML + element; 
       
                popups.unshift(id);
                       
                calculate_popups();
               
            }
           
            //calculate the total number of popups suitable and then populate the toatal_popups variable.
            function calculate_popups()
            {
                var width = window.innerWidth;
                if(width < 540)
                {
                    total_popups = 0;
                }
                else
                {
                    width = width - 200;
                    //320 is width of a single popup box
                    total_popups = parseInt(width/320);
                }
               
                display_popups();
               
            }
           
            //recalculate when window is loaded and also when window is resized.
            window.addEventListener("resize", calculate_popups);
            window.addEventListener("load", calculate_popups);
           
        </script>
    </head>
    <body>
        <div class="chat-sidebar">
            <div class="sidebar-name">
                <!-- Pass username and display name to register popup -->
                <a href="javascript:register_popup('narayan-prusty', 'Narayan Prusty');">
                    <img width="30" height="30" src="https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xap1/v/t1.0-1/p50x50/1510656_10203002897620130_521137935_n.jpg?oh=572eaca929315b26c58852d24bb73310&oe=54BEE7DA&__gda__=1418131725_c7fb34dd0f499751e94e77b1dd067f4c" />
                    <span>Narayan Prusty</span>
                </a>
            </div>
            <div class="sidebar-name">
                <a href="javascript:register_popup('qnimate', 'QNimate');">
                    <img width="30" height="30" src="https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xap1/v/t1.0-1/p50x50/1510656_10203002897620130_521137935_n.jpg?oh=572eaca929315b26c58852d24bb73310&oe=54BEE7DA&__gda__=1418131725_c7fb34dd0f499751e94e77b1dd067f4c" />
                    <span>QNimate</span>
                </a>
            </div>
            <div class="sidebar-name">
                <a href="javascript:register_popup('qscutter', 'QScutter');">
                    <img width="30" height="30" src="https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xap1/v/t1.0-1/p50x50/1510656_10203002897620130_521137935_n.jpg?oh=572eaca929315b26c58852d24bb73310&oe=54BEE7DA&__gda__=1418131725_c7fb34dd0f499751e94e77b1dd067f4c" />
                    <span>QScutter</span>
                </a>
            </div>
            <div class="sidebar-name">
                <a href="javascript:register_popup('qidea', 'QIdea');">
                    <img width="30" height="30" src="https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xap1/v/t1.0-1/p50x50/1510656_10203002897620130_521137935_n.jpg?oh=572eaca929315b26c58852d24bb73310&oe=54BEE7DA&__gda__=1418131725_c7fb34dd0f499751e94e77b1dd067f4c" />
                    <span>QIdea</span>
                </a>
            </div>
            <div class="sidebar-name">
                <a href="javascript:register_popup('qazy', 'QAzy');">
                    <img width="30" height="30" src="https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xap1/v/t1.0-1/p50x50/1510656_10203002897620130_521137935_n.jpg?oh=572eaca929315b26c58852d24bb73310&oe=54BEE7DA&__gda__=1418131725_c7fb34dd0f499751e94e77b1dd067f4c" />
                    <span>QAzy</span>
                </a>
            </div>
            <div class="sidebar-name">
                <a href="javascript:register_popup('qblock', 'QBlock');">
                    <img width="30" height="30" src="https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xap1/v/t1.0-1/p50x50/1510656_10203002897620130_521137935_n.jpg?oh=572eaca929315b26c58852d24bb73310&oe=54BEE7DA&__gda__=1418131725_c7fb34dd0f499751e94e77b1dd067f4c" />
                    <span>QBlock</span>
                </a>
            </div>
        </div>
       
    </body>
</html>
Sep 25, 2014Narayan Prusty
Popup Best Time, Placement and OptionsChange Navigation Style On Scroll
Comments: 71
  1. guna
    1 year ago

    hai can you help any one i’m using this code fb chat popup but inthis code there is no text fiels for send ing messages please help me

    ReplyCancel
  2. piyush kamani
    1 year ago

    This is a nice design please try it…..
    link:http://www.nicesnippets.com/snippet/bootstrap-4-chat-box-design-like-facebook

    ReplyCancel
  3. fatima zahra bouj
    2 years ago

    thanks a lot for that demo ^^

    ReplyCancel
  4. James
    2 years ago

    If I copy and paste this complete code in a code snippet on Zoho Sites nothing is shown on the published page.

    ReplyCancel
  5. GYmstore
    2 years ago

    How can i use this code with wordpress

    ReplyCancel
  6. Ikechi Okorie
    2 years ago

    I like this tutorial and i have been able to do everything get it working but unable to make it focus when a chat window is popped up. Please how can I achieve this?

    ReplyCancel
  7. sengly
    2 years ago

    i want to use this script with server side (PHP, ASP.NET…) which one can help me? thanks

    ReplyCancel
  8. seng
    2 years ago

    How to add Textbox and do chatting , can you you help thanks?

    ReplyCancel
  9. siva
    2 years ago

    Sir can u give complete coding messages and comment box

    ReplyCancel
  10. Kusal Videshan
    2 years ago

    hey thx for your code bro its really good…but i have trouble on minimizing the chat list can you send a code for that?

    ReplyCancel
    • Kusal Videshan
      2 years ago

      is there any way i can put a message box on the chat pop ups? so like a way for people to send messages

      ReplyCancel
  11. PollChat
    2 years ago

    Great article. Very helpful for my project.
    Thanks..

    ReplyCancel
  12. marwen ben naya
    2 years ago

    thank you for your wonderful work.
    but plz how can i use this code to show up messages from database , i can’t use javascript variable “id” to get data from database in every popup . if any one know how to do that plz help

    ReplyCancel
  13. Alex
    2 years ago

    Is there a way when i write a message to user 1 for example and when i hit enter if user 1 is online is there a way to popup the chat window to him with my message?

    ReplyCancel
  14. Supriadi
    2 years ago

    Jika anda butuh angka ritual jitu 2D 3D 4D di jamin tembus 100% silakan hub Mbah Joko di no 081290772525 Thankz”room’nya.sobat..

    ReplyCancel
  15. Kyaw
    2 years ago

    very lucky to see it!Thanks!!

    ReplyCancel
  16. smita
    2 years ago

    How to add Textbox and do chatting , can you please send whole code?

    ReplyCancel
  17. Haisam
    3 years ago

    Hi , first of all thank you for your wonderful work.
    I built upon this example to make a full chat application with php and jquery, although the javascript functions you made remained unmodified. On some occasions the popup close button does not close the popup, I also tried calling the close function from console, it returns “undefined”.
    I have no idea why this error occurs, I will be very grateful if you provided some hint on how I can resolve this issue.
    Thanks in advance.

    ReplyCancel
  18. Robert Sherman
    3 years ago

    Popup box disapears after postback.

    I have a postback section:

    function isPostBack() {//Use during postbacks...

    }

    What part of the code do I have to put there to keep the popup box between postbacks?

    ReplyCancel
  19. Gyan
    3 years ago

    When the pop up box is on,other jquery codes of the page become disables.They stop working until I refresh the page.Why?Sir,Help me.

    ReplyCancel
    • Taiwanese
      3 years ago

      Because when:

      document.getElementsByTagName(“body”)[0].innerHTML = document.getElementsByTagName(“body”)[0].innerHTML + element;

      This code will change HTML body, so it would never load JQuery source

      use this:

      $(“body”).append(element);

      it will work

      ReplyCancel
  20. Gyan
    3 years ago

    Hi,I add the following java code inside your jquery code,Sir. But,the java code is always executed without clicking the noti_button.What is the error,Sir!

    else {
    $(‘#noti_Button’).css(‘background-color’, ‘#FFF’); // CHANGE BACKGROUND COLOR OF THE BUTTON.
    var up= function update(){

    }
    }
    });

    ReplyCancel
    • Gyan
      3 years ago

      var up= function update(){
      “”//This code
      }

      ReplyCancel
  21. Rajasekhar
    3 years ago

    first of all thank you,

    but i have some doubt where i place typing message and display and how to i store date in my database .please tell me and replay me as soon possible plz or another format is their. plz replay me i'm waiting for ur answer.plz

    ReplyCancel
  22. sadaru
    3 years ago

    who can… create this chat system with login and chat … with database… show massage and send massage and etc…
    full chat system code give me…
    pease reply

    ReplyCancel
    • shubham
      3 years ago

      i can create one using php, html, jq, css. But there is a problem, i wont give it anyone, whom i even dont know.

      ReplyCancel
    • manoj kumar
      3 years ago

      mail me your id

      ReplyCancel
      • vanita
        2 years ago

        hi sir pls send me full working script like fb

        thank u sir

        ReplyCancel
  23. yudha
    3 years ago

    thank you sir :)

    ReplyCancel
  24. surf.az
    3 years ago

    the demo doesnt work

    ReplyCancel
  25. sp
    3 years ago

    it works fine only if write code like this

    but it works only for once when we write code like this(using jquery)

    $('.chatpopup').on('click', function () {
    register_popup(1, "sp");
    });

    Please resolve this issue asap.

    ReplyCancel
  26. Deric
    3 years ago

    Nice Work Simple and Efficient , but you forgot to add the textbox to the chat pop-up

    ReplyCancel
  27. Omar
    3 years ago

    How to make it work with Internet Explorer 8 and more?

    ReplyCancel
  28. Oranusi Anayo
    3 years ago

    Please how do make it work perfectly on meteor

    ReplyCancel
  29. Derrick
    3 years ago

    Hello , Please , help me , am using Bootstrap, with the script and everytihng is fine only that each time i popup the chat window, it disables Javascript/jquery .

    ReplyCancel
  30. Hrashvardhan
    4 years ago

    How can i use this code with mysql because my record save to database

    ReplyCancel
  31. Debashis
    4 years ago

    where i type this code…?

    ReplyCancel
  32. Nevil
    4 years ago

    I used the popup window of facebook chat and its amazing.I put in textarea for chat. Now the problem is i cannot make it as richtextbox (using texteditor) for emotes purposes.The texteditor gets integrated but the texteditor functionality is not shown. i tried calling the javascript and css files…during popup window creation..still the same.. console of browser shows no error. The texteditor working in webforms but not in chat window…

    ReplyCancel
    • Bobby
      4 years ago

      hi…i have a same problem too…until now i still trying to add a richTextBox to PopupMessage

      ReplyCancel
    • Sujay
      3 years ago

      hey hii..

      How to add textarea.. please give mi that code..

      ReplyCancel
  33. Helly
    4 years ago

    How to toggle the popup chat box? someone please answer. thanks.

    ReplyCancel
    • hieu vo
      4 years ago

      Just use javascript to catch the click event and then toggle the chat box using css element call display (display: none //to hide the chat box, display: block //to show the chat box).

      ReplyCancel
  34. ratneshwar
    4 years ago

    I have simple live script which in opentok.

    ReplyCancel
    • shahd
      4 years ago

      oooh how are you?

      ReplyCancel
      • Gaza
        4 years ago

        fine 😀 اه

        ReplyCancel
  35. Mythili
    4 years ago

    Popup window is nice its working.Is it possible to place the textarea inside the popup window along with smilies and other formatting options?

    ReplyCancel
  36. Kartik Arora
    4 years ago

    Hi

    I am using your script and its working fine for me in my project.
    But i am also using angular JS in my project. When i use this code to open chat box after that my angular JS code stops working until i refresh the complete page.
    I am unable to get why is it not working. If you can help me with this, it would be great.

    Thanks

    ReplyCancel
    • Ayoub
      4 years ago

      the same problem as Kartik Arora

      ReplyCancel
      • Vinod
        4 years ago

        I am also having same problem

        ReplyCancel
        • Vinod
          4 years ago

          can i know what did u do for solution

          ReplyCancel
    • Gyan
      3 years ago

      The same problem and do you have the solution .Reply me

      ReplyCancel
  37. nitn
    4 years ago

    how to chat in pop box

    ReplyCancel
  38. Jollin George
    4 years ago

    Hi dude

    Your application is great but how to send message from one user to another

    ReplyCancel
  39. me
    4 years ago

    here u are using php and mysql but i am using sql server and hve no knowledge in php
    so i need to use http post

    ReplyCancel
  40. me
    4 years ago

    how to using jquery to send messages

    ReplyCancel
  41. troll
    4 years ago

    nice! thanks Narayan, do you recommand any chat script to use your script?

    ReplyCancel
  42. stephen aryee
    4 years ago

    i have a challenge; any time am chatting with two or more people, only one session of the chat works. example, suppose am chatting with Steve, it works well, but if am chatting with more than one user on the site one works.. (stephen.aryee69@gmail.com)

    here is the script that insert into the database

    HERE IS THE HTML:

    <a href="javascript:register_popup('’, ”);” ‘;?>

    $Uof[3] && $img[4]===”Male”)

    {

    ?>

    <li id='’ class=’holder normaltip’ title=’He is Online’><img src='profile-pics/’ class=’fri-online-img’/>

    $Uof[3] && $img[4]===”Female”)

    {

    ?>

    <li id='’ class=’holder normaltip’ title=’She is Online’><img src='profile-pics/’ class=’fri-online-img’/>

    <li id='’ class=’holder ‘normaltip’ title=’He is Offline’><img src='profile-pics/’ class=’fri-online-img’/>

    <li id='’ class=’holder normaltip’ title=’She is Offline’><img src='profile-pics/’ class=’fri-online-img’/>

    HERE IS THE JQUERY:

    $(document).ready(function() {

    // load messages every 1000 milliseconds from server.
    load_data = {‘fetch':1};

    window.setInterval(function(){

    var popups_id = $(“.chat-popup:last”).attr(‘id’); //id from Chat popUp window
    $.post(“sidebar_right/functions/writechat.php?tofriend=”+ popups_id, load_data, function(data) {
    $(‘.show_chatting-‘+ popups_id).html(data);
    });
    }, 1000);

    //method to trigger when user hits enter key
    $(“body”).on(“submit”, “form.chatting-form”, function (e){
    e.preventDefault();

    var popups_id2 = $(“.chat-popup”).attr(‘id’); //id from Chat popUp window
    var chat_with = $(this).attr(‘id’).replace(‘the_chat_’,”); //msg to
    var chat_msg = $(‘.chat_messages’).attr(“value”);

    if(popups_id2)
    {
    post_data = {‘username':chat_with, ‘message':chat_msg};

    //send data to “writechat.php” using jQuery $.post()
    $.post(‘configs/writechat.php’, post_data, function(data) {

    //append data into messagebox with jQuery fade effect!
    $(data).hide().appendTo(‘.show_chatting-‘+ chat_with).fadeIn();

    //reset value of message box
    $(‘.chat_messages’).val(”);

    });
    }
    });
    });

    HERE IS THE PHP

    <?php

    if($_POST)

    {

    if(isset($_POST["message"]))

    {

    $username = sanitizeString(trim($_POST["username"]));

    $message = sanitizeString(trim($_POST["message"]));

    $insert_time = time(); // current time

    if(queryMysql("INSERT INTO chat_messages VALUES(NULL,'$user','$username','$message','$insert_time', 1)"))

    {

    echo '’.timeAgo(time()).”.$message.”;

    }

    queryMysql(“DELETE FROM chat_messages WHERE chat_from=” OR message=””);

    }

    elseif($_POST[“fetch”]==1)

    {

    $results = queryMysql(“SELECT id, chat_with, chat_from, message, timesent FROM chat_messages WHERE (chat_from = ‘”.$_SESSION[‘user’].”‘ AND chat_with = ‘”.$_GET[‘tofriend’].”‘) OR (chat_with = ‘”.$_SESSION[‘user’].”‘ AND chat_from = ‘”.$_GET[‘tofriend’].”‘) ORDER BY chat_messages.id ASC”);

    while($row = mysql_fetch_array($results))

    {

    $dfd = queryMysql(“SELECT fname,lname,image FROM rnmembers WHERE user = ‘”.$row[‘chat_from’].”‘”);

    $noms = mysql_fetch_row($dfd);

    $msg_time = timeAgo($row[“timesent”]); //message posted time

    if($row[‘chat_from’]==$_SESSION[‘user’] && $row[‘chat_with’]==$_GET[‘tofriend’])

    {

    echo ”;?><?php echo $msg_time.'

    ‘.$row[“message”];

    echo”;

    }

    else if($row[‘chat_with’]==$_SESSION[‘user’] && $row[‘chat_from’]==$_GET[‘tofriend’])

    {

    echo ”;?><?php echo $msg_time.'

    ‘.$row[“message”];

    echo’‘;
    }
    }
    }
    }
    ?>

    HERE IS YOUR SCRIPT (with little changes)

    //this function can remove a array element.

    Array.remove = function(array, from, to) {

    var rest = array.slice((to || from) + 1 || array.length);

    array.length = from < 0 ? array.length + from : from;

    return array.push.apply(array, rest);

    };

    //this variable represents the total number of popups can be displayed according to the viewport width

    var total_popups = 0;

    //arrays of popups ids

    var popups = [];

    //this is used to close a popup

    function close_popup(id)

    {

    for(var iii = 0; iii < popups.length; iii++)

    {

    if(id == popups[iii])

    {

    Array.remove(popups, iii);

    document.getElementById(id).style.display = "none";

    calculate_popups();

    return;

    }

    }

    }

    //displays the popups. Displays based on the maximum number of popups that can be displayed on the current viewport width

    function display_popups()

    {

    var right = 270;

    var iii = 0;

    for(iii; iii < total_popups; iii++)

    {

    if(popups[iii] != undefined)

    {

    var element = document.getElementById(popups[iii]);

    element.style.right = right + "px";

    right = right + 320;

    element.style.display = "block";

    }

    }

    for(var jjj = iii; jjj < popups.length; jjj++)

    {

    var element = document.getElementById(popups[jjj]);

    element.style.display = "none";

    }

    }

    //creates markup for a new popup. Adds the id to popups array.

    function register_popup(id, name)

    {

    for(var iii = 0; iii < popups.length; iii++)

    {

    //already registered. Bring it to front.

    if(id == popups[iii])

    {

    Array.remove(popups, iii);

    popups.unshift(id);

    calculate_popups();

    return;

    }

    }

    var element = '';

    element = element + ”;

    element = element + ”+ name +”;

    element = element + ‘‘;

    element = element + ”;

    element = element + ”;

    document.getElementsByTagName(“section”)[0].innerHTML = document.getElementsByTagName(“section”)[0].innerHTML + element;

    popups.unshift(id);

    calculate_popups();

    }

    //calculate the total number of popups suitable and then populate the toatal_popups variable.

    function calculate_popups()

    {

    var width = window.innerWidth;

    if(width < 540)

    {

    total_popups = 0;

    }

    else

    {

    width = width – 200;

    //320 is width of a single popup box

    total_popups = parseInt(width/320);

    }

    display_popups();

    }

    //recalculate when window is loaded and also when window is resized.

    window.addEventListener("resize", calculate_popups);

    window.addEventListener("load", calculate_popups);

    ReplyCancel
    • Narayan Prusty
      4 years ago

      Are you using my script?

      ReplyCancel
      • stephen aryee
        4 years ago

        yes am using your script

        ReplyCancel
      • Fido
        3 years ago

        Narayan, did u update the script ? how can i use’it for chat? I will apreciate your help

        ReplyCancel
      • suresh sanasam
        2 years ago

        hello sir i have been dealing with this problem for the last 3 days my problem is that in the popup message i want to display message from database but the ” ID” (register popup function)is in javascript variable so i tried to call it with ajax and return the variable data to php variable which i can Query the result to the popup message box but it didnt work out..Is there any way that i can excess to the database from the JS variable with ajax and return data to the popup message box …i tried every thing please help i cant fix this problem

        ReplyCancel
      • guna
        1 year ago

        hai sir i’m using your script for chatting application but im face a problem in that script there is no message sending box please help to share the code or guide me please help im started career just know but im not solve this problem please help me

        ReplyCancel
    • Debashis
      4 years ago

      where i type this one…..?

      ReplyCancel
    • Sanjay Dey
      3 years ago

      use $_POST rather than $_SESSION

      ReplyCancel
    • Fido
      3 years ago

      Nice work, can u send me the script? If u can ?

      ReplyCancel
  43. NK
    5 years ago

    Hi there, great script. I have a few questions as I’d like to add a few things to this already wonderful chat/pop-up script but need your input. How can I minimize each pop by clicking on the pop-up head and it scrolls down to the pop-up head title…much like facebook’s functionality? It’s not as useful if you can only close it. Also, is there a way that you can create a tab simillar to that of facebook when you open a certain amount of pop you can scroll through the chat users in that tab button?

    Any help with code samples is very much appreciated as I am new to javascript/jQuery. Thank you.

    ReplyCancel
    • Narayan Prusty
      5 years ago

      Follow the steps to achieve it:

      1. Create a new button in header.
      2. When user clicks on it call a JS function with box id as parameter.
      3. This function toggles the message area of the box.

      If I get time I will update the script also. Thanks.

      ReplyCancel
  44. dare
    5 years ago

    hello
    yor scripts are really great… but i would like to know how i can make this script such that as i move from page to page..the chat window stays put…what you have now..as i move from one page to another i need to start opening current cahts all over again and thats not nice..
    thanks

    ReplyCancel
    • Narayan Prusty
      5 years ago

      Follow these instructions to save the state of the popups between page reloads:

      1. Whenever u make changes to the popups[] array, make sure u send the array to your server using AJAX.

      2. During page load, make sure u retrieve the popups[] array value using AJAX and assign it.

      ReplyCancel
      • Alemseged Matusala
        4 years ago

        hello sir…..it’s nice to find you… what about the messaging box ? am not seeing the message box to right..? .

        ReplyCancel
      • sonu
        3 years ago

        i added jquery code for the textarea msg but that does not work.

        //this function can remove a array element.
        Array.remove = function(array, from, to) {
        var rest = array.slice((to || from) + 1 || array.length);
        array.length = from < 0 ? array.length + from : from;
        return array.push.apply(array, rest);
        };

        //this variable represents the total number of popups can be displayed according to the viewport width
        var total_popups = 0;

        //arrays of popups ids
        var popups = [];

        //this is used to close a popup
        function close_popup(id)
        {
        for(var iii = 0; iii < popups.length; iii++)
        {
        if(id == popups[iii])
        {
        Array.remove(popups, iii);

        document.getElementById(id).style.display = "none";

        calculate_popups();

        return;
        }
        }
        }

        //displays the popups. Displays based on the maximum number of popups that can be displayed on the current viewport width
        function display_popups()
        {
        var right = 220;

        var iii = 0;
        for(iii; iii < total_popups; iii++)
        {
        if(popups[iii] != undefined)
        {
        var element = document.getElementById(popups[iii]);
        element.style.right = right + "px";
        right = right + 320;
        element.style.display = "block";
        }
        }

        for(var jjj = iii; jjj < popups.length; jjj++)
        {
        var element = document.getElementById(popups[jjj]);
        element.style.display = "none";
        }
        }

        //creates markup for a new popup. Adds the id to popups array.
        function register_popup(id, name)
        {

        for(var iii = 0; iii < popups.length; iii++)
        {
        //already registered. Bring it to front.
        if(id == popups[iii])
        {
        Array.remove(popups, iii);

        popups.unshift(id);

        calculate_popups();

        return;
        }
        }

        var element = '';
        element = element + ”;
        element = element + ”+ name +”;
        element = element + ‘✕‘;
        element = element + ”;

        document.getElementsByTagName(“body”)[0].innerHTML = document.getElementsByTagName(“body”)[0].innerHTML + element;

        popups.unshift(id);

        calculate_popups();

        }

        //calculate the total number of popups suitable and then populate the toatal_popups variable.
        function calculate_popups()
        {
        var width = window.innerWidth;
        if(width < 540)
        {
        total_popups = 0;
        }
        else
        {
        width = width – 200;
        //320 is width of a single popup box
        total_popups = parseInt(width/320);
        }

        display_popups();

        }

        //recalculate when window is loaded and also when window is resized.
        window.addEventListener("resize", calculate_popups);
        window.addEventListener("load", calculate_popups);

        $(document).ready(function(){
        $(‘textarea’).keypress(
        function(e){
        if(e.keyCode == 13){
        var msg = $(this).val();
        $(this).val(”);
        $(“”+msg+””).insertBefore(‘.msg_insert’);

        }
        });
        $(‘.popup-head’).click(function(){
        $(‘.popup-messages’).slideToggle(‘slow’);
        });

        });

        <div class='popup-box chat-popup' id='’ >

        <div class='popup-head'>
        <div class="popup-head-left"><?php echo $find['username']; ?></div>
        <div class="popup-head-right"><a href="javascript:close_popup('<?php echo $find['id']; ?>');">✕</a></div>
        <div style="clear: both"></div>
        </div>
        <div class='popup-messages'>

        <div class="msg_A">this is massage a</div>
        <div class="msg_B">this is massage b</div>
        <div class="msg_insert"></div>

        <div class="msg_footer" >
        <textarea class="msg_input"> Wright...</textarea>
        </div>
        </div>
        </div>

        ReplyCancel

Leave a Reply to Gyan Cancel reply

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

Narayan Prusty

I am a full-stack web developer. I specialize in Blockchain and JavaScript. This is my personal blog where I write about programming and technologies that I learn and feel interesting to share.

Image5 years ago 73 Comments Web Development
Share this
0
GooglePlus
0
Facebook
0
Twitter
0
Linkedin
  • CSS Implementation
  • JavaScript Implementation
  • Live Demo and Complete code
Related Articles
  • Facebook Style Chat Bubbles using CSS
  • Responsive Typography Techniques
  • wikiHow Style Popup
  • Media Queries Tutorial
  • Create a Chat App using Intel XDK and XMPP
Our Sponsor
Freelance: I am available
@narayanprusty
Hi, I am a full-stack developer - focusing on JavaScript, WordPress, Blockchain, DevOps, Serverless and Cordova. You can outsource your app development to me.





Will get back to you soon!!!
WordPress
ReactJS
Meteor
Blockchain
Serverless
Kubernetes
DevOps
DB & Storage
Ejabberd
Let's get started
My Books

2014 - 2015 © QNimate
All tutorials MIT license