how to create a jquery plugin

As promised , here is how you create a plugin in jQuery. No sweat and blood, relax and follow.. 🙂

Let us create a simple “jquery circle plugin”.

create a div in you index page, this is our div element which animates later as a circle!.

<div id="circular" class="_default_circle">&nbsp;plugin</div>

The important one’s,  the CSS:

._default_circle{ 
  width:50px;
  height:50px;
  background:#00FFFF;
  border:#0000FF solid 1px; text-align:center;
}

._custom_circle{
  width:50px;
  height:50px;
  background:#00FFFF;
  border:#0000FF solid 5px;
  text-align:center; top:50%;
  -webkit-border-radius: 999px;
  -moz-border-radius: 999px;
  border-radius: 999px;
  behavior: url(PIE.htc);
}

 

The ._default_circle is used for the div on initial load, the ._custom_circle is used when you actually access the div through your plugin.

Jquery plugin structure explained!

We can initiate the actual function of plugin using the jQuery built-in structure

(function($){....... })(jQuery);Next, make sure that your plugin name is as simple as possible, because , the main advantage of using plugin is to get work done fast, so don’t let your plugin users think for hours to get the function name right.

Ok , having said that , you can create your plugin function within extended JQ function like this, well i am going to call it as circle itself!, so our first plugin function is circle , so you can call your plugin as $('#divname').circle();

That’s it!.. pretty cool ha?

Now, for the creation of function

inside the extended function write something like this

$.fn.circle = function() {        
  this.animate({width : 100, height: 100} ,1000);
  this.addClass("_custom_circle");
}

Remember, “this” is already an object, so , its not necessary for you to call $(this) within the function.

ok , here is what we are doing.. we are increasing the width and height of the circle along with different css appended to it , also, with an animation delay of 1000sec.

Alright,  here is the overall jQuery plugin code:

$(document).ready(function(){
  //initialize the Jquery plugin
  $("#circular").circle();                          
});
                          
(function($){
  $.fn.circle = function() {
    this.animate({width : 100, height: 100} ,1000);
    this.addClass("_custom_circle");
  };        
})(jQuery);

save this script as circle.jquery.js and include in your index page.

That’s it!!! comments are welcome!! 🙂

how it looks:

 

Please subscribe for more cool codes 🙂

how to create a jquery plugin with options

Check out the previous tutorial on how to create a simple jquery plugin.

Now lets learn a bit jquery plugin tutorial with some advance skill. Lets see how to build the same circle plugin with customizable parameters.

jQuery plugin with customization parameters

create a div in you index page, this is our div element which animates later as a circle!.

<div id="circular" class="_default_circle">&nbsp;plugin</div>

The important one is the CSS:

._default_circle{
  width:50px;
  height:50px;
  background:#00FFFF;
  border:#0000FF solid 1px; text-align:center;	    
}

._custom_circle{
  width:50px;
  height:50px;
  background:#00FFFF;
  border:#0000FF solid 5px;
  text-align:center; top:50%;
  -webkit-border-radius: 999px;
  -moz-border-radius: 999px;
  border-radius: 999px;
  behavior: url(PIE.htc);	
}

The ._default_circle is used for the div on initial load, the ._custom_circle is used when you actually access the div through your plugin.

jQuery plugin with options structure explained!

We can initiate the actual function of plugin using the jQuery built-in structure.

(function($){....... })(jQuery);

We will use the jQuery “extend” function to have options for the plugin.

Ok, first we need to decide on how to give options to the plugin, because if you provide more options to the user , more likely is he going to like your plugin. Also, remember that complexity kills the performance, so have a balanced plugin. In this tut, i have three options included ; animation speed, height and width of circle.

Now, how to initialize jquery plugin:

$.fn.extend({........ }); same way as you would initialize document ready…but, with different syntax.

call the circle function within the extend function

circle: function() {... } , if you are passing default values then use circle: function(options) {... }

within circle function let us set our default functions like this

var defaults = {
  anim_speed : 100,
  width: 100,
  height : 100,
};

set the default values if the user does not set any in his function call.

var choice = $.extend(defaults, options);

The $.extend api will merge the contents of two or more objects together into the first object , more info jquery.extend()

So for every option we will overwrite the default values in the plugin like this:

return this.each(function() {
  var curr = $(this);
  curr.animate({width : choice.width, height: choice.height} ,choice.anim_speed);
  curr.addClass("_custom_circle");
});

For every option we will animate with default values or with the values user has set.

A user will call your plugin like this  $("#circular").circle();

In this case , the default variable that you had set earlier will be used in the function.

Since you have given the options, user can call their plugin with options like this:

$("#circular").circle({
  anim_speed : 1000,
  width : 200,
  height: 200
});

Wow congratulation! you did it..

Here is overall code for JQuery Plugin Defaults and Options :

$(document).ready(function(){
  $("#circular").circle(
  { anim_speed : 1000, width : 200, height: 200 } 
  );
});  
(function($){
  $.fn.extend({
    circle: function(options) {
      var defaults = {
        anim_speed : 100,
        width: 100,
        height : 100,
      };
      var choice = $.extend(defaults, options);
      return this.each(function() {
        var curr = $(this);
        curr.animate({width : choice.width, height: choice.height} ,choice.anim_speed);
        curr.addClass("_custom_circle");
      });
    }
  });
})(jQuery);

Please subscribe for more cool codes 🙂

PHP script to read outlook email inbox

Here is a simple php code to read outlook email inbox. This code also contains php script to read a outlook inbox mail received from a particular email address.

Please note that the following is achieved through PHP IMAP PROTOCOL
Also, this is not a very secured method of doing it. The idea here is to reveal the concept.

<?php
  error_reporting(E_ALL ^ (E_NOTICE | E_WARNING));
  
  $incoming_mail_server = 'imap.gmail.com'; 
  //This is an example incoming mail server for gmail which you can configure to your outlook, check out the manual on Supported IMAP client list
  
  $your_email = '[email protected]'; // your outlook email ID
  $yourpassword = 'xyz' // your outlook email password
  
  $mbox   = imap_open("{$incoming_mail_server}", $your_email , $yourpassword )   or  die("can't connect: " . imap_last_error());
  $num = imap_num_msg($mbox); // read total messages in email
  $MC = imap_check($mbox);
  $msg=array();
  // Fetch an overview for all messages in INBOX
  $result = imap_fetch_overview($mbox,"$num:{$MC->Nmsgs}",0);
  foreach ($result as $overview) {
    echo 'Message no'.$overview->msgno. '<br/>';
         "{$overview->subject}<br/>";
           $check = imap_mailboxmsginfo($mbox);
      
       echo $check->Unread;
       
        echo $overview->subject;
        echo $overview->body;
        
    //code to check and display email received from a particular Email address
        if(preg_match("/[email protected]/",$overview->from,$match)){
              $msg[$overview->msgno]=$overview->subject;
              imap_delete($mbox,$overview->msgno);
        }
        else{
              imap_delete($mbox,$overview->msgno);
        }
  }
       imap_close($mbox); 
  
?>

Supported IMAP client list

Subscribe for more cool codes 😉

Simple script in PHP to drag and drop jQuery UI and store result in MySQL

Hello !

I was thinking, how much would drag and drop UI of jQuery help the people in pure designing aspect?, well… found out – not much!, until you use it with powerful scripting language, whats better then PHP ?.
Secondly, I thought if you can use PHP why not database to store it?. Behold!! here is the simple script to drag and drop the UI and store result in MySQL along with the help of PHP.

Include jquery library
Include jquery UI widget library, especially interactions.

Before we start , I would recommend you to learn this basic Drag & drop tutorial

Basic CSS to style our drag and drop UI

.content_box { 
  padding:5px; 
  width:300px; 
  float:left;
  height:250px; 
  border:#00FFFF solid 1px; 
  font-family:Verdana, Arial, Helvetica, sans-serif;
  margin:10px;
  overflow:auto;
  color:#999999;
  font-size:14px;
}

.content_holder_box{ width:300px;
  float:right;
  height: 250px;
  border:#0099FF solid 1px;
  padding:10px;
  margin:10px;
  color:#999999;
  font-size:14px;
}

.content_holder_box:hover{ 
  border:#0099FF solid 1px; 
}


.dragelement{ 
  padding:5px; 
  margin:3px; 
  width:270px; 
  border:#99FF66 solid 1px;
  background-color:#E2FFC6;
  cursor:move;
  color:#000;
  font-size:13px;
}

.dropper{ width:270px;
  height:125px;
  margin:10px;
  
}

.dropper_hover{ 
  border:#999999 dashed 1px; 
  background:url(../images/darrow.jpg) center no-repeat;
}

//you can show arrow image to suggest where user has to drop selected UI.

Create index.php and write a simple drag environment , i have created a static one, you can create a dynamic drag environment, for example shopping cart elements from database.

<div class="content_box" id="content_box_drag" onMouseOver="drag();"> Drag label
<?php
for($i=0; $i<5;$i++)
{
    echo "<p class='dragelement' id='dragelement_$i'>Ferrari_$i</p>";
}
?>
</div>
<div class="content_holder_box" id="content_box_drop">Drop here
<p class="dropper"></p>
</div>
<div style="clear:both;"></div>
<br/><br/>
<div id="search_result"></div>
  • id “content_box_drag” is a static draggable environment.
  • initialize drag() function on mouse hover , to prepare the drag UI.
  • create few drag elements from php (static).
  • create a drop box “content_box_drop” , so that users can drop the dragged element into it for selection.
  • create a <p> tag so that we can append the drag element to it.  (you can use any!)
  • use a div to show the result , here “search_result”.

javascript to create a drag and drop function and store the result in MySQL

//initialize the drag and drop functions.
function drag() {

$("#content_box_drag p").draggable({
    appendTo: "body",
    helper: "clone",
    revert: "invalid"

    //add comma to previous last line & uncomment this if u want to remove the dropped item
    /*stop: function(){$(this).remove();}*/

});

$("#content_box_drop p").droppable({
    activeClass: "dropper_hover",
    hoverClass: "dropper_hover",
    accept: ":not(.ui-sortable-helper)",
    drop: function (event, ui) {
        var ele = ui.draggable.text();
        $.ajax({
            url: "store.php",
            type: "POST",
            data: {
                element: ele
            },
            beforeSend: function () {
                $('#search_result').html("<center><br/><h4>Loading.....</h4></center>");
            },
            success: function (data) {
                $("#search_result").html(data);
            }
        });
    }
});

}

Please note that the idea of this tutorial is to show you how to create things in a simple and understandable way. It does not focus on security and authenticity etc..

Check out the other cool code links 🙂

Hope it was helpful , as it was for me , Subscription and Comments are appreciated!!

jquery ui draggable DEMO:

[sociallocker]

https://www.infoandapps.com/demo/simple-script-in-php-to-drag-and-drop-jquery-ui-and-store-result-in-mysql/

[/sociallocker]

simple tooltip in Jquery

Hi,

In this post, i have attempted to create my own jquery code to show the tooltip on mouseover event.
The coding goes like this:

CREATE A DIV ELEMENT:

<div class="tooltip" id="toolt" style="display: none;"></div>

create a div element and name the ID as “toolt”(not necessarily same name) and initially hide the division by giving style=”display:none;” option

CSS FOR THE ELEMENT:

.tooltip{
  border:1px dashed #0000FF;
  padding-left:10px;
  padding:5px;
  width:100px;
  background-color:#CCFFFF;
  position:absolute;
  opacity:0.9;
  font-family:Geneva;
  font-weight:bold;
  -moz-box-shadow: 0 0 13px #888;
  -webkit-box-shadow: 0 0 13px #888;
  box-shadow: 0 0 13px #888;
  -moz-border-radius:3px;
}

Note that i have called the css through .tooltip class in the division which is supposed to be used for tooltip on hover.
Also, note that i have cracked the mozilla firefox to create round edge effect .Also, i would give a different design in IE.

JQUERY TO SHOW TOOLTIP:

function show(id,txt){
    $(id).mouseover(function(e){
    var offsetsLeft = $(window).scrollLeft();
    var offsetsTop = $(window).scrollTop();
    leftpos = parseInt(offsetsLeft + (e.pageX)) + 'px';
    toppos = parseFloat(offsetsTop + (e.pageY)) + 'px';
    $('#toolt').css({'top':toppos,'left':leftpos});
    document.getElementById("toolt").innerHTML=txt;
    $('#toolt').show();
});

$(id).mouseout(function(e){
    $('#toolt').hide();
    e.stopPropagation();
});
}

First , we need to pass the parameter to the function “show()”(see below to see how it is initialized), the first parameter should be DOM object type like a,p,span,div etc; the second parameter should be the content that will be displayed in the tooltip.
Next we shall calculate the mousepointer coordinates and call the tooltip division on that particular division.The first part of the function will do that trick.
Later, when mouse is taken off we will hide that division again.

INITIALIZING THE TOOLTIP:

<a href="javascript:void(0);" onmouseover="show('p','This is a tooltip content')">Hover Here</a>

If you need to call a tooltip for the ‘p’ tag, then you can use the above method to initialize the tooltip. Dont forget to pass the DOM object in the first parameter and remember your DOM object will be your first parameter.

Thats it guys, feedback’s are welcome! 🙂