Toggle menu
876
3.8K
30.2K
279.1K
Catglobe Wiki
Toggle preferences menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

JQuery - Tips: Difference between revisions

From Catglobe Wiki
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: …'
Β 
Nguyentrantri (talk | contribs)
No edit summary
Β 
(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 09: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}}";