Archive for the ‘jQuery & Javascript’ Category

Twitter Login and Auth in a Popup Window

Making use of Twitter in an app is a simple and straightforward task thanks to great libraries like this one that handle all of the OAuth handshaking and heavy lifting for you. The only problem with the default method is that when a user clicks the connect via Twitter button, it takes them to the Twitter login page and eventually redirects them back to you.

Folks around the Internet are not keen on this approach, preferring a Facebook style integration where a simple pop-up is used to contain the Twitter login process, ensuring the user never loses your page along the way.

First off, grab the Twitter API library if you haven’t already and familiarize yourself with the fantastically simple process. I’m going to modify the included example files to the pop-up feature. First, we add some javascript on the connect.php page (the one with the Twitter button). Add a click event to that connect link that opens a simple window:

window.open('./redirect.php', 'Twitter', 'menubar=no,width=790,height=360,toolbar=no');

The width and height are setup to properly accommodate the Twitter login page. Notice that I am setting the source of the new window to redirect.php, which sets everything up to begin the auth process before sending the pop-up off to Twitter’s login.

The next step is to handle the post-login phase when the user is returned to us. The example uses callback.php as the target for the post-auth redirect, so we’ll modify there. All we have to do there is simply add some javascript to refresh or parent page and close the pop-up and we’re all set. So remove the existing index redirect in the callback file and replace it with some simple javascript and a blank html page:

opener.location = 'index.php'; // could be a refresh or anything really
self.close();

There you have it. The process is essentially the same as the before, only now we’ve moved it all into a separate window that we tightly control.

Javascript: The importance of the var keyword

I recently found a great example of the importance of the var keyword and properly scoping your variables in javascript. In the best case, we should be coding in an object oriented way and utilizing closures to properly contain our code, but sometimes we run into some plain old javascript written the old fashioned (read: messy) way.

By omitting var, we are essentially declaring the variable in the global scope, which is most likely not something we want to be doing. A great example is when declaring an iterator variable for a loop. Without var, the iterator is exposed to any functions called within the loop. If that function also has a variable of the same name that is not locally scoped, you will find that upon completion of the called function, your iterator is suddenly way off.

function parent() {
     // some (incorrect) loop calling a function
     for(iterator=0; iterator<5; iterator++) {
          child();
     }
};

// This function can then mess with our iterator!
function child() {
    iterator = 99;
}

This example shows how some code hidden away in a called function may inadvertently mess with your variables. It is only made worse when both caller and callee are disregarding scope by omitting var. The proper loop is then obvious:

for(var iterator=0; iterator<5; iterator++)

By doing so, we ensure that no one else can accidentally mess with the internals of our code. This is an easy mistake to make, but fortunately not too difficult to identify and correct.

Programmatically clicking an anchor tag via Javascript

Here’s a simple one that occurs often. Take for instance, the links on the sidebar of this blog. The links are wrapped in list items, however you’ll notice that you can just as easily click the big list item block as you can the link itself. Additionally, hovering over the list item triggers the hover state of the child link element. Here’s the code used to achieve this.

// Cause the parent list item to function like its child link
// Note we must use window.location as triggering a click event programmatically will not work!
$('li.widget_categories li, li.widget_archives li').click(function() {
    window.location = $(this).children('a').attr('href');
});

// When mousing over a list item, we add a class to the child link that imitates its hoverstate.
// Triggering mouse events and the like will only cause recursion errors.
$('li.widget_categories li, li.widget_archives li').mouseenter(function() {
    $(this).children('a').addClass('active');
});

// Same as above, only this time we return to normal
$('li.widget_categories li, li.widget_archives li').mouseleave(function() {
    $(this).children('a').removeClass('active');
});

Simple stuff here, but that’s about all I seem to ever have time to write down.

Adding social sharing buttons after page load

More and more sites are adding the various slew of social sharing buttons onto their pages and blog posts. There are several widgets like ShareThis and AddToAny that attempt to handle this, but what if you only want to add specific sharing buttons to your page? And what if you want to delay the loading of these buttons so as to not block the loading of your page?

I spent about an hour today solving this problem to implement a Digg, Facebook, and TweetMeMe combo of buttons. The first two weren’t much trouble, but the ReTweet button and its generated iFrame were causing me headache. My soluction simply added the iFrame myself, note also that in order to add javascript via jQuery, one must use a quirky workaround:

tweetmeme_style = 'compact';

function loadSocialButtons() {

     var str = '<ul>';

     // add digg
     str += '<li>';
     str += '<script src="http://widgets.digg.com/buttons.js" type="text/javascript">// <![CDATA[';
     str += '<';
     str += '/script>';
     str += '<a class="DiggThisButton DiggCompact"></a>';
     str += '</li>';

     // add facebook
     str += '<li>';
     str += '<a id="fb-share" name="fb_share" type="button_count" href="http://www.facebook.com/sharer.php" mce_href="http://www.facebook.com/sharer.php">Share</a>';
     str += '<script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" mce_src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript">';
     str += '<';
     str += '/script>';
     str += '</li>';

     // add retweet
     str += '<li>';
     str += '<iframe width="90" scrolling="no" height="20" frameborder="0" src="http://api.tweetmeme.com/button.js?url=ADD_YOUR_URL&amp;style=compact" mce_src="http://api.tweetmeme.com/button.js?url=&amp;style=compact"></iframe>';
     str += '</li>';
     str += '</ul>';

     $('div#social').html(str);
}

$(document).ready(function() {
     setTimeout("loadSocialButtons()", 1000);
});

Make sure to add your page’s url in the TweetMeMe section, you can do this with some server side code.

Triggering events in parent document within iFrame

Consider a situation where you have an iFrame on a page. Suppose you have an element outside of the iFrame (in the parent document) that you wish to target with some jQuery from within the iFrame. This situation may sound odd, but it has come up multiple times.

The method by which I target elements in the parent document is quite straightforward:

$(window.parent.document).find('some.selector');

This simply gets the parent document and uses find to get whatever page element you are after. Quite obvious when you see it, but it can be elusive in the moment.