Blog posts about jquery

  • How to set this when calling a javascript function

    February 04, 2014 | Tags: Javascript, jQuery, Snippet
    Ever wondered how the this entity was set in a function like for instance a jQuery event handler? Or maybe even needed to invoke that event handler from code passing the object that would be accessed through this within the function? The secret is to use the call-function that is available on every function in JavaScript.

    If you for instance have an event handler setup in jQuery like the one below:
    function buttonClickHandler(e) {
    $(this).addClass('clicked');
    }

    $('a.btn').click(buttonClickHandler);
    ..that you would like to invoke from code and passing the object that would be accessed through this within the function, using the call-function on your event handler function will do the trick:
    var btn = $('#button1');
    buttonClickHandler.call(btn);

    The syntax of the call-function is: call(thisArg[, arg1[, arg2[, ...]]]). The first parameter you pass is what will be accessible through the this entity. Then follows optional parameters that will be passed as parameters to the function being called in the given order.

    If you which to pass an object as this to a function that takes two parameters (lets say showName(firstName, surName)) you would do it like this:
    function showName(firstName, surName) {
    $(this).val(firstName + ' ' + surName);
    }

    var element = $('#element');
    showName.call(element, 'alice', 'cooper');

  • Convert JSON string to JavaScript objects safely

    February 03, 2014 | Tags: Javascript, JSON, jQuery
    If you have a JSON string that you want to convert into JavaScript object but doesn't want to use eval (which you should avoid due to the security implications), you can either use jQuery.parseJSON() or - if you're not using jQuery - use a dedicated JSON library such as JSON 3.
    // using jQuery
    var myObject = jQuery.parseJSON(myJSONString);

    // using JSON 3 (for polyfill in older browsers)
    var myObject2 = JSON.parse(myJSONString);

  • $(window).height() vs $(document).height()

    April 23, 2013 | Tags: Javascript, Troubleshooting, jQuery
    I was trying to use the $(window).height() method in jQuery to get the height of the browser window but was instead getting the document height in return (same as $(document).height()).

    So, what to do if window height returns document height instead?

    Solution

    The problem is most likely that your HTML document lacks a <!DOCTYPE>-definition. So the solution to the problem is to add a valid <!DOCTYPE> like <!DOCTYPE HTML> in the top of the HTML file. When done $(window).height() should start to report the proper window height and not the document's.



  • JQuery UI dialog ASP.NET postback problem

    August 24, 2011 | Tags: Javascript, ASP.NET, Troubleshooting, jQuery, Snippet
    I you're trying to use the jQuery UI dialog function together with ASP.NET form postback you might be in for a suprise. Most likely that suprise is that the fields will be returned empty to your server side code. And that would be a rather big problem.

    The reason for this is that the dialog function pulls your element and puts it in a window container which are placed outside the Form tag. And therefor if you do a postback directly from the dialog the input fields in the dialog are not included in the data that is posted to the server.

    But there's an easy way to solve this. And that is to add a line to your javascript code that move the dialog window back into the Frame element.

    var myDialog = jQuery("#myDialog").dialog({ width: 480, height: 400 });
          

    // This is where the magic happens :)
    myDialog.parent().appendTo(jQuery("form:first"));

    Or if you're more into one liners, here you go:
    jQuery("#myDialog").dialog({ width: 480, height: 400 }).parent().appendTo(jQuery("form:first"));
          

  • Get Facebook profile picture using API and jQuery

    January 12, 2011 | Tags: Javascript, Facebook, jQuery, Snippet
    This shows how to fetch the users profile information directly to your web page using the Facebook API and jQuery (for updating the HTML).

    First step is to register your web site as a Facebook app. You will need a Facebook account in order to access the development features.



    If you're doing local development be sure to set the URL to your local path, otherwise you'll get an error saying: API Error Code: 191
    API Error Description: The specified URL is not owned by the application


    Once signed up your new Facebook app will get an App ID assigned. You need to copy that into the script below where it says xxxxxxxxxxxxxxxxx.

    Most of the code below should be self explaining, but this is what it does:
    1) Init a connection to Facebook with your app id
    2) Get login status and..
    3a) Show connect button if not connected
    3b) Show profile information if connected

    <div id="fb-root"></div>
    <script src="http://connect.facebook.net/en_US/all.js"></script>

    <h2>Profile</h2>
    <div id="account-info"></div>

    <script>
    function showAccountInfo() {
    FB.api({
    method: 'fql.query',
    query: 'SELECT name, pic FROM user WHERE uid=' + FB.getSession().uid
    },
    function(response) {
    $('#account-info').html('<img src="' + response[0].pic + '">' +
    response[0].name + ' <img onclick="FB.logout()" style="cursor: pointer;" ' +
    'src="https://s-static.ak.fbcdn.net/rsrc.php/z2Y31/hash/cxrz4k7j.gif">');
    }
    );
    }

    function showLoginButton() {
    $('#account-info').html('<img onclick="FB.login()" style="cursor: pointer;" ' +
    'src="https://s-static.ak.fbcdn.net/rsrc.php/zB6N8/hash/4li2k73z.gif">');
    }

    // Called when Facebook login status change
    function onStatus(response) {
    if (response.session) {
    showAccountInfo();
    } else {
    showLoginButton();
    }
    }
    FB.init({
    appId: 'xxxxxxxxxxxxxxxxx',
    cookie: true,
    status: true,
    xfbml: true
    });

    FB.getLoginStatus(function(response) {
    onStatus(response); // once on page load
    FB.Event.subscribe('auth.statusChange', onStatus); // every status change
    });

    </script>

    You can access other profile information as well. You'll find all properties on the user object over at Facebook Query Language (FQL) Reference.

    If you're getting an unspecified error when trying to connect a user to your web page, the most likely issue is that you're app is in sandbox mode which blocks the app for other users than the developer. You can turn it off under settings over at your Facebook app page.