skip to main | skip to sidebar

Tuesday, September 28, 2010

Tooltip Component Using Java Script & CSS

A simple, small Java Script Component, which you can use to have custom Tooltips on your web page. Well why wait, let get right on to it. First lets see the styles used by the Tooltip popup box.
.toolTipDef, .toolTip { 
            position: absolute; 
            background-color: #ccc; 
            border: 1px solid #000; 
            padding: 3px; 
.toolTipDef { display: none; }
.toolTip { display: block; }
All together we’ve to CSS classes, one ‘toolTipDef’ and ‘toolTip’. ‘toolTipDef’ is used when the tooltip need to be hidden, and when user mouse over the text, we’ll use ‘toolTip’ class to make the tooltip popup visible. These styles set standard attributes like background color for the tooltip popup, its border and text padding inside tooltip popup. ‘toolTipDef’ set the ‘display’ property to ‘none’ so that by default the popup is hidden and ‘toolTip’ sets the ‘display’ property to ‘block’ so that when used the tooltip popup gets displayed.
To display tooltip text, we need a container to be used as popup with the given text for this we need to add the below given empty ‘div’ tag to the HTML page.
<div id="toolTip" class="toolTipDef"></div>
If you observe, the default CSS style class used for this ‘div’ is ‘toolTipDef’ which makes this ‘div’ hidden by default. We need to give some value for the ‘id’ attribute of this container div, so that we can access it using the java script and change its content and CSS styles. Here its given as ‘toolTip’, this value will be used while initializing Tooltip Java Script Component.
The last and core part of this component is the Java Script, lets see what we’ve here.
(function() {
    Tooltip = {
        init: function(elId) {
            if (!elId)
            var el = document.getElementById(elId);
            this.el = el;             this.isIE = document.all? true : false;         }, // End of init()
        showTip: function(anchor, text) {             this.el.innerHTML = text;             this.el.className = "toolTip";
            var pos = this.getElPosition(anchor);
  ['left'] = pos.x + "px";   ['top'] = (pos.y + anchor.offsetHeight - 1) + "px";         }, // End of showTip()
        hideTip: function (anchor) {             this.el.className = "toolTipDef";         }, // End of hideTip()
        getElPosition: function(anchor) {             for(var zx=zy=0; anchor!=null; zx+=anchor.offsetLeft,zy+=anchor.offsetTop,anchor=anchor.offsetParent);             return {x:zx,y:zy}         } // End of getElPosition()     } // End of Tooltip })();
This ‘Tooltip’ Java Script class has 4 methods init, ‘init()’, ‘showTip()’, ‘hideTip()’, and ‘getElPoistion()’. The ‘init()’ method initializes the component, it takes the ‘id’ attribute value of the tooltip popup container ‘div’ element. In this example we’ve given it as ‘toolTip’ as mentioned in the above HTML code. This ‘init()’ method checks the given value, if its not provided returns immediately, otherwise it tries to get the DOM reference of this element. If it fails to get the DOM reference, it returns with out giving any error, otherwise keeps this reference in ‘el’ object of this component.
The ‘getElPosition()’ method is used to get the position of the element on the screen for which the tooltip is being displayed, it takes the element as parameter and uses ‘offsetLeft’, ‘offsetTop’, and ‘offsetParent’ attribute values to give the top, left positions of the given element.
The ‘showTip()’ method is used to display the tool tip popup when user, mouse over an element. This method takes the element and the tool tip text as parameters. It sets the ‘innerHTML’ of the popup container ‘div’ with the given text, and sets the CSS class name of the container ‘div’ to ‘toolTip’ which makes it visible. Then it tries to get the position of the given element by calling ‘getElPosition()’ method, and changes the ‘top’ and ‘left’ CSS style attributes with the values returned by the ‘getElPosition()’ method.
The last method ‘hideTip()’, is used to hide the tool tip popup when user, mouse out from an element. This method takes the element for which the tooltip was displayed. This method simply changes the CSS class name of the given element to ‘toolTipDef’ which hides the tool tip container ‘div’.
The last step is to initialize this component on window ‘onload’ event. You can use the sample code given below OR have your own way of doing it.
window.onload = function () { Tooltip.init('toolTip'); };
Only thing you need to make sure is, the parameter to the ‘init()’ method, it should be the ‘id’ attribute value of the popup container ‘div’.
To show tool tip for a HTML element you call the ‘showTip()’ and ‘hideTip()’ method on ‘mouseover’ and ‘mouseout’ events. Sample code on how to do it is given below
<h2 onmouseover="Tooltip.showTip(this, 'This is a Sample Tooltip');"
    onmouseout="Tooltip.hideTip(this);">Move your mouse on to me!!!</h2>
That is all you need to do, Simple isn’t it!

Monday, September 13, 2010

Ant Script To Sign A JAR File

To sign a JAR file you need a ‘keystore” first. You can create a sample keystore using the following simple command.
keytool -genkey -keystore <> -alias <aliasname>
After creating the keystore, you can add the following Ant tag to sign the JAR file using it.
<signjar jar="<JAR file to be signed>" alias="<Keystore Alias Name>" 
                keystore="<>" storepass="<Keystore password>"/>
Attributes used are
  • jar – The JAR file path which needs to be signed.
  • alias – Keystore alias name, given in the ‘keytool’ command to create the keystore.
  • keystore – Path to the keystore file, which was created using the ‘keytool’ command.
  • storepass – Keystore password used while creating the keystore using ‘keytool’ command.

Monday, September 6, 2010

Ajax Form Submit GET/POST Methods

This example explains GET and POST methods of form submit using AJAX. Only code is posted for now, will try to update it later some time. Complete example can be downloaded using the link at the end of the post.
package com.rakesh.ex.dto; 
public class EmployeeDTO {     private String empId;     private String name, email;     private String designation, department;
    public EmployeeDTO(String empId) {         this.empId = empId;     }
    public String getEmpId() {         return empId;     }
    public void setEmpId(String empId) {         this.empId = empId;     }
    public String getName() {         return name;     }
    public void setName(String name) { = name;     }
    public String getEmail() {         return email;     }
    public void setEmail(String email) { = email;     }
    public String getDesignation() {         return designation;     }
    public void setDesignation(String designation) {         this.designation = designation;     }
    public String getDepartment() {         return department;     }
    public void setDepartment(String department) {         this.department = department;     } }

package com.rakesh.ex.dao; 
import java.util.ArrayList; import java.util.List;
import com.rakesh.ex.dto.EmployeeDTO;
public class EmployeeDAO {
    /**      * sample method to get list of employees. This method creates sample list      * of employees data.      */     public List<EmployeeDTO> getEmployees() {         List<EmployeeDTO> empList = new ArrayList<EmployeeDTO>();         for (int i=1; i<=10; i++)             empList.add(createSampleData(i, i%2));         return empList;     }
    private static EmployeeDTO createSampleData(int i, int j) {         EmployeeDTO emp = new EmployeeDTO(String.valueOf(1000 + i));         emp.setName("Employee" + i);         emp.setEmail(emp.getName() + "");         emp.setDesignation("Designation" + i);         emp.setDepartment("Department" + j);         return emp;     }
    /**      * create dummy employee information. You can replace this method to query the      * database for actual employee information in your implementation.      */     public EmployeeDTO getEmployeeInfo(String empCode) {         EmployeeDTO emp = new EmployeeDTO(empCode);         emp.setName("Employee-" + empCode);         emp.setEmail(emp.getName() + "");         emp.setDesignation("Designation" + empCode);         emp.setDepartment("Department" + empCode);         return emp;     } }

package com.rakesh.ex.web; 
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import com.rakesh.ex.dao.EmployeeDAO; import com.rakesh.ex.dto.EmployeeDTO;

public class AjaxExample extends HttpServlet {     private static final long serialVersionUID = -6377586508833712244L;
    private EmployeeDAO empDAO;
    @Override     public void destroy() {         super.destroy();         this.empDAO = null;     }
    @Override     public void init() throws ServletException {         super.init();         this.empDAO = new EmployeeDAO();     }
    @Override     protected void doGet(HttpServletRequest req, HttpServletResponse resp)             throws ServletException, IOException {         doPost(req, resp);     }
    @Override     protected void doPost(HttpServletRequest req, HttpServletResponse resp)             throws ServletException, IOException {         final String empCode = req.getParameter("empCode");         // get employee info         EmployeeDTO empInfo = empDAO.getEmployeeInfo(empCode);         // set employee list in to request         req.setAttribute("emp_info", empInfo);
        // forward to jsp which generates table out of employee list         req.getRequestDispatcher("emp_info.jsp").forward(req, resp);         return;     }

<%@page import="java.util.List" %>
<%@page import="com.rakesh.ex.dto.EmployeeDTO" %>
    EmployeeDTO empInfo = (EmployeeDTO) request.getAttribute("emp_info");
    if (empInfo == null) {
    <p>Could not find employee information!</p>
<%    } else { %>
    <div class="data">Employee ID: <%=empInfo.getEmpId()%></div>
    <div class="data">Name        : <%=empInfo.getName()%></div>
    <div class="data">Email        : <%=empInfo.getEmail()%></div>
    <div class="data">Designation: <%=empInfo.getDesignation()%></div>
    <div class="data">Department    : <%=empInfo.getDepartment()%></div>
<% } %>

(function() {
    AjaxEx = {
        init: function(url, elId) {
            if (!url || !elId) {
                alert("Invalid input!");
            this.url = url;
            var el = document.getElementById(elId);
            if (!el) {
                alert("Container Element, to place Ajax response doesn't exists!");
            this.el = el;
            this.sampleHtml = "<p>This will be replaced with AJAX response!</p>";
            // create xml http request object for AJAX requests
            this.xmlHttp = this.initXmlHttp();
        }, // End of init()
        initXmlHttp : function () {
            if (window.XMLHttpRequest)
                // Firefox, Opera, IE7, etc.
                return new XMLHttpRequest();
            if (window.ActiveXObject)
                // IE6, IE5
                return new ActiveXObject("Microsoft.XMLHTTP");
        }, // End of initXmlHttp()
        resetContent : function () {
            this.el.innerHTML = this.sampleHtml;
        }, // End of resetContent()
        sendAjaxRequest : function () {
            // initialize XML Http object if not available
            if (!this.xmlHttp)
                this.xmlHttp = this.initXmlHttp();
            if (this.xmlHttp) {
                var ajaxObj = this;
                this.xmlHttp.onreadystatechange = function() {
                    if (ajaxObj.xmlHttp.readyState==4 && ajaxObj.xmlHttp.status==200) {
                        // 4 = "loaded", 200 = "OK"
                        ajaxObj.el.innerHTML = ajaxObj.xmlHttp.responseText;
                var selBox = document.getElementById("empCode");
                // prepare parameters
                var empCode = selBox.options[selBox.selectedIndex].value;
                if (empCode == "") {
                    alert("Please select employee code to get employee information!");
                var params = "empCode=" + empCode;
                // for multiple parameters separate them by '&' as given below
                // var params = "empCode=E1001&dept=TestDept"
                // this.makeGETRequest(params);
            } else
                alert("Your browser does not support AJAX.");
        }, // End of sendAjaxRequest() 
        makePOSTRequest : function (params) {   "POST", this.url, true);             //Send the proper header information along with the request             this.xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");             this.xmlHttp.setRequestHeader("Content-length", params.length);             this.xmlHttp.setRequestHeader("Connection", "close");             this.xmlHttp.send(params);         }, // End of makePOSTRequest()
        makeGETRequest : function (params) {   "GET", this.url + "?" + params, true);             this.xmlHttp.send(null);         } // End of makeGETRequest()
    } // End of AjaxEx })();

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="" xml:lang="en" lang="en">
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> 
    <title>Simple Ajax Example</title>
    <script type="text/javascript" src="js/ajax-example.js"></script>     <style type="text/css">         body {             width: 800px;             height: 600px;         }         .top_block {             text-align: center;         }         .top_block input {             font-weight: bold;         }         .ajax_content {             border: 2px solid #000;             padding: 2em;         }         .data { margin-bottom: 0.5em; }     </style> </head> <body>     <div class="top_block">        Select Employee Code: <select id="empCode" name="empCode">             <option value="">Select</option>             <option value="E1001">E1001</option>             <option value="E1002">E1002</option>             <option value="E1003">E1003</option>             <option value="E1004">E1004</option>             <option value="E1005">E1005</option>             <option value="E1006">E1006</option>             <option value="E1007">E1007</option>         </select>         <input type="button" onclick="javascript:AjaxEx.sendAjaxRequest();" value="Get Data"/>&nbsp;&nbsp;         <input type="button" onclick="javascript:AjaxEx.resetContent();" value="Reset Content"/>     </div>     <div id="ajax_content" class="ajax_content">         <p>This will be replaced with AJAX response!</p>     </div>     <script type="text/javascript">     <!--         // view source of this page after it loads in browser         // and check this variables value         var url = "<%=request.getContextPath()%>/ajaxServlet";         AjaxEx.init(url, "ajax_content");     // -->     </script> </body> </html>

Download the Source code.