Showing posts with label Function (mathematics). Show all posts
Showing posts with label Function (mathematics). Show all posts

Tuesday, 3 January 2012

How to track online status of a user in my website like facebook

I came across this when i was developing 1 of my social website aFriend.in.

I found out a very simple solution using jQuery or Javascript
setInterval("update()", 10000); // Update every 10 seconds 
function update()
{
$.post("update.php"); // Sends request to update.php
}

Your update.php file would have a bit of code like this:
session_start(); 
if ($_SESSION["userid"])
updateUserStatus($_SESSION["userid"]);

This all assumes that you store your userid as a session-variable when users login to your website. The updateUserStatus() function is just a simple query, like the following:
UPDATE users SET lastActiveTime = NOW() WHERE userid = $userid 

So that takes care of your storage. Now to retrieve the list of users who are "online." For this, you'll want another jQuery-call, and another setInterval() call:
setInterval("getList()", 10000) // Get users-online every 10 seconds 
function getList()
{
$.post("getList.php", function(list)
{ $("listBox").html(list); });
}

This function requests a bit of HTML form the server every 10 seconds. The getList.php page would look like this:
session_start(); 
if (!$_SESSION["userid"]) die; // Don't give the list to anybody not logged in
$users = getOnlineUsers(); /* Gets all users with lastActiveTime within the last 1 minute */
$output = "<ul>";
foreach ($users as $user)
{
$output .= "<li>".$user["userName"]."</li>";
}
$output .= "</ul>";
print $output;

That would output the following HTML:
<ul> <li>Jonathan Sampson</li> 
<li>Paolo Bergantino</li>
<li>John Skeet</li> </ul>

That list is included in your jQuery variable named "list." Look back up into our last jQuery block and you'll see it there.

jQuery will take this list, and place it within a div having the classname of "listBox."
<div></div> 

Thursday, 15 December 2011

Google plus like drag and drop adding groups


You might have marked a cool feature in google plus, where we add people to groups simply by dragging it to the perticular frame.

Here is a explanation of the above implementation using JQuery and PHP.
Google Plus Style Drag and Drop adding Groups


Sample database contains three tables and relationship between Members and Groups.

Members
Table contains members(users) data such as member_id, member_image and etc.
CREATE TABLE IF NOT EXISTS `members` ( `member_id` int(9) NOT NULL AUTO_INCREMENT, `member_name` varchar(220) NOT NULL, `member_image` text NOT NULL, `dated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`member_id`) );

Groups
Contains groups information.
CREATE TABLE IF NOT EXISTS `groups` ( `group_id` int(9)  AUTO_INCREMENT, `group_name` varchar(220), `sort` int(9), `date` timestamp  DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`group_id`), KEY `sort` (`sort`) );

User_group
Members and Groups table relationship table contains user_id(same as memeber_id), group_id, member_id() and sort(ordering)
CREATE TABLE IF NOT EXISTS `user_group` ( `id` int(9) NOT NULL AUTO_INCREMENT, `user_id` int(9) NOT NULL, `group_id` int(9) NOT NULL, `member_id` int(9) NOT NULL, `sort` int(9) NOT NULL, PRIMARY KEY (`id`) );

Javascript
Here draggable applying for two classes .members and .group
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.js"></script> <script type="text/javascript" src="jquery.livequery.min.js"></script> <script type="text/javascript" > $(function() { // Initiate draggable for public and groups var $gallery = $( ".members, .group" ); $( "img", $gallery ).live("mouseenter", function() { var $this = $(this); if(!$this.is(':data(draggable)')) { $this.draggable({ helper: "clone", containment: $( "#demo-frame" ).length ? "#demo-frame" : "document", cursor: "move" }); } }); // Initiate Droppable for groups // Adding members into groups // Removing members from groups // Shift members one group to another $(".group").livequery(function(){ var casePublic = false; $(this).droppable({ activeClass: "ui-state-highlight", drop: function( event, ui ) { var m_id = $(ui.draggable).attr('rel'); if(!m_id) { casePublic = true; var m_id = $(ui.draggable).attr("id"); m_id = parseInt(m_id.substring(3)); } var g_id = $(this).attr('id'); dropPublic(m_id, g_id, casePublic); $("#mem"+m_id).hide(); $( "<li></li>" ).html( ui.draggable ).appendTo( this ); }, out: function(event, ui) { var m_id = $(ui.draggable).attr('rel'); var g_id = $(this).attr('id'); $(ui.draggable).hide("explode", 1000); removeMember(g_id,m_id); } }); }); // Add or shift members from groups function dropPublic(m_id, g_id,caseFrom) { $.ajax({ type:"GET", url:"groups.php?m_id="+m_id+"&g_id="+g_id, cache:false, success:function(response){ $.get("groups.php?reload_groups", function(data){ $("#groupsall").html(data); $("#added"+g_id).animate({"opacity" : "10" },10); $("#added"+g_id).show(); $("#added"+g_id).animate({"margin-top": "-50px"}, 450); $("#added"+g_id).animate({"margin-top": "0px","opacity" : "0" }, 450); }); } }); } // Remove memebers from groups // It will restore into public groups or non grouped members function removeMember(g_id,m_id) { $.ajax({ type:"GET", url:"groups.php?do=drop&mid="+m_id, cache:false, success:function(response){ $("#removed"+g_id).animate({"opacity" : "10" },10); $("#removed"+g_id).show(); $("#removed"+g_id).animate({"margin-top": "-50px"}, 450); $("#removed"+g_id).animate({"margin-top": "0px","opacity" : "0" }, 450); $.get("groups.php?reload", function(data){ $("#public").html(data); }); } }); } }); </script>

groups.php
<?php require_once("multipleDiv.inc.php"); // Initiate Object $obj = new Multiplediv(); // Add or Update Ajax Call if(isset($_GET['m_id']) and isset($_GET['g_id'])) { $obj->addMembers((int)$_GET['m_id'], (int)$_GET['g_id']); exit; } // Remove Memebers from groups Ajax call if(isset($_GET['do'])) { $obj->removeMember($_GET['mid']); exit; } // Reload groups each ajax call if(isset($_GET['reload'])){ echo $obj->getMembers_reload(); exit; } if(isset($_GET['reload_groups'])){ echo $obj->getmembergroups_reload(); exit; } // Initiate Groups and members $members = $obj->public_members(); $groups = $obj->groups(); ?> Friends <div id="main_portion"> <div id="public"> <!-- Initiate members --> <?php if(!isset($members)) $members = $obj->public_members(); if($members) { foreach($members as $member) { extract($member); echo "<div class='members' id='mem".$member_id."'>\n"; echo "<img src='images/".$member_image."' rel='".$member_id."'>\n"; echo "<b>".ucwords($member_name)."</b>\n"; echo "</div>"; } } else echo "Members not available"; ?> </div> <div id="groupsall"> Groups <!-- Initiate Groups --> <?php if(!isset($groups)) $groups = $obj->groups(); if($groups) { foreach($groups as $group) { extract($group); echo "<div id='".$group_id."' class='group'>\n"; echo ucwords($group_name); echo "<div id='added".$group_id."' class='add' style='display:none;' ><img src='images/green.jpg'></div>"; echo "<div id='removed".$group_id."' class='remove' style='display:none;' ><img src='images/red.jpg'></div>"; echo "<ul>\n"; echo $obj->updateGroups($group_id); echo "</ul></div>"; } } ?>


multipleDiv.inc.php
Download this and modify database connection credentials.
<?php // Database declaration's define("SERVER", "localhost"); define("USER", "username"); define("PASSWORD", "password"); define("DB", "database");class Multiplediv { ........................ ........................ ......................... } ?>

Friday, 25 November 2011

Getting and setting attributes [attr()]

In the previous chapter, we saw how easy it was to get and set text and HTML content from and to an element. Fortunately, changing one or more attributes of an element is just as easy. We use the attr() method for this, which in its simplest form takes one parameter: The name of the attribute we wish to get:

<a href="http://www.google.com" id="aGoogle1">Google Link</a>
<script type="text/javascript">
$(function()
{
        alert($("#aGoogle1").attr("href"));
});
</script>

In this example, we get the value of the "href" attribute of our link and then show it to the user. To change an attribute, we simply specify an extra parameter:

<a href="http://www.google.com" id="aGoogle2">Google Link</a>
<script type="text/javascript">
$(function()
{
        $("#aGoogle2").attr("href", "http://www.google.co.uk");
});
</script>

This will change the link to point to the British version of Google. The attr() method can also take a map of name/value pairs, for setting multiple attributes at the same time. Here we set both the href and the title attributes simultaneously:

<a href="http://www.google.com" id="aGoogle3">Google Link</a>
<script type="text/javascript">
$(function()
{
        $("#aGoogle3").attr(
        {
                "href" : "http://www.google.co.uk",
                "title" : "Google.co.uk"
        });
});
</script>

The attr() method also supports the special overload where the value parameter is instead a callback function, allowing you to access the index of the element selected as well as the existing attribute value. Here's an example of just that:

<a href="http://www.google.com/" class="google">Google.com</a><br />
<a href="http://www.google.co.uk/" class="google">Google UK</a><br />
<a href="http://www.google.de/" class="google">Google DE</a><br />

<script type="text/javascript">
$(function()
{
        $("a.google").attr("href", function(index, oldValue)
        {
                return oldValue + "imghp?tab=wi";
        });
});
</script>

We simply change all the Google links to point to the Image search instead of the default page, by adding an extra parameter to the href attribute. In this example we don't really use the index parameter, but we could have if we needed it, to tell us which index in the list of elements selected we're currently dealing with.

Introduction to events

Events in JavaScript are usually something where you write a snippet of code or a name of a function within one of the event attributes on an HTML tag. For instance, you can create an event for a link by writing code like this:

<a href="javascript:void(0);" onclick="alert('Hello, world!');">Test</a>

And of course this is still perfectly valid when using jQuery. However, using jQuery, you can bind code to the event of an element even easier, especially in cases where you want to attach anonymous functions or use the same code for multiple events, or even the same code for multiple events of multiple elements. As an example, you could bind the same event to all links and span tags in your document, with only a few lines of code like this:
<script type="text/javascript">
$(function()
{
        $("a, span").bind("click", function() {
                alert('Hello, world!');
        });
});
</script>

We use the bind method, which is essential when working with events and jQuery. In the following chapters we will tell you more about how it works, along with other event related information you need.

The unbind() method

In the previous chapter, we used the bind() method to subscribe to events with jQuery. However, you may need to remove these subscriptions again for various reasons, to prevent the event handler to be executed once the event occurs. We do this with the unbind() method, which in its simplest form simply looks like this:

$("a").unbind();

This will remove any event handlers that you have attached with the bind() function. However, you may want to only remove event subscriptions of a specific type, for instance clicks and doubleclicks:

$("a").unbind("click doubleclick");

Simply separate the event types with a comma. Here is a more complete example, where you can see it all in effect:

<a href="javascript:void(0);">Test 1</a>
<a href="javascript:void(0);">Test 2</a>
<script type="text/javascript">
var msg = "Hello, world!";
$(function()
{
        $("a").bind("click", function() {
                $("a").unbind("click");
                alert("First and only message from me!");
        });
});
</script>

In this little example, we subscribe to the click event of all links. However, once a link is clicked, we remove all the subscriptions and alert the clicker about it. The event handler will no longer be activated by the links.

jQuery allows you to subscribe to the same event type more than one time. This can come in handy if you want the same event to do more than one thing in different situations. You do it by calling the bind() method for each time you want to attach a piece of code to it, like this:

<a href="javascript:void(0);">Test 1</a>
<a href="javascript:void(0);">Test 2</a>
<script type="text/javascript">
var msg = "Hello, world!";
$(function()
{
        $("a").bind("click", function() {
                alert("First event handler!");
        });

        $("a").bind("click", function() {
                alert("Second event handler!");
                $("a").unbind("click");
        });
});
</script>

However, this opens up for the possibility that once you unbind an event, you may be removing event subscriptions used a whole other place in your code, which you still need. If you try the example, you will see the result of this - when you click a link, all of the event subscriptions are removed. jQuery allows you to specify a secondary argument, which contains a reference to the specific handler you would like to remove. This way, we can make sure that we only remove the event subscription we intend to. Here's an example:

<a href="javascript:void(0);">Test 1</a>
<a href="javascript:void(0);">Test 2</a>
<script type="text/javascript">
var msg = "Hello, world!";
$(function()
{
        var handler1 = function()
        {
                alert("First event handler!");
        }

        var handler2 = function()
        {
                alert("Second event handler!");
                $("a").unbind("click", handler2);
        }

        $("a").bind("click", handler1);
        $("a").bind("click", handler2);
});
</script>

By specifying handler2 as the secondary parameter, only this specific event handler is removed. Try the example. The secondary message is only displayed the first time you click the link.

The live() method

In the previous chapters, we used the bind() and unbind() methods to attach and detach event handlers to various elements on the page. This works great for elements which already exists, but what if you want your event handler to be attached to future elements as well? Normally you would have to do this manually, upon creating the new elements, and this is still possible. However, using the live() method, you can inform jQuery to attach your event handler to any future elements which matches your original selector, without having to lift a finger. Let me first show you an example where we use the bind() method, and then replace it with the live() method, to show you the difference:

<div id="divTestArea1">
        <a href="javascript:void(0);" onclick="AddBox();">Add box</a>
        <div class="test">This is a box</div>
</div>

<script type="text/javascript">
$(function()
{
        $(".test").bind("mouseover", function()
        {
                $(this).css("background-color", "blue");
        }).bind("mouseout", function()
        {
                $(this).css("background-color", "white");
        });
});

function AddBox()
{
        var div = $("<div></div>").addClass("test").text("Another box");
        $("#divTestArea1").append(div);
}
</script>

Okay, this example might seem a bit complicated, but actually it's not. Let me walk you through it. We have a link, which will call the AddBox() JavaScript method, and then we have a div with the class "test". The AddBox() method will simply add another div to the page, with the same class, so that when you click the link, you get yet another box on the page. In the ready event, we select all elements with the "test" class and then we bind a handler to two of the events: The mouseover and the mouseout event, where we change the color of the element invoking the event. Try the example in your browser. The first div will have the mouseover effect, but if you click the link to add more boxes, they won't have the same effect. The reason is pretty obvious: We attached the events before these new boxes were created.

Now try the following example instead. I have only changed two words in it: The two calls to bind() has been replaced with calls to live():

<div id="divTestArea2">
        <a href="javascript:void(0);" onclick="AddBox();">Add box</a>
        <div class="test">This is a box</div>
</div>

<script type="text/javascript">
$(function()
{
        $(".test").live("mouseover", function()
        {
                $(this).css("background-color", "blue");
        }).live("mouseout", function()
        {
                $(this).css("background-color", "white");
        });
});

function AddBox()
{
        var div = $("<div></div>").addClass("test").text("Another box");
        $("#divTestArea2").append(div);
}
</script>

Now if you run this example, you will see that even though you add new elements after the page has loaded, jQuery will automatically attach the event handlers to them for you. The live() method works just like bind() in all the other aspects, so check the previous chapters for more information on it. The same goes for the die() method, which works just like the unbind() method, but should be used for cases where the live() method has been used.

Tuesday, 30 August 2011

Facebook Style CSS JQuery drop down menus



Now a days drop down menus are becoming more and more popular. They arebeing used in  most modern websites like facebook, gmail, gplus, orkut, gmail, yahoo...

There is no secret that they are using JQuery and HTML to implement the above feature.

Even you can do this by writing some very simple code.

 

       

 

 

 

 

Step-1:

Lets write our HTML code.
<div style="height:300px;">
            <div style="width:162px;">
                <dl style="">
                   <dt>
                   <a class="" id="linkglobal"
                   style="cursor: pointer;"></a></dt>
                    <dd>
                        <ul style="display: none;" id="ulglobal">
                            <li><a href="#">Everyone</a></li>
                            <li><a href="#">Friends</a></li>
                            <li><a href="#">Only Me</a></li>
                            <li><a href="#">Customize</a></li>
                      </ul>
                   </dd>
                </dl>
            </div>
        </div>

Step-2:
The next step is to add some CSS which will further stylize the menu
which is going to look just like facebook.
<style type="text/css">

    *{
        padding:0;
        margin:0;
    }

    body{
        color: #333333;
        direction: ltr;
        font-family:
        "lucida grande",tahoma,verdana,arial,sans-serif;
        font-size: 11px;
        text-align: left;
    }

/* Grey Small Dropdown */

/* General dropdown styles */
.dropdown dl{ margin-left:5px; }
.dropdown dd, .dropdown dt, .dropdown ul
{ margin:0px; padding:0px; }
.dropdown dd { position:relative; }

/* DT styles for sliding doors */
.dropdown dt a {background:#EEEEEE
url(privacyOff.png) no-repeat scroll right center;
    display:block; width:40px; height:22px; cursor:pointer;}

.dropdown dt a.selected{
    background:#EEEEEE url(privacyOn.png)
    no-repeat scroll right center;
}
.dropdown dt a span {
cursor:pointer; display:block; padding:5px;}

/* UL styles */
.dropdown dd ul {
background:#EEEEEE none repeat scroll 0 0; display:none;
    list-style:none; padding:3px 0; position:absolute;
    left:0px; width:160px; left:auto; right:0;
    border:1px solid #656565; cursor:pointer;
    }
.dropdown dd ul li{
background-color:#EEEEEE; margin:0; width:160px;
}
.dropdown span.value { display:none;}
.dropdown dd ul li a {
display:block; font-weight:normal; width:137px;
text-align:left; overflow:hidden; padding:2px 4px 3px 19px;
color:#111111; text-decoration:none;
}
.dropdown dd ul li a:hover{
background:#656565; color:white; text-decoration:none;
}
.dropdown dd ul li a:visited{
text-decoration:none;
}
</style>

Step-3 :

Now lets include the JQuery into our webpage and start writing the necessary JQuery function calls.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".dropdown dt a").click(function() {

// Change the behaviour of onclick states for links within the menu.
var toggleId = "#" + this.id.replace(/^link/,"ul");

// Hides all other menus depending on JQuery id assigned to them
$(".dropdown dd ul").not(toggleId).hide();

//Only toggles the menu we want since the menu could be showing and we want to hide it.
$(toggleId).toggle();

//Change the css class on the menu header to show the selected class.
if($(toggleId).css("display") == "none"){
$(this).removeClass("selected");
}else{
$(this).addClass("selected");
}

});

$(".dropdown dd ul li a").click(function() {

// This is the default behaviour for all links within the menus
var text = $(this).html();
$(".dropdown dt a span").html(text);
$(".dropdown dd ul").hide();
});

$(document).bind('click', function(e) {

// Lets hide the menu when the page is clicked anywhere but the menu.
var $clicked = $(e.target);
if (! $clicked.parents().hasClass("dropdown")){
$(".dropdown dd ul").hide();
$(".dropdown dt a").removeClass("selected");
}});
});
</script>