Một số hàm jquery hữu ích


1.  jQuery get array of checked checkboxes ids

1
2
3
4
5
6
var checkedIds = Array();
$('form:input[type="checkbox"][checked]').each( function(i,v)
{
    checkedIds.push($(v).attr('id'));
});
console.log(checkedIds);

 

2.  jQuery Output All Attributes of Element

jQuery code snippet which outputs all attributes of element using the default .attr() function on any dom element(s).

double click code to edit/copy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//extending the attr function to return all attrs
(function($) {
        // duck-punching to make attr() return a map
        var _old = $.fn.attr;
        $.fn.attr = function() {
          var a, aLength, attributes, map;
          if (this[0] && arguments.length === 0) {
                  map = {};
                  attributes = this[0].attributes;
                  aLength = attributes.length;
                  for (a = 0; a < aLength; a++) {
                          map[attributes[a].name.toLowerCase()] = attributes[a].value;
                  }
                  return map;
          } else {
                  return _old.apply(this, arguments);
          }
  }
}(jQuery));

usage:

double click code to edit/copy

1
console.dir($('#c4').attr());

output:

output-attributes

 3 . jQuery capture window resize

Use jQuery capture the event of when the browser window is resized, then do something. In the example below it logs the window’s new size.

1
2
3
4
5
6
7
8
9
10
11
//capture window resize
$(window).bind('resize', function(e)
{
    var win = $(this),
        w = win.width(),
        h = win.height();
    console.log('window resized to: ' + w + ' by ' + h);
});
//output: window resized to: 1598 by 521

4. jQuery count the number of checked checkboxes

Simple jQuery code snippet to count the number of checkboxes checked in a table.

1
$('#table :input[type="checkbox"]:checked').length

5. jQuery Function Get Max X,Y Coordinates of Element

jQuery function to get the coordinates of the furthest space occupied by an element (or group of elements within the selector). Could be useful if your setting the area of a container based on the absolute positioning of child elements that need to be within the container (ie for drag and drop elements).

max-location-of-element

1
2
3
4
5
6
7
8
9
10
11
12
13
14
jQuery.fn.getMaxOccupiedLocation = function()
{
    var maxX = 0, maxY = 0, tmpX, tmpY, elem;
    this.each( function(i,v)
    {
        elem = $(this),
        tmpX = elem .offset().left + elem.width(),
        maxX = (tmpX > maxX) ? tmpX : maxX,
        tmpY = elem .offset().top + elem.height(),
        maxY = (tmpY > maxY) ? tmpY : maxY;
    });
    // console.log(maxX+','+maxY);
    return { x:maxX, y:maxY }; //not the best implementation as it breaks the chain
};

 6. jQuery Set Minimum Height for Page Content

jQuery code snippet which set a minimum height for a page content area based on the size of the window. This could be used to set the footer of a page to always be on the bottom within the page content area no matter what size the window is. It could be used with Capturing window resize so that it resizes automatically when the user resizes the browser window.

1
2
3
4
5
6
7
8
9
//sets the minimum height for the content area of the page
minWrapperHeight: function()
{
    var wrapperElem = $('#wrapper');
    //padding+offset+header+footer
    var offset = wrapperElem.height()-wrapperElem.outerHeight()-$('header').height()-$('footer').height()-$('#wrapper').offset()['top'];
    console.log($(window).height() + ' - ' + offset + ' = ' + ($(document).height()-offset));
    wrapperElem.height($(window).height()+offset); //offset is negative
}
 7.  jQuery get coordinates of element

jQuery function to get coordinates of element.

The jQuery methods

.position() method allows us to retrieve the current position of an element relative to the offset parent

double click code to edit/copy

1
2
3
var pos = $('#wrapper').position();
console.dir(pos);
//output: left: 0, top: 20

.offset(), which retrieves the current position relative to the document.

1
2
3
var offset = $('#wrapper').offset();
console.dir(offset);
//output: left: 70, top: 40

Into coordinates:

1
2
3
4
5
var elem = $("#wrapper");
var x = $("#wrapper").offset().left;
var y = $("#wrapper").offset().top;
console.log('x: ' + x + ' y: ' + y);
//output: x: 70 y: 40

jQuery getCoord() function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
jQuery.fn.getCoord = function()
{
  var elem = $(this);
  var x = elem.offset().left;
  var y = elem.offset().top;
  console.log('x: ' + x + ' y: ' + y);
  //output: x: 70 y: 40
  return {
      "x" : x,
      "y" : y
  };
  //note that it is not efficient as it breaks the jQuery chain
  //return elem;
};
$('#wrapper').getCoord();
//output: Object { x=70, y=40 }

Bình luận về bài viết này