Difference between revisions of "JQuery - Tips"

From Catglobe Wiki
Jump to: navigation, search
(Created page with '*** under contruction Following are few very useful jQuery Tips and Tricks for all jQuery developers. I am sharing these as I think they will be very useful to you. Disclaimer: …')
 
 
(20 intermediate revisions by 3 users not shown)
Line 1: Line 1:
*** under contruction
+
<accesscontrol>Main:MyGroup</accesscontrol>
 +
[[Category:Miscellaneous]]
 +
== JQuery Tips ==
  
Following are few very useful jQuery Tips and Tricks for all jQuery developers. I am sharing these as I think they will be very useful to you.
+
'''1. Optimize performance of complex selectors'''<br/>var subset = $(""); $("input[value^='']", subset);''<br/><br/>'''2. Set Context and improve the performance'''<br/>On the core jQuery function, specify the context parameter when. Specifying the context parameter allows jQuery to start from a deeper branch in the DOM, rather than from the DOM root. Given a large enough DOM, specifying the context parameter should translate to performance gains. $("input:radio", document.forms[0]);<br/><br/>'''3. Live Event Handlers'''<br/>Set an event handler for any element that matches a selector, even if it gets added to the DOM after the initial page load: $('button.someClass').live('click', someFunction);<br/><br/>'''4. To show / hide element'''
Disclaimer: I have not written all of the below code but have collected from various sources from Internet.
 
1. Optimize performance of complex selectors
 
  
Query a subset of the DOM when using complex selectors drastically improves performance:
+
$("a").hide();
view source
+
$("a").show();
print?
 
1 var subset = $("");
 
2 $("input[value^='']", subset);
 
2. Set Context and improve the performance
 
  
On the core jQuery function, specify the context parameter when. Specifying the context parameter allows jQuery to start from a deeper branch in the DOM, rather than from the DOM root. Given a large enough DOM, specifying the context parameter should translate to performance gains.
+
<br/>'''5. Check element exists'''
view source
 
print?
 
1 $("input:radio", document.forms[0]);
 
3. Live Event Handlers
 
  
Set an event handler for any element that matches a selector, even if it gets added to the DOM after the initial page load:
+
if ($("#someDiv").length) {}
view source
 
print?
 
1 $('button.someClass').live('click', someFunction);
 
  
This allows you to load content via ajax, or add them via javascript and have the event handlers get set up properly for those elements automatically.
+
<br/>'''6. Back to top button/link'''
  
Likewise, to stop the live event handling:
+
$('#top').click(function() { 
view source
+
$(document).scrollTo(0,500); }
print?
 
1 $('button.someClass').die('click', someFunction);
 
  
These live event handlers have a few limitations compared to regular events, but they work great for the majority of cases. Live event will work starting from jQuery 1.3
+
<br/><br/>'''7. Change width of item on many browser'''
4. Checking the Index
 
  
jQuery has .index but it is a pain to use as you need the list of elements and pass in the element you want the index of
+
$('#input:text[name=QUESTION.Q12.1]).width(500);
view source
 
print?
 
1 var index = e.g $('#ul>li').index( liDomObject );
 
  
The following is easier:
 
  
if you want to know the index of an element within a set, e.g. list items within a unordered list:
 
view source
 
print?
 
1 $("ul > li").click(function ()
 
2 {
 
3     var index = $(this).prevAll().length;
 
4 });
 
5. Use jQuery data method
 
  
jQuery’s data() method is useful and not well known. It allows you to bind data to DOM elements without modifying the DOM.
+
<br/><br/>var error_message = "The error was happened" var oldCheck = questioncheck; questioncheck = function() {
6. Fadeout Slideup effect to remove an element
 
  
Combine more than one effects in jQuery to animate and remove an element from DOM.
+
  //QUESTION.Label1
view source
+
  if (checkLength("QUESTION.Label1",5)){
print?
+
    ErrorMessages.getInstance().clearErrorMessages();
1 $("#myButton").click(function() {
+
    ErrorMessages.getInstance().showErrorMessage(error_message);
2         $("#myDiv").fadeTo("slow", 0.01, function(){ //fade
+
    return;
3             $(this).slideUp("slow", function() { //slide up
+
  }
4                 $(this).remove(); //then remove from the DOM
+
 
5             });
 
6         });
 
7 });
 
7. Checking if an element exists
 
  
Use following snippet to check whether an element exists or not.
+
}
view source
 
print?
 
1 if ($("#someDiv").length) {
 
2     //hooray!!! it exists...
 
3 }
 
8. Add dynamically created elements into the DOM
 
  
Use following code snippet to create a DIV dynamically and add it into the DOM.
+
function checkLength(objname,maxlength) {
Further Reading: Dynamically Add/Remove rows in HTML table using JavaScript
 
view source
 
print?
 
1 var newDiv = $('<div></div>');
 
2 newDiv.attr("id","myNewDiv").appendTo("body");
 
9. Line breaks and chainability
 
  
Instead of doing:
+
  var ao=$("input:text[name="+objname+"]");
view source
+
  if (ao.val().length>maxlength)
print?
+
    return true;
1 $("a").hide().addClass().fadeIn().hide();
+
  return false
  
You can increase readability like so:
+
}<br/><br/>'''8. Get value of question in javascript'''<br/>from_Q8= "{{Q8[0].value}}";
view source
 
print?
 
1 $("a")
 
2   .hide()
 
3   .addClass()
 
4   .fadeIn()
 
5   .hide();
 
10. Creating custom selectors
 
view source
 
print?
 
1 $.extend($.expr[':'], {
 
2     over100pixels: function(a) {
 
3         return $(a).height() > 100;
 
4     }
 
5 });
 
6
 
7 $('.box:over100pixels').click(function() {
 
8     alert('The element you clicked is over 100 pixels high');
 
9 });
 
11. Cloning an object in jQuery
 
 
 
Use .clone() method of jQuery to clone any DOM object in JavaScript.
 
view source
 
print?
 
1 // Clone the DIV
 
2 var cloned = $('#somediv').clone();
 
 
 
jQuery’s clone() method does not clone a JavaScript object. To clone JavaScript object, use following code.
 
view source
 
print?
 
1 // Shallow copy
 
2 var newObject = jQuery.extend({}, oldObject);
 
3
 
4 // Deep copy
 
5 var newObject = jQuery.extend(true, {}, oldObject);
 
12. Test if something is hidden using jQuery
 
 
 
We use .hide(), .show() methods in jquery to change the visibility of an element. Use following code to check the whether an element is visible or not.
 
view source
 
print?
 
1 if($(element).is(":visible") == "true") {
 
2       //The element is Visible
 
3 }
 
13. Alternate way of Document Ready
 
view source
 
print?
 
1 //Instead of
 
2 $(document).ready(function() {
 
3     //document ready
 
4 });
 
5 //Use
 
6 $(function(){
 
7     //document ready
 
8 });
 
14. Selecting an element with . (period) in its ID
 
 
 
Use backslash in the selector to select the element having period in its ID.
 
view source
 
print?
 
1 $("#Address\\.Street").text("Enter this field");
 
15. Counting immediate child elements
 
 
 
If you want to count all the DIVs present in the element #foo
 
view source
 
print?
 
01 <div id="foo">
 
02   <div id="bar"></div>
 
03   <div id="baz">
 
04     <div id="biz">
 
05   </div>
 
06   <span><span>
 
07 </div>
 
08
 
09 //jQuery code to count child elements
 
10 $("#foo > div").size()
 
16. Make an element to “FLASH”
 
view source
 
print?
 
1 jQuery.fn.flash = function( color, duration )
 
2 {
 
3     var current = this.css( 'color' );
 
4     this.animate( { color: 'rgb(' + color + ')' }, duration / 2 );
 
5     this.animate( { color: current }, duration / 2 );
 
6 }
 
7 //Then use the above function as:
 
8 $( '#importantElement' ).flash( '255,0,0', 1000 );
 
17. Center an element on the Screen
 
view source
 
print?
 
1 jQuery.fn.center = function () {
 
2     this.css("position","absolute");
 
3     this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
 
4     this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
 
5     return this;
 
6 }
 
7
 
8 //Use the above function as:
 
9 $(element).center();
 
18. Getting Parent DIV using closest
 
 
 
If you want to find the wrapping DIV element (regardless of the ID on that DIV) then you’ll want this jQuery selector:
 
view source
 
print?
 
1 $("#searchBox").closest("div");
 
19. Disable right-click contextual menu
 
 
 
There’s many Javascript snippets available to disable right-click contextual menu, but JQuery makes things a lot easier:
 
view source
 
print?
 
1 $(document).ready(function(){
 
2     $(document).bind("contextmenu",function(e){
 
3         return false;
 
4     });
 
5 });
 
20. Get mouse cursor x and y axis
 
 
 
This script will display the x and y value – the coordinate of the mouse pointer.
 
view source
 
print?
 
1 $().mousemove(function(e){
 
2     //display the x and y axis values inside the P element
 
3     $('p').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY);
 
4 });
 
5
 
6 <p></p>
 

Latest revision as of 11:39, 23 October 2013

<accesscontrol>Main:MyGroup</accesscontrol>

JQuery Tips

1. Optimize performance of complex selectors
var subset = $(""); $("input[value^=]", subset);

2. Set Context and improve the performance
On the core jQuery function, specify the context parameter when. Specifying the context parameter allows jQuery to start from a deeper branch in the DOM, rather than from the DOM root. Given a large enough DOM, specifying the context parameter should translate to performance gains. $("input:radio", document.forms[0]);

3. Live Event Handlers
Set an event handler for any element that matches a selector, even if it gets added to the DOM after the initial page load: $('button.someClass').live('click', someFunction);

4. To show / hide element

$("a").hide();
$("a").show();


5. Check element exists

if ($("#someDiv").length) {}


6. Back to top button/link

$('#top').click(function() {  
$(document).scrollTo(0,500);  }



7. Change width of item on many browser

$('#input:text[name=QUESTION.Q12.1]).width(500);




var error_message = "The error was happened" var oldCheck = questioncheck; questioncheck = function() {

  //QUESTION.Label1
 if (checkLength("QUESTION.Label1",5)){
    ErrorMessages.getInstance().clearErrorMessages();
    ErrorMessages.getInstance().showErrorMessage(error_message);
    return;
 }
 

}

function checkLength(objname,maxlength) {

  var ao=$("input:text[name="+objname+"]");
 if (ao.val().length>maxlength)
    return true;
 return false

}

8. Get value of question in javascript
from_Q8= "{{Q8[0].value}}";