Floating Message Box

We can build a floating message box on fly in the browser depends on the scroll position of the window. This can be done using jquery simple few link code as seen below,

Here in the below code will fly message while on click  in submit button.Create a div tag, that going to become  a message box look on gly in the browser,

<div id=”message_box” ></div>

$(document).ready(function(){ 

$(‘#message_box’).css({visibility:’hidden’});

 $(window).scroll(function()
   {
       temp_sval=$(window).scrollTop();
    }
 );
 $(“.save_btn”).click(function(event){
  $(‘#message_box’).css({visibility:’visible’});
  $(“#message_box”).html(‘Settings Updated Sucessfully’); 
    $(‘#message_box’).animate({top:temp_sval+”px”,opacity:1 },{queue: false, duration: 350}); 
 setTimeout(function(){
  $(‘#message_box’).animate({ top:”+=15px”,opacity:0 }, “slow”);
 },1500);
 });

  
});

Advertisements

Idle Timer

The idle timer is built on jQuery and provides two custom events: idle.idleTimer and active.idleTimer, which fire when the user’s idle state has changed.

This example has an idle timeout of 7 seconds. When you move your mouse over the page or start typing, you’re considered “active”. The status above the textarea changes to indicate your current state.

 

 

 

 

(function($){
  
        $(document).bind(“idle.idleTimer”, function(){
            $(“#status”).html(“User is idle :(“).css(“backgroundColor”, “silver”);
        });
       
        $(document).bind(“active.idleTimer”, function(){
             $(“#status”).html(“User is active :D”).css(“backgroundColor”, “yellow”);
        });
       
        $.idleTimer(7000);
   
   
    })(jQuery);

<div id=”status” style=”padding: 5px;”>&nbsp;</div>

Note:

Running this Idile Timer successfully need to include the jquery.js and idletime.js. You can download the idile timer from this below URL,

http://paulirish.com/demo/js/idle-timer.js

Open All External Links in a New Window

Using Jquery, you can customize the external links of your site will open in a new window by the following format.

$(document).ready(function(){
         $(“a[@href^=’http’]”).attr(‘target’,’_blank’);
});

 Not process links to the same domain, and pdfs can done as follows,

 

 


var host = window.location.host.toLowerCase();
$(“a[@href^=’http’]:not([@href^=’http://&#8221; + host + “‘]):not([@href^=’http://www.&#8221; + host + “‘]), a[@href$=’.pdf’]”).css({outline: ‘solid 1px red’}).attr(“target”, “_blank”);

Scroll window smoothly in jQuery

the animate() function to do a smooth scrolling.

I have also created a div as follow:

<div id=”scrollToHere”>
Scroll to here
</div>

You need something to run your script. Create a button like this:

<input type=”button” onclick=”scollWin();” value=”Scroll up” />
The jQuery Code will be like this:

function scrollWin(){
$(‘html, body’).animate({
scrollTop: $(“#scrollToHere”).offset().top
}, 2000);
}

}

Note:
In order to run this jquery, you need to include the Jquery COre file. It is available in http://docs.jquery.com/Downloading_jQuery

Grid Panel in Jquery

Implementing the Grid Panel with JSON ordered data  with Load once technique done  here with the JQuery jgrid plugin. We can see here dynamically fetching the data on the selected keywords and update the grid with the new list of records.

This post sending keywords is done in the last post, You can refer  the last post to get details on the keywords,

The demo on the Jgrid is available from below link as,

                         http://trirand.com/jqgrid/jqgrid.html

Including the CSS & JS:

<link rel=”stylesheet” type=”text/css” media=”screen” title=”basic” href=”js/themes/basic/grid.css” />
<link rel=”alternate stylesheet” type=”text/css” href=”js/themes/coffee/grid.css” title=”coffee” media=”screen” />

 <script type=”text/javascript” src=”js/jquery-1.3.2.js”></script>
  <script type=”text/javascript” src=”js/jquery.jqGrid.js”></script>

Layout:

<table id=”list3″ class=”scroll” cellpadding=”0″ cellspacing=”0″></table>
<div id=”pager3″ class=”scroll” style=”text-align:center;”></div>

Jquery part:

$(document).ready(function() {

var gridimgpath = ‘js/themes/basic/images’;

   jgrid=jQuery(“#list3”).jqGrid({
  
url:’server.php?q=2&note=’+document.getElementById(‘CityAjax’).value,
   datatype: “json”,
   colNames:[‘Inv No’,’Date’, ‘Client’, ‘Amount’,’Tax’,’Total’,’Notes’],
   colModel:[
      {name:’idd’,index:’idd’, width:60, sorttype:”int”},
      {name:’invdate’,index:’invdate’, width:90, sorttype:”date”},
      {name:’name’,index:’name’, width:100},
      {name:’amount’,index:’amount’, width:80, align:”right”,sorttype:”float”}, {name:’tax’,index:’tax’, width:80, align:”right”,sorttype:”float”},
      {name:’total’,index:’total’, width:80,align:”right”,sorttype:”float”}, {name:’note’,index:’note’, width:150, sortable:false}
     ],
   rowNum:20,
   rowList:[10,20,30],
   imgpath: gridimgpath,
   pager: jQuery(‘#pager3’),
   sortname: ‘idd’,
   viewrecords: true,
   sortorder: “desc”,
   loadonce: true,
   caption: “Load Once”
   });

});

On Updating the Record grid List  by the  typeing the keyword in the input box  done by calling the bleow to update the grid,

var gridimgpath = ‘js/themes/basic/images’;

   jQuery.ajax({
  
url:’server.php?note=’+document.getElementById(‘CityAjax’).value,  
   datatype: “json”,
   complete: function (jsondata,stat){  
     //alert(jsondata.responseText);
     if(stat==”success”){
      var thegrid = jQuery(“#list3”)[0];
      thegrid.addJSONData(eval(“(“+jsondata.responseText+”)”));
     }
      else{
      //alert(“no”);
                    }
               } // end complete
   });   
}

AutoComplete in Jquery

Auto complete search in JQuery possible by including the jquery autocomplete plugin provided by the jquery library. Follow the link below to get the Jquery Autocomplete updated plugin with the examples,

http://dyve.net/jquery/?autocomplete

For running the Jquery autocomplete smoothly we need to include the following js file in the files

<script type=”text/javascript” src=”js/jquery-1.3.2.js”></script>
 <script type=’text/javascript’ src=’js/jquery.autocomplete.js’></script>

The below code will shows the input box with auto complete functionalities,

<p>
  Ajax City Autocomplete:
  <input type=”text” id=”CityAjax” value=”” style=”width: 200px;” />
  <input type=”button” value=”Get Value” onclick=”lookupAjax();” />
 </p>

on typing a keywords in CityAjax table, the autocomplete will fire  with help of following code,

$(document).ready(function() {
 $(“#CityAjax”).autocomplete(
  “autocomplete.php”,
  {
   delay:10,
   minChars:3,
   matchSubset:1,
   matchContains:1,
   cacheLength:10,
   onItemSelect:selectItem,
   onFindValue:findValue,
   formatItem:formatItem,
   autoFill:true,
   maxItemsToShow:10
  }
 );

The Autocomplete.php will give the JSON formated data to the autocompleter list to search auto display the typed keyword like lists. The Auto Search will start after typing minimum 3 characters in the input box.
The properties controlling search auto complete is shown above.

Calling the autocomplete JQuery for the inbut box is,

function lookupAjax(){
 var oSuggest = $(“#CityAjax”)[0].autocompleter;
 oSuggest.findValue();
 return false;
}

JSON Retriver:
The Json Coverter in the autocomplete.php will look like,

error_reporting(0);
include(‘dbconfig.php’);
$q = strtolower($_GET[“q”]);

if (!$q) return;
$query=mysql_query(“select * from invheader”);
$temp_items=array();
$i=0;
while($qdata=mysql_fetch_array($query))
 {
  $temp_items[$qdata[‘note’]].=$qdata[‘note’];
  $i++;
 }
foreach ($temp_items as $key=>$value) {
    if (strpos(strtolower($key), $q) !== false) {
        echo “$key|$value\n”;
   }
}

Jquery Customization

1. Simple slide panel

Let’s start by doing a simple slide panel. You’ve probably seen a lot of this, where you click on a link and a panel slide up/down. (view demo)
When an elment with class=”btn-slide” is clicked, it will slideToggle (up/down) the <div id=”panel”> element and then toggle a CSS class=”active” to the <a class=”btn-slide”> element. The .active class will toggle the background position of the arrow image (by CSS).

$(document).ready(function(){

	$(".btn-slide").click(function(){
	  $("#panel").slideToggle("slow");
	  $(this).toggleClass("active");
	});

});

  2. Simple disappearing effect

This sample will show you how to make something disappear when an image button is clicked.(view demo)

When the <img class=”delete”> is clicked, it will find its parent element

<div class=”pane”> and animate its opacity=hide with slowspeed.

$(document).ready(function(){ 
$(".pane .delete").click(function(){   
            $(this).parents(".pane").animate({ opacity: "hide" }, "slow");
               });
  });

 3 Chain-able transition effects

Now let’s see the power of jQuery’s chainability. With just several lines of code, I can make the box fly around with scaling and fading transition..(view demo)

Line 1: when the <a class=”run”> is clicked
Line 2: animate the <div id=”box”> opacity=0.1, left property until it reaches 400px, with speed 1200 (milliseconds)
Line 3: then opacity=0.4, top=160px, height=20, width=20, with speed “slow”
Line 4: then opacity=1, left=0, height=100, width=100, with speed “slow”
Line 5: then opacity=1, left=0, height=100, width=100, with speed “slow”
Line 6: then top=0, with speed “fast”
Line 7: then slideUp (default speed = “normal”)
Line 8: then slideDown, with speed “slow”
Line 9: return false will prevent the browser jump to the link anchor

$(document).ready(function(){

 $(“.run”).click(function(){

   $(“#box”).animate({opacity: “0.1”, left: “+=400”}, 1200)
   .animate({opacity: “0.4”, top: “+=160”, height: “20”, width: “20”}, “slow”)
   .animate({opacity: “1”, left: “0”, height: “100”, width: “100”}, “slow”)
   .animate({top: “0”}, “fast”)
   .slideUp()
   .slideDown(“slow”)
   return false;

 });

});

4a. Accordion #1

Here is a sample of accordion.

 

The first line will add a CSS class “active” to the first <H3> element within the <div class=”accordion”> (the “active” class will shift the background position of the arrow icon). The second line will hide all the <p> element that is not the first within the <div class=”accordion”>..(view demo)

When the <h3> element is clicked, it will slideToggle the next <p> and slideUp all its siblings, then toggle the class=”active”.

$(document).ready(function(){

 $(“.accordion h3:first”).addClass(“active”);
 $(“.accordion p:not(:first)”).hide();

 $(“.accordion h3”).click(function(){

   $(this).next(“p”).slideToggle(“slow”)
   .siblings(“p:visible”).slideUp(“slow”);
   $(this).toggleClass(“active”);
   $(this).siblings(“h3”).removeClass(“active”);

 });

});

4b. Accordion #2

This example is very similar to accordion#1, but it will let you specify which panel to open as default. ;..(view demo)

In the CSS stylesheet, set .accordion p to display:none. Now suppose you want to open the third panel as default. You can write as $(“.accordion2 p”).eq(2).show(); (eq = equal). Note that the indexing starts at zero.

$(document).ready(function(){

 $(“.accordion2 h3”).eq(2).addClass(“active”);
 $(“.accordion2 p”).eq(2).show();

 $(“.accordion2 h3”).click(function(){
   $(this).next(“p”).slideToggle(“slow”)
   .siblings(“p:visible”).slideUp(“slow”);
   $(this).toggleClass(“active”);
   $(this).siblings(“h3”).removeClass(“active”);
 });

});

5a. Animated hover effect #1

This example will create a nice animated hover effect with fade in/out.;..(view demo)

When the menu link is mouseovered, it will find the next <em> and animate its opacity and top position.

$(document).ready(function(){

 $(“.menu a”).hover(function() {
   $(this).next(“em”).animate({opacity: “show”, top: “-75”}, “slow”);
 }, function() {
   $(this).next(“em”).animate({opacity: “hide”, top: “-85”}, “fast”);
 });

});

5b. Animated hover effect #2

This example will get the menu linktitle attribute, store it in a variable, and then append to the <em> tag.(view demo)

 

The first line will append an empty <em> to the menu <a> element.

When the link is mouseovered, it will get thetitle attribute, store it in a variable “hoverText”, and then set the <em> text content with the hoverText’s value.

$(document).ready(function(){

 $(“.menu2 a”).append(“<em></em>”);

 $(“.menu2 a”).hover(function() {
   $(this).find(“em”).animate({opacity: “show”, top: “-75”}, “slow”);
   var hoverText = $(this).attr(“title”);
   $(this).find(“em”).text(hoverText);
 }, function() {
   $(this).find(“em”).animate({opacity: “hide”, top: “-85”}, “fast”);
 });

});

6. Entire block clickable

This example will show you how to make the entire block element clickable as seen on my Best Web Gallery’s sidebar tabs.(view demo)

Suppose you have a <ul> list with class=”pane-list” and you want to make the nested <li> clickable (entire block). You can assign the click function to “.pane-list li”; and when it is clicked, the function will find the <a> element and redirect the browser location to its href attribute value.

$(document).ready(function(){

 $(“.pane-list li”).click(function(){
   window.location=$(this).find(“a”).attr(“href”); return false;
 });

});

7. Collapsible panels

Let’s combine the techniques from the previous examples and create a serie of collapsible panels (similar to the Gmail inbox panels). Notice I also used the same technique on Web Designer Wall comment list and Next2Friends message inbox?.(view demo)

First line: hide all <div class=”message_body”> after the first one.
Second line: hide all <li> element after the 5th
Third part: when the <p class=”message_head”> is clicked, slideToggle the next <div class=”message_body”>
Fourth part: when the <a class=”collpase_all_message”> button is clicked, slideUp all <div class=”message_body”>
Fifth part: when the <a class=”show_all_message”> is clicked, hide this, show <a class=”show_recent_only”>, and slideDown all <li> after the fifth one.
Sixth part: when the <a class=”show_recent_only”> is clicked, hide this, show <a class=”show_all_message”>, and slideUp all <li> after the 5th.

$(document).ready(function(){

 //hide message_body after the first one
 $(“.message_list .message_body:gt(0)”).hide();

 //hide message li after the 5th
 $(“.message_list li:gt(4)”).hide();

 //toggle message_body
 $(“.message_head”).click(function(){
   $(this).next(“.message_body”).slideToggle(500)
   return false;
 });

 //collapse all messages
 $(“.collpase_all_message”).click(function(){
   $(“.message_body”).slideUp(500)
   return false;
 });

 //show all messages
 $(“.show_all_message”).click(function(){
   $(this).hide()
   $(“.show_recent_only”).show()
   $(“.message_list li:gt(4)”).slideDown()
   return false;
 });

 //show recent messages only
 $(“.show_recent_only”).click(function(){
   $(this).hide()
   $(“.show_all_message”).show()
   $(“.message_list li:gt(4)”).slideUp()
   return false;
 });

});

8. Imitating the WordPress Comment Backend

I think most of you have probably seen the WordPress Ajax comment management backend. Well, let’s imitate it with jQuery. In order to animate the background color, you need include the Color Animations plugin.?(view demo)

First line: will add “alt” class to even <div class=”pane”> (to assign the grey background on every other <div >)
Second part: when <a class=”btn-delete”> is clicked, alert a message, and then animate the backgroundColor and opacity of <div class=”pane”>
Third part: when <a class=”btn-unapprove”> is clicked, first animate the backgroundColor of <div class=”pane”> to yellow, then white, and addClass “spam”
Fourth part: when <a class=”btn-approve”> is clicked, first animate the backgroundColor of <div class=”pane”> to green, then white, and removeClass “spam”
Fifth part: when <a class=”btn-spam”> is clicked, animate the backgroundColor to red and opacity =”hide”

//don’t forget to include the Color Animations plugin
//<script type=”text/javascript” src=”jquery.color.js”></script>

$(document).ready(function(){

 $(“.pane:even”).addClass(“alt”);

 $(“.pane .btn-delete”).click(function(){
   alert(“This comment will be deleted!”);

   $(this).parents(“.pane”).animate({ backgroundColor: “#fbc7c7” }, “fast”)
   .animate({ opacity: “hide” }, “slow”)
   return false;
 });

 $(“.pane .btn-unapprove”).click(function(){
   $(this).parents(“.pane”).animate({ backgroundColor: “#fff568” }, “fast”)
   .animate({ backgroundColor: “#ffffff” }, “slow”)
   .addClass(“spam”)
   return false;
 });

 $(“.pane .btn-approve”).click(function(){
   $(this).parents(“.pane”).animate({ backgroundColor: “#dafda5” }, “fast”)
   .animate({ backgroundColor: “#ffffff” }, “slow”)
   .removeClass(“spam”)
   return false;
 });

 $(“.pane .btn-spam”).click(function(){
   $(this).parents(“.pane”).animate({ backgroundColor: “#fbc7c7” }, “fast”)
   .animate({ opacity: “hide” }, “slow”)
   return false;
 });

});

9. Image replacement gallery

Suppose you have a portfolio where you want to showcase multi images without jumping to another page, you can load the JPG into the target element.(view demo)

First append an empty <em> to H2.

When a link within the <p class=thumbs> is clicked:
– store its href attribute into a variable “largePath”
– store its title attribute into a variable “largeAlt”
– replace the <img id=”largeImg”> scr attribute with the variable “largePath” and replace the alt attribute with the variable “largeAlt”
– Set the em content (within the h2) with the variable largeAlt (plus the brackets)

$(document).ready(function(){

 $(“h2”).append(‘<em></em>’)

 $(“.thumbs a”).click(function(){

   var largePath = $(this).attr(“href”);
   var largeAlt = $(this).attr(“title”);

   $(“#largeImg”).attr({ src: largePath, alt: largeAlt });

   $(“h2 em”).html(” (” + largeAlt + “)”); return false;
 });

});

10. Styling different link types

With most modern browsers, styling the link selector is very easy. For example, to style the link to .pdf file, you can simply use the following CSS rule: a[href $=’.pdf’] { … }. Unfortunately, IE 6 doesn’t support this (this is another reason why we hate IE!). To get around this, you can do it with jQuery..(view demo)

What is JQuery ?

jQuery is an amazing JavaScript library that makes it easy to create wonderful web effects in just a few lines of code

http://docs.jquery.com/Main_Page

How jQuery works?

First you need to download a copy of jQuery and insert it in your html page (preferably within the <head> tag). Then you need to write functions to tell jQuery what to do. The diagram below explains the detail how jQuery work:

How to get the element?

Writing jQuery function is relatively easy (thanks to the wonderful documentation). The key point you have to learn is how to get the exact element that you want to apply the effects.

    * $(“#header”) = get the element with id=”header”
    * $(“h3”) = get all <h3> element
    * $(“div#content .photo”) = get all element with class=”photo” nested in the <div id=”content”>
    * $(“ul li”) = get all <li> element nested in all <ul>
    * $(“ul li:first”) = get only the first <li> element of the <ul>