Saturday, 31 May 2014

Human Computer Interface introduction with calculator example

human computer interaction,human computer interaction example,human computer interaction calculator ,artificial intelligence example,artificial intelligence calculator
This article is to demonstrate a human computer interaction system with a calculator example.
I am trying to reduce the GUI interface and make a human command mode to the system.Many of the researchers think that human speak  recognition is the basic step of Human Computer Interaction (HCI).   But I don't think so,because human speak recognition is a gigantic problem.
Because the  pronunciation and volume variation of each persion is varying and the slang are also different.

But the easy way to give HCI commands to computer is by text medium.That is we can simply type the commands and execute the command.
Here you can see the example HCI calculator:-

HCI Calculator

Enter command
Result


This is a basic calculator with addition,subtraction,multiplication and division.    But odd to regular calculators you can't see digit or operator buttons instead  a 'Enter command'   box and 'Calculate'   button. When you write commands in the box and click calculate button the result will display in the result text box.

The command should have one operator and two operands.

My first command is ' add 4 7 ' .    It mean find the sum of 4 and 7.
You can see the screenshot here:-







But the real beauty is where  the command 4 add 7 also give the same result.
Then  4 7 add give the same result.
 addition 4 7   and 4+7 has the same result

prod 4 3  give the result 12.
The clean ,   cls    commands clear the results.

Yes, more flexible than GUI and it is more related to real life communication.

These are the commands I included in the calculators vocabulary.
SumDifferenceProductQuoetientClear
adddifferenceproductquotientclear
additiondiffproddivclean
plusminusmultiplydivisionempty
+-*/cls
clrscr

You can see the code here:
calc.html 


<html>
<body>
<table>
<tr><td colspan="2" align="center"><h3>HCI Calculator</h3></td></tr>
<tr>
<td valign="top">
Enter command
</td>
<td>
<textarea cols="50" rows="10" id="command"></textarea>
</td>
</tr>
<tr>
<td>&nbsp;</td>
<td  align="center">
<input type="button" value="Calculate" onclick="evaluateComm();"/>
</td>
</tr>
<tr>
<td>&nbsp;</td>
</tr>
<tr>
<td>
Result
</td>
<td>
<input type="text" id="result"/>
</td>
</tr>
</table>
<script type="text/javascript">
var verb=Array();
verb[0]=Array('sum','add','addition','plus','+');
verb[1]=Array('difference','diff','minus','-');
verb[2]=Array('product','prod','multiply','*');
verb[3]=Array('quotient','div','division','/');
verb[4]=Array('clear','clean','empty','cls','clrscr');



function evaluateComm()
{
var command=new String(document.getElementById('command').value);
if(command=='') return;
var comm=Array();
var i,flag=0,op_index=0;

command=command.replace('+',' plus ');
command=command.replace('-',' minus ');
command=command.replace('*',' prod ');
command=command.replace('/',' div ');

comm=command.trim().split(/\s+/);
for(i=0;i<comm.length;i++)
{
res=analyseOne(comm[i]);
if(res>=0)
{
flag=1;
op_index=i;
break;
}
}
if(flag==1)
{
if(res!=4&&comm.length<3)
{
alert('Two operands and one operator required!!!!');
return;
}
var op=getOtherOperand(op_index);
var output;
switch(res)
{
case 0:
output=Number(comm[op[0]])+Number(comm[op[1]]);
break;
case 1:
output=Number(comm[op[0]])-Number(comm[op[1]]);
break;
case 2:
output=Number(comm[op[0]])*Number(comm[op[1]]);
break;
case 3:
output=Number(comm[op[0]])/Number(comm[op[1]]);
break;
case 4:
document.getElementById('result').value='';
document.getElementById('command').value='';
return;
break;
}
document.getElementById('result').value=output;
}
else
{
alert('Command does not match my occabulary.Please check spellings');
return;
}
}
function getOtherOperand(res)
{
var arr=Array();
switch(res)
{
case 0:
arr=Array(1,2);
break;
case 1:
arr=Array(0,2);
break;
case 2:
arr=Array(0,1);
break;
}
return arr;
}

function analyseOne(str)
{
if(str=='') return -1;
var i,j,flag=0,fflag=0;
for(i=0;i<verb.length;i++)
{
for(j=0;j<verb[i].length;j++)
{
if(verb[i][j]==str.toLowerCase())
{
flag=1;
break;
}
}
if(flag==1){ fflag=1;break;}
}
if(fflag==1)
return i;
else
return -1;
}
</script>
</body>
</html>

Hope that you enjoy this code.More stuff on artificial intelligence and HCI is coming soon.Keep reading....

Sunday, 8 September 2013

Encode form elements for ajax submit

Hi friends,
Today my description is about submit form elements through ajax.Submit form through javascript can done using submit() method .
But when  try to submit a form through ajax we need to provide the name of elements and its value as data parameter in jquery $.ajax();

We can done this like
var data='';
data+='name='+$('#name').val()+'&age='+$('#age').val();


But we can use jquery serialize() method we can do this all stuff in single step,like this:
var data=$('#frm').serialize();


Example:

<form id="frm">
<input type="text" name="name"/>
<input type="text" name="age"/>
<input type="button" onclick="submitFrm();"/>
</form>

<script type="text/javascript">
function submitFrm()
{
var data=$('#frm').serialize();
$.ajax({
url:'action.php',
data:data,
type:'post',
datatype:'html',
success:function(){
alert('success...');
},
error:function(){
alert('error...');
}
});
}
</script>


That is we can use serialize() to easy ajax form submit.
If we want to add some additional parameters  existing outside of the form,
add them easily by using '&' like this.
var data=$('#frm').serialize();
data+='&teacher_name='+$('#teach_name').val();

Thank you.

Tuesday, 24 July 2012

Chat application using a database table in PHP

This article is to describe a simple chat application in php or web chat application.
When think about how to create chat application in php  we can understand that. each user accessing
the webpage get a separate instance of the webpage and there have no direct
connection between two users using the same page at the same time.So we can use
a sql database to communicate with two users.

   Online chat application in php means a chat application using ajax or in othe words
 a jquery chat application.

           Before go through the source code you can see a sample screen shot here
 Please open this same page in another tab or another browser to test the chat application.
For reduce  complexity I am not using a user login.You can simply login to chat by using your name or nick
name without any log up process.


Enter your name like Xwe , Yrt , Zty  in the From text box.You can see the online users in the right column.Click one of the
names , you can see a chat box is opened.You can write messages in it and send to the selected user.


You can download the complete zip file fromthis link:-
http://sukeshbr.freeiz.com/blog_works/openchat/openchat.zip
Here is the source code for chat application in php
 Here have two files index.php and back.php
 code
 index.php
 <html>
    <head>
       
    </head>
    <body>
        <table width="100%" height="100%" border="1" align="center" valign="center">
            <tr><td colspan="2" height="6%"><h3>Chat Window</h3></td></tr>
            <tr><td colspan="2" height="6%"> From(Your Name or Id):&nbsp;&nbsp;<input type="text" name="sender" id="sender"><br></td></tr>
            <tr><td width='85%'>
                    <div id="chat_view" >
      
       &nbsp;
                    </div>
                </td>
                <td>
                    <div id="users" name="users">Online Users</div>
                </td>
            </tr>
        </table>
        <div id="chat_list"></div>
        <style type="text/css">
            .chat_box{
border-style:solid;
border-width:medium;
width:200px;
height:300px;
float:left;

}
#msg{
width:200px;
height:200px;
overflow:auto;
}
#new_msg_text
{
width:200px;
height:50px;
}
#close_button{
width:20px;
height:20px;
}
.user_list{

}
        </style>
       
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                window.setInterval(function() {
                   viewMsg();
                   viewOnlineUsers();
                   createNewChatBox();
                   
                },1000);
            });
           
            function creatNewBox(receiver)
            {
            var newbox ="<div class='chat_box' id='chat_box_"+receiver+"'>"+
            "<div id='chat_header'><input type='text' name='receiver[]' READONLY value='"+
            receiver+"' id='receiver'><img id='close_button' src='images/close_button.jpg' alt='X' onclick='closeWindow($(this))'/></div>"+
            "<div  height='20%' id='msg' >"+
                "<br><br><br></div>"+
             "<div id='newmsg'><textarea rows='4' cols='10' id='new_msg_text'>&nbsp;</textarea></div>"+
             "<input type='button' id='btn' onclick='saveMsg($(this))'>"+
        "</div>";
       
        return newbox;
            }
           
            function createNewChatBox()
            {
             var sender=$("#sender").val();
    $("#chat_list").load('back.php?opt=get_chat&sender='+sender);
    $("input[name='chat_users[]']").each(function(){
   
viewBox($(this).val());
});
            }
            function viewBox(receiver)
            {
                if($.trim($("#sender").val())==$.trim(receiver))
                return;
               $(document).ready(function(){
               var flag=false;
              $("input[name='receiver[]']").each(function(){
             
if($(this).val()==receiver)
{flag=true;}
});
        if(flag==false)$("#chat_view").append(creatNewBox(receiver));          
               });
            }
           
            function viewOnlineUsers()
            {
                var sender=$("#sender").val();
                $("#users").load('back.php?opt=view_users&sender='+sender);
               
            }
            function closeWindow(obj)
            {
            obj.parent().parent().remove();
            }
           
            function viewMsg()
            {
                var sender=$("#sender").val();
$("input[name='receiver[]']").each(function(){
var receiver=$(this).val();
$("#chat_box_"+receiver).find("#msg").load('back.php?opt=view_msg&sender='+sender+"&receiver="+receiver);
});
}
         
        function saveMsg(obj)
        {
            var receiver=obj.parent().find("#receiver").val();
                          
            var sender=$("#sender").val();
            var msg=obj.parent().find("#new_msg_text").val();
           
           $.ajax({
           type: 'POST',
           url: 'back.php?opt=save',
           data: {"receiver":receiver,"sender":sender,"msg":msg},
           success: function(){
              
           alert("success");
           }
          
           });
        }
        </script>
       
    </body>
</html>


back.php
<?php



extract($_POST);
extract($_GET);
$con = mysql_connect('localhost', 'root', '');
mysql_select_db('sukesh');
switch ($opt) {
    case "save":
        $query = "INSERT INTO chat (sender,receiver,msg,time) values('" . $sender . "','" . $receiver . "','" . $msg . "',NOW()" . ")";
        mysql_query($query, $con) or die("Error...");

        break;

    case "view_msg":
       
        $query = "SELECT * FROM chat WHERE receiver='" . $sender. "' AND sender='".$receiver."'";
       
        $r = mysql_query($query, $con) or die("Error...");
        while ($row = mysql_fetch_array($r)) {
            echo "<table><tr>";
            echo "<td>".$row['msg']."</td>";

            echo "</tr></table>";
        }
        break;
       
        case "get_chat":
        $query = "SELECT DISTINCT  sender from chat ".
        "  WHERE receiver='$sender' AND AddTime(time, '00:00:15')>=NOW()";
        echo $query ;
           $r = mysql_query($query, $con) or die("Error...3");
        while ($row = mysql_fetch_array($r)) {
       
        echo "<input type='text' name='chat_users[]' value='".$row['sender']."'>";
        }
        break;
        case "view_users":
            $query = "SELECT count(*) as count FROM users WHERE user_id='".$sender."'";
            $r=mysql_query($query, $con) or die("Error...1");
            $row = mysql_fetch_array($r);
            if($row['count']>0)
                $query = "UPDATE users SET last_visit=NOW() WHERE user_id='".$sender."'";
                else
            $query = "INSERT INTO users (user_id,last_visit) values('".$sender."',NOW())";
             
            mysql_query($query, $con) or die("Error...2");
       
            $query = "SELECT * FROM users WHERE AddTime(last_visit, '00:00:15')>=NOW()";
           
     
        $r = mysql_query($query, $con) or die("Error...3");
        while ($row = mysql_fetch_array($r)) {
            echo "<table><tr>";
       
            echo "<td><a onclick=\"viewBox('".$row['user_id']."')\">".$row['user_id']."</a></td>";

            echo "</tr></table>";
        }
            break;
}
?>


Here I am using two Mysql tables namely chat and users
chat








users






The query to make this tables
chat
CREATE TABLE IF NOT EXISTS `chat` (
  `sender` varchar(255) DEFAULT NULL,
  `receiver` varchar(255) DEFAULT NULL,
  `msg` text,
  `time` datetime DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

users
CREATE TABLE IF NOT EXISTS `users` (
  `user_id` varchar(255) NOT NULL,
  `last_visit` datetime NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;


You can also read :-
Simple Game Using Jquery

Monday, 25 June 2012

Simple Game Using Jquery

This article is to discuss about online game programming.In other words  how to make a game
in  html . Nothing to think further the option is jquery.
    There are any jquery games examples are available in internet.But here I am
introducing a free online ball game coded in jquery.This is padd and ball game.The padd
move with mouse movement.We may save the ball from fall to the ground.I think
this is a simple jquery game.

You can see the working of game which I named Hit Ball before go through this
jquery game source code.


 
You can download the source code from here
http://sukeshbr.byethost3.com/Blog_Works/hit_ball/hit_ball.zip


Here have two html files g1.html and end.html.

Code

g1.html
<html>
<head>
<style type="text/css">
*{    margin: 0;
    padding: 0}
#bar{
position:absolute;
left:200px;
width:130px;
height:20px;

}
#ball{
position:absolute;
left:270px;
width:20px;
height:20px;
}
#plain{
width:97%;
height:95%;
border:10px solid #000000;
background:#ccffff;
}

#block_red1{
position:absolute;
top:100px;
left:50px;
width:50px;
height:25px;
}
#block_blue1{
position:absolute;
top:100px;
left:100px;
width:50px;
height:25px;
}
#block_red2{
position:absolute;
top:100px;
left:150px;
width:50px;
height:25px;
}
#block_pink1{
position:absolute;
top:100px;
left:200px;
width:50px;
height:25px;
}
#block_blue2{
position:absolute;
top:100px;
left:250px;
width:50px;
height:25px;
}
#block_pink2{
position:absolute;
top:100px;
left:300px;
width:50px;
height:25px;
}


</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#bar").css("top", window.innerHeight-80);
$("#ball").css("top", window.innerHeight-100);
var click_stat=false;
//Code to move bar
$(document).mousemove(function(m){
$("#body").css('cursor', 'none');
if(m.pageX>10&&m.pageX<window.innerWidth-180)
{
$("#bar").css({"left":m.pageX});
if(click_stat==false)
$("#ball").css({"left":m.pageX+70});
}
});


window.setInterval(function() {
if(click_stat==true){
var p = $("#ball");
var position = p.position();
var status=getStatus();
if(status==1)
{
var tadd=getTAdd();
var ladd=getLAdd();
$("#ball").css({"top":position.top+tadd,"left":position.left+ladd});
}
else if(status==0)
{
alert("Game Over...");
location.href="end.html";
}
else if(status==2)
{
alert("You Won...");
location.href="end.html";
}
}
},40);


//code to detect initial click
$(document).click(function(){

$("#plain").css('cursor', 'none');
click_stat=true;

});
});

function getLAdd()
{
var ladd=0;
var pball = $("#ball");
var pbar = $("#bar");
var bar_position = pbar.position();
var ball_position = pball.position();

if(ball_position.top>=window.innerHeight-100)
{
if(ball_position.left-10>=bar_position.left && ball_position.left-10<=bar_position.left+100 )
 {ladd=-2; }
 if(ball_position.left+10<=bar_position.left+200  && ball_position.left+10>=bar_position.left+100 )
 {ladd=2; }

}

if(ladd==0){ladd=getLAdd.ladd;}
if(ball_position.left<=15|| ball_position.left>=window.innerWidth-40)
ladd=-ladd;

getLAdd.ladd=ladd;
return ladd;
}

function getTAdd()
{
var tadd=0;
var pball = $("#ball");
var pbar = $("#bar");
var ball_position = pball.position();
var bar_position = pbar.position();
if(ball_position.top>=0 && ball_position.top<=11) tadd=5;
if(ball_position.top>=window.innerHeight-100) tadd=-5;
if(ball_position.top>75&&ball_position.top<125)
{

if(($("#block_red1").length>0) && (ball_position.left+20>50&&ball_position.left<100))
{
tadd=-(getTAdd.tadd);
$("#block_red1").remove();
}

if(($("#block_blue1").length>0) && (ball_position.left+20>100&&ball_position.left<150))
{
tadd=-(getTAdd.tadd);
$("#block_blue1").remove();
}
if(($("#block_red2").length>0) && (ball_position.left+20>150&&ball_position.left<200))
{
tadd=-(getTAdd.tadd);
$("#block_red2").remove();
}
if(($("#block_pink1").length>0) && (ball_position.left+20>200&&ball_position.left<250))
{
tadd=-(getTAdd.tadd);
$("#block_pink1").remove();
}
if(($("#block_blue2").length>0) && (ball_position.left+20>250&&ball_position.left<300))
{
tadd=-(getTAdd.tadd);
$("#block_blue2").remove();
}
if(($("#block_pink2").length>0) && (ball_position.left+20>300&&ball_position.left<350))
{
tadd=-(getTAdd.tadd);
$("#block_pink2").remove();
}
}
if(tadd==0){tadd=getTAdd.tadd;}
getTAdd.tadd=tadd;
return tadd;
}

function getStatus()
{
var stat;
var pball = $("#ball");
var pbar = $("#bar");
var bar_position = pbar.position();
var ball_position = pball.position();
if(ball_position.top>=bar_position.top-20)
{
if(ball_position.left+22>=bar_position.left && ball_position.left<=bar_position.left+200)
stat=1;
else
stat=0;
}
else stat=1;
if(stat!=0&&($("#block_blue1").length==0)&&($("#block_blue2").length==0)
&&($("#block_red1").length==0)&&($("#block_red2").length==0)
&&($("#block_pink1").length==0)&&($("#block_pink2").length==0))
stat=2;
return stat;
}
</script>

</head>
<body>
<div id="plain"  >
<img id="block_red1" src="images/block_red.png">
<img id="block_blue1" src="images/block_blue.png">
<img id="block_red2" src="images/block_red.png">
<img id="block_pink1" src="images/block_pink.png">
<img id="block_blue2" src="images/block_blue.png">
<img id="block_pink2" src="images/block_pink.png">

<label id="name"><h3>Hit_ball By Sukesh B R</h3></label>
<img id="bar"  src="images/bar.png">
<img id="ball"  src="images/ball.png">
</div>
</body>
</html>


end.html
<html>
<body>
<h1>Game Completed...</h1>
<br>
<a href="g1.html">Restart</a>
</body>
</html>

Code description

 Let we start from g1.html.   In the body section I placed two images namely bar and ball .
 The images for this is in the image folder which can be download from above.You can see another
 four images.They are the bricks placed above the  bar.

   In the css section , there are the code to position correctly the bricks , padd and ball.


  In the jquery section  in the mousemove event the code to move the padd is written.m is
the mouse object m.pageX gives the x cordinate of mouse pointer m.pageY  gives the y cordinte of
mouse position.      Here we change only the left property of bar image with m.pageX. 
We wont change the y cordinate.Because we need to move the padd in horizontal direction
only.


  window.setInterval()  is  another event used to execute a particular block iteratively
  in a particular time interval.in this function  getTAdd()  is called to get the   tadd which is added to the y position of the ball.
  getLAdd() is called to get the ladd which is added to the x position of the ball.
 
  The variable status returned from getStatus() determine that the game is active or
  game over or win in the game.
 
 
 In the functions getTAdd(),getLAdd() and getStatus() the ladd , tadd and staus   is calculated
by analysing the position of ball and padd.  If the ball is hit the left half of padd the ladd   will be +2.


If the ball is hit the right half of padd the ladd will be -2.  If the ball position come   near to the walls the ladd is multiplied with -1. Thus the ladd change to opposite value.  This will gives a good flow to ball.

  In the top when come near to the top wall or bricks the tadd is multiplied with minus.
  So the ball then move to downward  direction.When ball come near to a brick this the
  brick will be removed using remove() method.
 
  This is only a brief description.Hope that you can understand the core.

You can also read :-

Play wav file using HTML

Very simple Menu using Jquery Beginners Tutorial

 

Thursday, 14 June 2012

Very simple Menu using Jquery Beginners Tutorial

This  article is to teach how to create drop down menu  in html.I am not going to design a
graphical pull down menu.  Instead I am trying to reveal the basic construction of pull down
menu.

  When creating menus using jquery only the hiding and pop up of menu is handled by jquery. The
actual layout is created using  css. Creating drop down menus in css means align a <ul> and
it's child <ul> using css,because the pull down menu is constructed using a <ul>.So code for
creating menu in html includes css and jquery.

You can see a demo of resultant menu here




Code


<html>
<head>

<style type="text/css">

*{    margin: 0;
    padding: 0}
    #menu{
        z-index:5;
    }
a{
text-decoration:none;
}
    #menu li
    {    float: left;
        list-style: none;
   
        }

    #menu li a
    {    display: block;
        }



        #menu li ul
        {
            position: absolute;
            display: none;

            }

        #menu li ul li
        {    float: none;
            display: inline
            }

</style>


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#menu > li").mouseenter(function(){
$(this).find('ul').css('display', 'inline');
});

$("#menu > li").mouseleave(function(){
$(this).find('ul').css('display', 'none');
});
});
</script>
</head>


<body>
<ul id="menu">
<li><a>Menu1</a>
<ul>
<li><a href="http://www.facebook.com">Facebook</a></li>
<li><a href="http://www.google.com">Google</a></li>
<li><a href="http://newprograminglogics.blogspot.com">My Blog</a></li>
</ul>
</li>
<li>
<a href="#">Menu2</a>
<ul>
<li><a href="http://www.gmail.com">GMail</a></li>
<li><a href="http://www.twitter.com">Twitter</a></li>
</ul>
</li>
</ul><br>

</body>
</html>



Code description
                      The pull down menu is actually a  <ul>  that is unordered list. Here in the <body>
section I have placed a <ul>   with id="menu".    As seen in the demo above in this page,
here have two menus namely Menu1 and Menu2.

      This Menu1 and Menu2 are  links(<a>) placed in  <li> of <ul> with id="menu".  Besides this link
there have another <ul> in each <li>.  The  menu items are placed in the <li> of this child <ul>.

        This <ul> without applying  css  is displayed just like a list.   But using some simple css
commands we can convert it into a menu form.

*{    margin: 0;
    padding: 0}
This code is for remove margin and padding from all elements.



#menu{
        z-index:5;
    }

Is used to place the menu above all elements in page.   




a{
text-decoration:none;
}
Is use to remove the under line from links.



In the code segment :-
#menu li
    {    float: left;
        list-style: none;
   
        }
       
        float : left   place the li of ul side by side.In default it is from top to bottom,  that is vertically.       
        list-style: none removes the dots (.) from the front of each item.
       
       
       
        #menu li a
    {    display: block;
        }
       
        Is for display each item as a block.

       
       
        #menu li ul
        {
            position: absolute;
            display: none;


            }
            Here position: absolute is for place the menu items exactly  below  menu heading
            irrespect  of other elements in the page.
            display: none is for hide this contents initially.The menu items will be displayed only
            after mouse entered in menu heading.
           
           
       
        #menu li ul li
        {    float: none;
            display: inline
            }
           
            Here float: none is for remove the float to left property of child <ul>'s <li>, which is
            set in #menu li   by{    float: left}


Because here that does not require because the menu items should be displayed in  vertical manner.
display: inline set the menu items vertically.
   
   
   
                The alignment of menu is over.Now we go through the jquery  section which displays and hide
    the menu items.
   
    $("#menu > li").mouseenter(function(){
$(this).find('ul').css('display', 'inline');
});

      This code will display the child ul,that is our menu items.The parent <ul>s <li>s
mouseenter event is defined with setting child <ul>'s display property to inline.Note
that this is set to display:none initially in the css section.$(this).find(ul)
will get the child element.  .css() is a jquery library function used to change css
property of certain elements.
   
     One more thing  remain is  that we need to hide the menu item again when mouse   is come out from the menu items.        That is done by this code
     
$("#menu > li").mouseleave(function(){
$(this).find('ul').css('display', 'none');
});
});
     This is just like above code. mouseleave   event is used to detect the disappearence of mouse
pointer.      $(this).find('ul')    will give the child <ul> then display : none is used
to hide the menu items.

Thus our simple menu is begin to work.

You can also read :-

Simple Game Using Jquery
Facebook like pop up window using jquery
Introducing AJAX with a simple example program

Sunday, 3 June 2012

Delete non empty directory in php

This article is to discuss how can delete any folder in php.Delete a directory in php is done by
the method rmdir().  But it work only if the directory is empty.That is it can delete empty directories only.   


            In php delete non empty directory is done by first delete contents of folder.
That is delete all files in a folder.Then delete the empty directory using rmdir().

This code will  describe how can php remove non empty directory.   

CODE

<?php
    del('new');

        function del($dir)
         {
            $result=array_diff(scandir($dir),array('.','..'));
             foreach($result as $item)
               {

     if(!@unlink($dir.'/'.$item))
    del($dir.'/'.$item);

                }
        rmdir($dir);
           }

?>



        Here I have defined a function with name del().   It has one parameter which is the  name of the directory to be delete.Here my directory name is 'new'.


        In the   del()    function defenition   $result=array_diff(scandir($dir),array('.','..'));
scandir()   is used to get the name of all files and folders in the directory provided.
array_diff(..,array('.','..'))   is used to remove the default '.' and '..' folders.  Then the remaining array is parsed using  a  foreach  loop.


        First assume the item is a file.So delete it using unlink().  If unlink() returns false  the item will be a directory.  So del()   function is called in  recursive manner with the sub folder name ($item).

 
        After the loop has executed rmdir($dir) will call.Now rmdir() can delete the directory
because the directory will be empty.   Hence delete directory with php is done.  

You can also read :-
Extend maximum execution time of php script

Thursday, 24 May 2012

Facebook like pop up window using jquery

This article is discussing pop up window using jquery or popup box using jquery.
Some of you are looking for a code for pop up window in html.     But jquery is the better solution to not only create simple pop up window but also more complicated popup windows.To
modal popup using jquery we use some essential css  too.

Try this :-


code
<html>
<head>
   <style type="text/css">
   #divid
   {
   z-index:5;
   position:absolute;
   width:400px;
   left:200px;
   top:150px;
   border:8px solid #a1a1a1;
   padding:0px 0px;
   background:#FFFFFD;
   border-radius:15px;
  }
  #headid
  {
  background:#6692CD;
  color:#ffffff;
  font-size:18px;
  }
  #shareid
  {
  background-color:#6692CD;
  color:#ffffff;
  font-size:15px;
  }
  </style>

 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function(){
$("#linkid").mouseenter(function(){
if(!$("#divid").length)
{
$("#bodyid").append("<div id='divid'>"+
"<table width='100%'><tr><td id='headid'>Share this Photo</td></tr>"+
"<tr><td><br><img src='http://mystifyingindia.com/blog/wp-content"+
"/uploads/2010/09/taj_mahal.jpg' width='60' height='50'>"+
"&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspHere come the body of the message..."+
"<br><br></td></tr>"+
"<tr><td align='right'><input type='button' value='Share Photo' id='shareid'>"+
"<input type='button' value='Cancel' onclick='btn_cancel()'></td></tr>"+
"</table></div>"
);
$("#divid").css({"left":window.innerWidth/2-200,"top":window.innerHeight/2-100});
}
});



}

);
</script>
<script type="text/javascript">
function btn_cancel()
{

$("#divid").remove();
}
</script>
</head>

<body id="bodyid">
   <div style='width:290px'>
<a id="linkid"><h3>Mouse over it to see popup window</h3></a>
    </div>


</body>
</html>


Here is the sample screenshot :-

















Here I am actully dynamically include a <div>  with id 'divid' when mouse is move over the text
'Mouse over it to see popup window'.  $("#bodyid").append("<div id='divid'>")   is
used to append the <div> to the body of html  page.

The contents in the pop up box is placed in this div. The css to this div is placed in the css section.
The border-radius property set  the <div> a rounded rectangle .
position:absolue set the pop up box exactly where the top and left is given even if some
elements are also present there.

The top and left positions are calculated just like this
"left":window.innerWidth/2-200 , "top":window.innerHeight/2-100.
window.innerWidth returns the width of browser window.Subtracting 200 from its half
gives the center position of window, because 400 is the predefined width of pop up box.
top position is also calculated just like this.

$("#divid").length returns the number of elements with the id 'divid'.if(!$("#divid").length)
is used to ensure the pop up box is not create when one is existing.

Finally $("#divid").remove() is used to permenently remove the newly added pop up box
from the dom.This is given in the onclick event of cancel button in the pop up box.

You can also read:-
Open a new browser window using javascript

Introducing AJAX with a simple example program 

Very simple Menu using Jquery Beginners Tutorial

Search This Blog