Some Useful JavaScript & jQuery Snippets – Part 4

How to get client ip address with jQuery $.getJSON(“http://jsonip.appspot.com?callback=?”,function(data){ alert( “Your ip: ” + data.ip); }); How to parse XML with jQuery file.xml: <?xml version=”1.0″ ?> <result> <item> <id>1</id> <title>title1</title> […]

  • How to get client ip address with jQuery
  • $.getJSON("http://jsonip.appspot.com?callback=?",function(data){
        alert( "Your ip: " + data.ip);
    });
  • How to parse XML with jQuery
  • 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 ...
        });
    });

    Tiny break: 📬 Want to stay up to date with frontend and trends in web design? Subscribe and get our Collective newsletter twice a tweek.

  • How to get the number in the ids
  • <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];
        ...
    });
  • How to transform a number like 12343778 into 12.343.778
  • <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);
  • Count number of textarea lines
  • var text = $("#textareaId").val();
    var lines = text.split(/r|rn|n/);
    alert(lines.length);
  • Logging to the firebug console
  • 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");
  • Find X/Y of an HTML element with Javascript
  • // 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
        };
    };
  • Validate Credit Card
  • 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);
    }
  • Distinguish left and right mouse click
  • $("#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");
    });
  • How to get the native image size
  • var img = $('#imageid');
    var theImage = new Image();
    theImage.src = img.attr("src");
    alert("Width: " + theImage.width);
    alert("Height: " + theImage.height);

    cody

    Cody loves jQuery - he puts the magic into every web application. He is crazy about Curry dishes.

    Stay in the loop: Get your dose of frontend twice a week

    Fresh news, inspo, code demos, and UI animations—zero fluff, all quality. Make your Mondays and Thursdays creative!

    Feedback 5

    Comments are closed.
    1. Pingback: Some Useful JavaScript & jQuery Snippets – Part 4 | Codrops

    2. Pingback: Tweets that mention Some Useful JavaScript & jQuery Snippets - Part 4 | Codrops -- Topsy.com

    3. >How to get the number in the ids
      You can use .index() method in jQuery.

      var index = $(this).index();