Combining Multiple attributes in jQuery


Below are some of the code snippets available in jQuery for you to combine your multiple lines of code:

Combining multiple css properties or element attributes:

Statement: Set the width and height attributes for a table with id=mytable
$(“#mytable”).attr({width:’50px’,height:’40px’});

Statement: Set the css properties of width, height, background-color for a div with id=mydiv
$(“#mydiv”).css({width:’50px’,height:’40px’,background-color:’#F2F2F2′});

Combining element multiple selector:

Statement: Set the width, height and background-color css properties for controls with id=mydiv1, mydiv2 and mydiv3

$(“#mydiv1, #mydiv2, #mydiv3”).css({width:’50px’,height:’40px’,background-color:’#F2F2F2′});

Combining attribute selectors:

Statement: Find out those elements with an id attribute, having ‘name’ ending with ‘mydiv’ and the ‘checked’ state being ‘checked’

$(“#mydiv[id][name$=’mydiv’][checked=’checked’]”).val();

Combining attribute selectors with psuedo properties:

Statement: Delete dropdown option values myvalue3, myvalue4 from a dropdown with id=mydiv

$(“#mydiv options:not([value=’myvalue1′][value=’myvalue2′]).remove();
$(“#mydiv options:[value=’myvalue3′],[value=’myvalue4′]”).remove();

Note: The coma separator in the last statement above will perform a repeat operation on the same element which implies that the above statement is a combined version of the below statements:

$(“#mydiv options:[value=’myvalue3′]”).remove();

$(“#mydiv options:[value=’myvalue4′]”).remove();
Setting multiple attributes for an element:

Statement: Create a new anchor tag and set its id, class and redirect url

$(‘</a>’, {
id : ‘myId’,
class : ‘myClass’,
href : ‘mytest.html’
});

Combining Objects in jQuery:

Statement: To combine or merge two objects in jQuery

var parentObject = { property1: false, property2: 5, property3: “foo” };
var options = { property1: true, property3: “bar” };

jQuery.extend(parentObject, options);
//Final values for parentObject { property1: true, property2: 5, property3: “bar” }

Happy Coding!!!

Best Practices for jQuery Developers


Following are some of the best practices that you could follow while working with jQuery:

  • Plugins:
    • Please avoid unnecessary use of plugins
    • If a plugin is being used, respect the authors work and ensure that the plugin file is reused with the license comments intact
    • If you are writing a reusable functionality in the code, always move it into a jQuery plugin format, to be reused across the site
  • Coding:
    • Use jQuery CDN (google or Microsoft or jQuery) as much as possible for script registration, if its fine with clients. To be on the safer side, you could have a fallback code as well:
      <!– Grab Google CDN jQuery. fall back to local if necessary –> 

<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js“></script> 

<script>!window.jQuery && document.write(‘<script src=”js/jquery-1.4.2.min.js”><\/script>’)</script>

  • Avoid unnecessary upgrades of jQuery, unless there are features, which you require or some plugins require. Stick to one version from the beginning. (ex. 1.5.1)
  • Avoid writing event handler attributes (onclick etc.), instead use live or bind methods to attach the respective event handlers.
  • Avoid mixing javascript code with jQuery code.
  • Cache any jQuery selector, if reused in multiple statements.
    Ex. Avoid $(“#x”).val(); $(“#x”).attr(“align”,”right”); Use var $x = $(“#x”); $x.val();$x.attr(“align”,”right”);
  • Ensure that you place ready function in your code. $(document).ready(function(){});
  • Use find method, instead of building a complex jQuery selector.

//Fine in modern browsers, though Sizzle does begin “running”

$(‘#someDiv p.someClass’).hide(); 

// Better for all browsers, and Sizzle never inits. 

$(‘#someDiv’).find(‘p.someClass’).hide(); 

  • Avoid misusing $(this).
    Ex. Use this.id instead of $(this).attr(‘id’)
  • Keep your code safe, by using noConflict() method or by passing jQuery.
    Ex. (function($){})(jQuery); or by wrapping it in a ready method.
  • Avoid declaring new jQuery selectors within foreach, instead declare them outside and reuse it inside the loop.
  • Use $.ajax instead of $.get or $.getJSON, because internally they call $.ajax.
  • Use JSON formats for communications.
  • Ensure that you move your jQuery codes to a separate javascript file, instead of inline scripts.
  • Compress javascript files for better performance.
  • Combine multiple css() calls or attr() calls into one. In case of attributes, you could also pass them as shown below: 
$(‘</a>’, {

    id : ‘myId’, 

    className : ‘myClass’, 

    href : ‘mytest.html’ 

});

  • Debugging:
    • Use Developer Toolbars and Inspectors to debug your code from client side. You do not need to perform deployments and builds to debug your jQuery code(s).
  • jQuery Cheat Sheet:
    • Always keep a jQuery cheat sheet handy with you to know about the list of functions available for you. Download here

Below are some more useful links you could check out:

Some words of caution:

  • $.ajax has issues in making cross domain AJAX calls. As a solution, you can get a patched version of $.ajax from the net.
  • Avoid http request on https sites. Your user will be prompted with a nagging security popup, which on rejection can break your request.
  • Avoid loading multiple jQuery versions.
  • Majority of the jQuery plugins are browser compatible, but NOT ALL. Read the plugin documentations carefully and use them judiciously.

This might appear to be a drop from the ocean. But it will guide them in the right direction.

Generate JSON string output in C#


This is one of the most widely used and very useful script that you could use in your web services/ WCF services/ Handlers or any place wherein you require a JSON string to be passed to the client/ consumer.

We make use of the Serialize method in JavaScriptSerializer class in C# under the following namespace:

using System.Web.Script.Serialization;

The code snippet below show how its done:

//Namespace for the JavascriptSerializer object

using System.Web.Script.Serialization;

public string GenerateJSONString(List<myObject> myCustomList)

{

//Initialize the JavascriptSerializer object   

JavaScriptSerializer serializer = new JavaScriptSerializer();

//Initialize a stringbuilder object to hold the final JSON output     

StringBuilder jsonBuilder = new StringBuilder();

//Generate the JSON string

serializer.Serialize(myCustomList, jsonBuilder);

//Return the JSON string

return Convert.ToString(jsonBuilder);

}

This code is just a framework to get to know that the JavascriptSerializer could help you generate JSON string with ease.

In the client side, you could use jQuery.parseJSON(JSONstring); and then parse this JSON string using the myObject properties. Remeber that parseJSON was added in jQuery v1.4.1.

Selecting a complex jQuery selector present in a page


Most of time, the moment we see a complex ID like ‘ctl00_m_g_f368f5ab_d679_4436_a6da_938c6bfcd60a_ctl00_SearchCheckBox’ we faint… 😉

And what we end up is start finding some parent which has an ID or see if there is a css class defined for this control. Targeting a control using its parent is good and performance-wise effective. However, using a css class for targeting a control is not advisable.

To work with a control which has a full-grown id like the one mentioned above, all you need is to make use of the CSS 3 selector. Before i proceed, let me clear a wrong notion here…

CSS 3 won’t work in IE6.0 [period], but CSS 3 selectors when used in jQuery on an IE 6 browser will work [period]

Solution:

$(“[id$=_SearchCheckBox]”).css(‘color’,’#737373′);

Steps to write:

$(“”).css(‘color’,’#737373′); //This is what you want at the end

$(“[]“).css(‘color’,’#737373′); //Add square brakets inside

$(“[id$=]”).css(‘color’,’#737373′); //Add id$= inside the square brackets

$(“[id$=_SearchCheckBox]”).css(‘color’,’#737373′); //Add your tail end of your id

Note:

$ in regular expression, is used to match a text that ends with a particular string. You can refer the CSS 3.0 Cheat Sheets to see the other possible options.

 

Solve Flickering jQuery accordion issue in MOSS 2007


MOSS 2007 for the simple reason of missing a DOCTYPE can screw up the smoothness of animations created through jQuery. One of my situations didn’t allow me to add DOCTYPE to my master and my clients ended up seeing flickering animation of the accordion. Seriously that was irritating. Being an ardent admirer and an evangelist of jQuery, it gave me a shock. But after some level of problem analysis and testing, i was able to get hold of a workaround.

One piece of advice: If you could add a DOCTYPE to your masterpage, you can very well get rid of this flickering issue.

Solution:

The sliding down effect of accordion was firing the callback once, while slidingup was triggering the callback twice. That was the catch. All i did was introduce a delay during the slide up operation, so that the first callback is veiled and only one invoke is visible.

Code Fix:

//Pause method which is to be used for the accordion slideup veil

var speed = 300;

function pausejs(millis) {
var date = new Date();
var curDate = null;
do { curDate = new Date(); }
while (curDate – date < millis);
}

$(“#accordion h2”).live(‘click’, function() {
$(“#accordion div”).slideUp(speed);     //slide up all the accordion children
        pausejs(speed);      //introduce a delay before the next code is executed
if ($(this).next().is(“:hidden”)) {      //opens up the respective child
$(this).next().slideDown(speed);
}
});

Explanation:

On clicking any of h2 (accordion headers), slide up all the accordion content/children. Then open up the respective accordion content/children. But before you open up / slideDown the respective child, ensure that the slideUp operation was complete. For this we introduce the delay.

You can also try using the callback argument of the slideUp(speed, callbackfunction) and invoke the slideDown of the respective child on completion of slideUp operation. However, since i did not find the flickering issue not getting resolved, i did not go ahead with that.

Enable Tab navigation for your entire page using jQuery


One of the most commonly faced Accessibility issue is in maintaining the tab order. If you don’t take it the right way, you might end up wasting days and days of effort, when you can just get it done in 2mins using jQuery.

Requirement:

Clicking on tab should go through all the functional controls on my current page.

Solution:

$(function() {
SetTabIndex();//Set tabIndex for all the HTML input elements, dropdowns, anchor tags and any control with classname as ‘linkname’ coming under control with id ‘myId’
});
function SetTabIndex() {
var tabindex = 1;
$(‘input,select,a,#myId .linkname’).each(function() {
if (this.type != “hidden”) {
var $input = $(this);
       $input.attr(“tabindex”, tabindex);
tabindex++;
}
});
}

Concept:

It’s very simple, you just need to set the tabIndex property of all the desired controls on your page, when the DOM load is complete.

Word of Caution:

It might look simple to you, but there is an expensive for loop going on inside, hence its desirable to avoid using any classnames and good to target Ids and specific controls. But i did not see much impact on my page which had around 300 links.

Hope this saved your time and effort.

jQuery Plugin: Page Size Analyzer for Page Performance Monitoring


One of my senior Technical Architect asked me if i could come up with some useful widget that could help him display the page size of the current page. I thought of writing a jQuery plugin that could do this job. I am sharing it here. Do read the notes carefully before using it.

Screenshot:

Features v1.0:

  • Totally unobtrusive
  • Gives the result in KB or bytes according to the page size
  • Page Size displayed in red or green depending on the threshold value set
  • No server post done to retrieve the page size.

Known Issues:

  • Page size is an approximate value. Double-chords(“) associated with the ID, script tags are excluded in this calculation. I am working on a fix for this.

How to use?

  • Load your jquery using the script tag.

<script language=”javascript” src=”jquery-1.4.2.min.js” type=”text/javascript”></script>

  • Load this plugin using the script tag.

<script language=”javascript” src=”pagesize.js” type=”text/javascript”></script>

  • Invoke the script and set the appropriate parameters

<script language=”javascript” type=”text/javascript”>
$(document).ready(function(){
var res= $(“html”).html();
$(“html”).pagesize({pagecontrol:”mydiv”,threshold:50,decimalplace:3}); //threshold value is in KB; decimalplace is for the number of decimal places for the page size
});
</script>

  • Place a control (div or span) on the page wherein the page size should be displayed.

<span id=”mydiv”></span>

Complete source code:

<html>
<head>
<script language=”javascript” src=”jquery-1.4.2.min.js” type=”text/javascript”></script>
<script language=”javascript” src=”pagesize.js” type=”text/javascript”></script>
<script language=”javascript” type=”text/javascript”>
$(document).ready(function(){
var res= $(“html”).html();
$(“html”).pagesize({pagecontrol:”mydiv”,threshold:50,decimalplace:3});
});
</script>
</head>
<body>
<span id=”mydiv”></span>
</body>
</html>

Downloads:

Demo [Remove the .pdf part from the filename]

Pagesize.js [Remove the .pdf part from the filename]