Scrolling Menu using Jquery


Hi Guys..

In this post I want to share a method of how you can implement scrollable Menu on HTML page using
Jquery.
The steps to implement scrollable Menu are as follows: Demo is available here

1. Include the Jquery Library:

<script src="jquery-1.3.2.min.js" type="text/javascript"></script>

2. Now, lets start with the menu which we want to be scrollable:

Let’s assign id as “scrollable-menu” to the menu:(The menu will be as under)

<div id="scrollable-menu">
<ul>
<li>Home</li>
<li>Pictures</li>
<li>Contact Me</li>
</ul>
</div>

3. Next is we start write the script code using jquery to implement the scroll:
Jquery has a function to handle the event scroll.

// This is the scroll event handler
$(window).scroll(function() {
//Write the action on scroll event here.
});

4. Lets get down on the action of moving the menu as we perform the action of scrolling:

$(window).scroll(function(){
$("#scrollable-menu")
.animate({"marginTop": ($(window).scrollTop()) + "px"}, "slow" );
});

Explanation:
$(window).scroll –> this is the function for scroll event for Window.
This event occurs whenever you scroll the window on browser and this
function will get executed.

$(“#scrollable-menu”) –> this is the selector which gets you the instance of DOM object
with id scrollable-menu and as we want to scroll the menu we are using its id

.animate is the function provided by jquery to perform custom animations on
object using CSS properties.

$(window).scrollTop() –> this is the function which provides us the numerical figure
of the amount of scroll performed on window
Ans using this value we are setting the margin-top value of Menu so, that it is
seen in the visible area of the page.
“slow” is the parameter of animate function to enable the animation on screen,
you can also use any numerical value in place of slow(it is in milli seconds)
More about animate function – here
More about scrollTop Function – here

5. Because this event can fire many times in a row we need to make sure we stop all previous repositions before progressing with the latest one. Imagine a users scrolls 3-4 times really fast. We want just the last call to be in control of the repositioning. Ensuring that all repositioning is stopped beforehand makes for much faster handling of the event, resulting in smoother animation. We call this BEFORE the code snippet above.

$(window).scroll(function(){
$("#scrollable-menu")
.stop()
.animate({"marginTop": ($(window).scrollTop()) + "px"}, "slow" );
});

6. One more way we can make the code smoother is storing the instance for the object that needs to be accessed
for every scroll event. Whenever the scroll event fires jQuery traverses the DOM looking for our element. In order to alleviate this overhead we can simply store the jQuery reference to our element in a variable when the DOM is initialised and reference this instead.

var $scrollableMenu = $("#scrollable-menu");

$(window).scroll(function(){
$scrollableMenu
.stop()
.animate({"marginTop": ($(window).scrollTop() + 30) + "px"}, "slow" );
});

7. The final Code will be as follows:

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script>
$().ready(function() {
var $scrollableMenu = $("#scrollable-menu");

$(window).scroll(function(){
$scrollableMenu
.stop()
.animate({"marginTop": ($(window).scrollTop() + 30) + "px"}, "slow" );
});
});
</script>

Thats all.. Jquery makes all simple.. 🙂 😀

JSONP… and why JSONP


How to start.. ?

I am working on Ajax and I need to get some data, that is using XML.

If I am working on domain, lets say  mysite.com and I need to get some data using xml

from the same domain,  where the xml url is mysite.com/myxml.xml , So here you can direct

get the xml from this specific domain using HttpRequest.

But, what if you want data from some other domain, may be  othersite.com/.

So, here XML will not be of an use, as XML httpRequest works only for the same domain

i.e. the requester and the responder are the same domains.

So, you may say lets use JSON. But, here JSON is also of no use.

As, JSON is just a formatting of data for (similar to XML)XML.

But it is also of no use for Cross Domain data Access.

What is JSON:  JSON is Java Script Object Notaion. It is a lightweight data-interchange format.

The JSON filename extension is .json.

JSON is an alternative to XML and it is more easy to access than XML.

So if XML is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<contacts>
    <contact id="1">
        <name>Anu Zamwar</name>
        <phone>123-456-7890</phone>
        <address>
            <street>123 JFKStreet</street>
            <city>Any Town</city>
            <state>Any State</state>
            <zipCode>12345</zipCode>
        </address>
    </contact>
</contacts>

So, JSON for this XML will be as:

{
   "contacts" : {
      "contact" : {
         "@attributes" : {
            "id" : "1"
         },
         "name" : "Anu Zamwar",
         "phone" : "123-456-7890",
         "address" : {
            "street" : "123 JFK Street",
            "city" : "Any Town",
            "state" : "Any State",
            "zipCode" : "12345"
         }
      }
   }
}

So, now let me get back to the point, how to overcome the problem of Cross Domain Data Access.

JSONP is a means by which to get JSON data from another

domain than the one your page is on.

If you try and use Ajax to request data from a different

domain than the page, you’ll get a security error.

One way around this is a concept some call “JSONP”.

This is where you include a script tag in your document. This script

tag points to an external javascript source and when the

script tag loads it executes (like any other script tag).

The catch is that you need to be able to tell that server what

to wrap the data with so your functions can handle it.

Let’s say we are on this page at clientcide.com.

Let’s say we want to get some data from the flicker api at flicker.com/services/api.

Here’s a simple request that gets the latest photos:

http://www.flickr.com/services/feeds/photos_public.gne?format=json

To Overcome this problem of Cross Domain Data Access, JSONP comes into picture. What is JSONP?

I asked this to Google and he gave me few answers as always. You can also get some from googly..

So, whats the difference between JSON and JSONP. Both are same, except the difference that in JSONP,

you also include a call back function name. So, when u need to get the data of this JSONP using AJAX,

you need to tell AJAx the name of the call back Function defined in JSONP file.

How will the above JSON look when written as JSONP:

func({
   "contacts" : {
      "contact" : {
           "@attributes" : {
                 "id" : "1"
            },
         "name" : "Anu Zamwar",
         "phone" : "123-456-7890",
         "address" : {
            "street" : "123 JFK Street",
            "city" : "Any Town",
            "state" : "Any State",
            "zipCode" : "12345"
         }
      }
   }
});

⇒ func is the Callback function, used in the above JSONP file.
Now let this above JSONP file name be myjsonp.json

and it is under domain → http://www.othersdomain.com/myjsonp.json

And you domain is http://www.mydomain.com/

I am using Jquery.ajax to show the working with JSONP. Code is as follows:

$.ajax({
url: "http://www.othersdomain.com/myjsonp.json", //URL of JSONP File
dataType: "jsonp",  // Data type is JSONP
processData: false, // No need to process Data, we use it as JSONP
jsonpCallback: "func",  // Callback function
success: function(data,textStatus,obj) {
var name = data.contacts.contact.name;
alert("Name is: " + name);

} });

So, here it is the use of JSONP to over come the problem of Cross Domain Requests..

🙂

JDBC with mySQL


The purpose of this Post is to get you beyond the initial hurdles involved in:

  • Use mySQL database for use with JDBC.
  • Writing and testing your first JDBC programs to administer the database and to manipulate the data stored in the MySQL database.

* What is JDBC:

JDBC technology is an API (included in both J2SE and J2EE) that provides cross-DBMS connectivity to a wide range of SQL databases and access to other tabular data sources, such as spreadsheets or flat files.

*  Connecting Java and mySQL

For Connecting Java and mySQL database you will need a Connector called “MySQL Connector/J” :

Download the Connector

What is MySQL Connector/J?

For those who don’t know, let me begin by explaining the purpose of MySQL Connector/J.

The JDBC API is designed to make it possible for you to write a single Java program and to use it to manipulate the data in a variety of different SQL database servers without a requirement to modify and/or recompile the program.  In order to do this, it is necessary for you to:

  • Inform the Java program as to the URL of the database server.  You can accomplish this with input data when you start the program.
  • Provide the Java program with a programming interface to the specific database server that you intend to use.  Assuming that the programming interface has been installed on your computer, you can also accomplish this with input data when you run the program.
Installing MySQL Connector/J :  First Extract the Connector/J downloaded archive.

It consists of many files. The file which is most imp for us is the jar file. May be named as:   “mysql-connector-java-5.1.12-bin.jar”

5.1.12 is the version, can be different for you. Depends on the version of Connector you download.

Now to install the Connector you will have 2 methods:

1. The following statement appears in the connector documentation Section 2.2.1. entitled Setting the CLASSPATH

copy the “com” and “org” subdirectories and all of their contents to anywhere you like, and put the directory holding the “com” and “org” subdirectories in your classpath

2. Second Method:

put mysql-connector-java-[version]-bin.jar in your classpath, either by adding the FULL path to it to your CLASSPATH environment variable, or by copying the .jar file to $JAVA_HOME/jre/lib/ext.

I will like to tell you the best method that worked for me and which is most uncomplicated is: Copy the downloaded Connector .jar file into /java/jre/lib/ext    folder. This easier rather typing commands or setting the classpath for different .jar files you need to run you program.

Note:  bfore running java programs on Windows Command prompt just do the following 2 steps and you can run the program from any directoy.

  • set path= “path of jdk/bin folder”    (without quotes) the path may be like(for Windows users)

C:\Program Files\Java\jdk1.5.0_14\bin

  • set classpath=%classpath%;.;

3. Lets check the connectivity using the Java Code:

Consider here the following things in the code:

  • database_name= The database you have made in mySQL you have to use
  • Database_password= Password of “root” in mySQL, you are using mySQL database as a ‘root’
  • The table you are using is “person” which has columns “name” and “age”
  • In the following code you take the name of person as command-line argument and use it to run the query
  • The command line argument is name of person you have in your database 🙂
  • Steps to run the following java code:
  • Save the following code and name the file as “example.java”
  • Run command on command prompt (Compile the code):    javac example.java
  • Execute the compiled File (Hope there are no Errors):  java example argument  (for example:    java example aniket      )


//Import Packages

import java.sql.*;
import java.lang.*;
public class example{
Connection con = null;
Statement smnt;
ResultSet rs;
String querystring;
public static void main(String[] args){
try{
final String DRIVER,DATABASE,USER,PASS;
DRIVER="com.mysql.jdbc.Driver";
DATABASE="jdbc:mysql:///database_name";
USER="root";
PASS="Database_password";

Class.forName(DRIVER).newInstance();
con = DriverManager.getConnection(DATABASE,USER,PASS);
if(!con.isClosed()){
System.out.println("MySQL server connected...");
smnt= con.createStatement();
querystring= "select age from person where name=\"" + args[0] + "\"";
rs = smnt.executeQuery(querystring);
if(rs.next()){
System.out.println("The age is" + rs.getString("age"));
}
rs.close();
con.close();
}
}//try Block Ends here
catch(Exception e) {System.err.println("Exception: " + e.getMessage());}
}//main ends here
}//class Ends

So the code is as above..
Here the post ends.. Hope this works for you..
While writing this post, I considered that you have Java(JDK) and mySQL configured on your computer.
Else this will not work for you.
Cheers… 🙂