Some Useful JavaScript & jQuery Snippets – Part 4
Development January 11, 2010 by cody 4 Comments

$.getJSON("http://jsonip.appspot.com?callback=?",function(data){
alert( "Your ip: " + data.ip);
});
file.xml:
<?xml version="1.0" ?>
<result>
<item>
<id>1</id>
<title>title1</title>
<description>desc1</description>
</item>
<item>
<id>2</id>
<title>title2</title>
<description>desc2</description>
</item>
<!-- ... -->
</result>
$.get('file.xml',{},function(data){
$('item',data).each(function(){
var $this = $(this);
var id = $this.find('id').text();
var title = $this.find('title').text();
var description = $this.find('description').text();
//do something ...
});
});
<div id="sites">
<a id="site_1" href="http://siteA.com">siteA</a>
<a id="site_2" href="http://siteB.com">siteB</a>
<a id="site_3" href="http://siteB.com">siteC</a>
...
</div>
you need to get 1 from site_1, 2 from site_2 …
$("#sites a").click(function(){
var $this = $(this);
var nmb = $this.attr('id').match(/site_(\d+)/)[1];
...
});
<div id="result">12343778</div>
var delimiter = '.';
$('#result').html()
.toString()
.replace(new RegExp("(^\\d{"+($this.html().toString().length%3||-1)+"})(?=\\d{3})"),"$1" + delimiter)
.replace(/(\d{3})(?=\d)/g,"$1" + delimiter);
var text = $("#textareaId").val();
var lines = text.split(/\r|\r\n|\n/);
alert(lines.length);
jQuery.fn.log = function (msg) {
console.log("%s: %o", msg, this);
return this;
};
$('#some_div').find('li.source > input:checkbox').log("sources to uncheck").removeAttr("checked");
// Based on: http://www.quirksmode.org/js/findpos.html
var getCumulativeOffset = function (obj) {
var left, top;
left = top = 0;
if (obj.offsetParent) {
do {
left += obj.offsetLeft;
top += obj.offsetTop;
} while (obj = obj.offsetParent);
}
return {
x : left,
y : top
};
};
function isCreditCard( CC ){
if (CC.length > 19)
return (false);
sum = 0; mul = 1; l = CC.length;
for (i = 0; i < l; i++){
digit = CC.substring(l-i-1,l-i);
tproduct = parseInt(digit ,10)*mul;
if (tproduct >= 10)
sum += (tproduct % 10) + 1;
else
sum += tproduct;
if (mul == 1)
mul++;
else
mul–;
}
if ((sum % 10) == 0)
return (true);
else
return (false);
}
$("#element").live('click', function(e) {
if( (!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 1) ) {
alert("Left Button");
}
else if(e.button == 2)
alert("Right Button");
});
var img = $('#imageid');
var theImage = new Image();
theImage.src = img.attr("src");
alert("Width: " + theImage.width);
alert("Height: " + theImage.height);










>How to get the number in the ids
You can use .index() method in jQuery.
var index = $(this).index();
Really useful, thank you!