Archive

Archive for the ‘JQuery’ Category

Adding JQuery Slider Part II

October 9th, 2009 No comments

In my last post I showed how to easily add slider functionality using JQuery. In this post I will showcase some of the options that slider provides with a Temperature Converter. This is how it will work: the slider represents temperature measured in Celsius units and ranges between 0 and 100. As the user drags the slider, we will display the temperature equivalent in Fahrenheit.

Lets start by registering a basic slider:

   <script type="text/javascript">
	$(function()
	{
		$("#slider").slider();
	});
   </script>

Since the slider converts temperatures in the range 0 celsius and 100 celsius, modify the slider definition to include the range:

	$("#slider").slider({
		min: 0,
		max: 100,
		step: 1
		
	});

The next step is to add two span tags to display the chosen temperature and the temperature in Fahrenheit:

	Temperature in Celsius: <span id="celsius">0</span>
	
Temperature in Fahrenheit: <span id="fahrenheit"></span>

Finally all we need to do would be to captrue the slide event so that we can update the span tags:

	$("#slider").slider({
		min: 0,
		max: 100,
		step: 1,
		slide: handleSlide
	});

The handleSlide is a javascript function that looks like this:

	function handleSlide(event, ui)
	{
		// Update the celsius span
		$("#celsius").html(ui.value);

		// Compute the fahrenheit equivalent
		var fTemp = (1.8 * ui.value) + 32;

		// Just display the last two digits of the temp
		$("#fahrenheit").html(fTemp.toFixed(2));
	}	

Here is a working demo

Categories: JQuery, Solutions Log Tags:

Adding JQuery UI Slider

October 1st, 2009 No comments

Here are five easy steps to add slider functionality to your web applications:

Step 1: Go to JQuery UI site and create a custom download. To keep things simple, select “No Theme”.under theme section and deselect all but UI Core and Slider checkboxes. Hit Download and unzip the downloaded file.

Step 2: Copy the jquery-1.3.2.min.js and “jquery-ui-1.7.2.custom.min.js” files into your project. These files should be under the js folder. Include the js files in your html/jsp page.

  
	
	
      

Step 3: Add the following styles to the page:

		
	

I am using the slider bar and slider handle images from YUI

Step 4: Add a DIV for the slider in the HTML.

		

Step 5: Initialize the slider in the document ready function:

	
      

That’s it. You can find a demo of this example here.

Basic JQuery Tips

September 22nd, 2009 No comments

This is more for my reference and hopefully helps others working with JQuery.

  1. Getting and Setting the innerHTML of an element

    	
    		var content = $("#id").html();
    		$("#id").html("Some HTML");		
       
  2. Getting and Setting the text (with out any HTML) of an element

    		
    		var txt = $("#id").text();			
    		$("#id").text("Some Text");		
    	
  3. Removing content from an element

    		
    		$("#id").empty();		
    	
  4. Getting and Setting style properties

    			
    		var displayValue = $("#id").css("display");
    		
    		$("#id").css("display", "block");
    	
  5. Hiding and Displaying elements

    	
    		// Toggles an element's visibility
    		$("#id").toggle();
    				
    		$("#id").hide();
    		
    		// Sets the display style property to block and not inline
    		$("#id").show();		
    	
  6. Registering to events such as keyup

    		$("#id").keyup(function(){
    			alert($(this).val());
    		});
    	
  7. Dealing with CSS classes

    		// Adds the specified class to the element
    		$("#id").addClass("showme");
    		
    		// Multiple classes should be separated by spaces
    		$("#id").addClass("showme1 showme2");
    				
    		// Removes the specified class
    		$("#id").removeClass("hideme");
    		
    		// Multiple classes should be separated by spaces
    		$("#id").removeClass("hideme1 hideme2");
    		
    		// Removes all the classes
    		$("#id").removeClass();
    	
  8. Getting and Setting values of form elements

    		// For input boxes
    		$("#inputbox").val(); // Returns the text box value
    		$("#inputbox").val("set some value");
    		
    		// For select boxes
    		$("#selectbox").val(); // Returns the selected value 
    		// To get the text of the selected option
    		$("#selectbox :selected").text();
    		
    		// Programatically selects a value or multiple values
    		$("#singleselect").val("123");
    		$("#multipleselect").val(["12", "234"]);
    
    		// For checkboxes and radio buttons
    		$("#chkId").val();  // Returns value whether the check box is checked or not
    		// Returns true when the check box is checked
    		$("#chkId").attr("checked"); 		
    		
    		// Programatically checks the check box
    		$("#chkId").attr("checked", "checked"); 	
    	
Categories: JQuery, Uncategorized Tags:

Unobtrusive JavaScript using JQuery

March 7th, 2009 No comments

I feel that an important advantage of using JQuery is its ability to separate behavior from structure. Consider the case where you want to trigger a JavaScript method when a link is clicked. A common implementation would be:



Click Me

Even though this mixing of behavior (JavaScript) and structure (HTML) looks straight forward, it can become a maintenance issue in large projects. This is where JQuery shines. Using JQuery, the above code can be rewritten in a cleaner way:



Click Me

Now, consider a slightly trickier case where context specific parameters need to be passed to the JavaScript method:



Click Me 1
Click Me 2
Click Me 3
Click Me 4
Click Me 5

Here is the refactored version using JQuery:



Click Me 1
Click Me 2
Click Me 3
Click Me 4
Click Me 5
Categories: JQuery, Uncategorized Tags:

JQuery – Five useful tips

March 7th, 2009 2 comments
  1. Selectors
    Before an element can be manipulated using JQuery, it needs to be identified. JQuery provides a powerful syntax for selecting a one or more elements. Here are some simple selectors (notice similarity to CSS element selection):

    • Selecting by id: $(‘#yourelementid’)
    • Selecting by class name: $(‘.yourclassname’)
    • Selecting by tag name: $(‘p’) selects all the

      elements in the page

    Other useful selectors:

    • div > a will select all the links present directly inside a div tag
    • tag[attribute=value] will select all the elements of type tag with the given attribute name and value. For example input[type=’text’] will select all the text tags
    • :checkbox, :radio, :file are shortcuts to select checkboxes, radio buttons and file elements.
    • :hidden selects all the elements that are hidden (such as head and base tags). This DOES NOT select all the form hidden fields.
  2. Reading and Modifying attribute values
    Once a element is selected, its value can be read and modified using attr method, Here are examples:

    • $(‘base’).attr(“href”) reads the href attribute of the base tag
    • $(“#formTextId”).attr(“value”, ‘Test Value’);
  3. Document ready handler
    The document ready handler provides a convenient location to place all the document’s initialization code. JQuery executes this handler right after the browser finishes converting HTML into DOM tree. Here is the syntax for handler:

    $(document).ready(function() {
       // Your code
    });
    

    A shortcut syntax for this:

     $(function() {
          // Your code
     });
    

    It is possible to chain the several handlers and JQuery will execute them in the order in which they are declared.

  4. live() method
    JQuery’s live() method binds a handler to an event for current and future matched elements. This is extremely useful when elements are loaded dynamically (using AJAX for example) and need to have their behavior controlled by JQuery. For example the following code will display a “Print” window when a link of class printLink is clicked.

     $(".printLink").live("click", function(){
    	window.print();
    	return false;	
    });
    

    A JQuery plugin called Live Query provides a similar but more robust functionality

  5. load() method
    Provides a simple and convenient way to inject html content into an element (or set of elements) using Ajax. For example the following code injects html code of a

    element with id ‘paragraphId’ inside test.html page into div with id ‘someDivId’.
    $(‘#someDivId’).load(‘/test.html #paragraphId’);

Categories: JQuery, Uncategorized Tags:

JQuery – Clearing hidden fields

March 6th, 2009 No comments

JQuery’s form plugin provides several convenient methods for clearing/resetting form element values. However, the clearForm method does not reset hidden fields. Here is a simple implementation for clearing hidden fields:

jQuery.fn.clearHiddenFields = function() {
	return this.each(function(){
		$("input[type='hidden']", this).each(function(){
			this.value = '';
		});
	});		
};

Invoking this method is very straightforward:

$("#yourformid").clearHiddenFields();

or simply:

$("form").clearHiddenFields();
Categories: JQuery, Uncategorized Tags: