Search code examples
javascriptjquerynamespacesfacebook-sdk-3.0

Facebook SDK takes over "$" from jQuery - how to stop that?


I'm using both the Facebook SDK and jQuery... for some reason, with the Facebook SDK loading, $ no longer works as the jQuery object. All my jQuery calls still work but I have to use jQuery instead of $... see below for an example. I also have other code in my footer that is just jQuery stuff and the $ doesn't work there either. Everything functions perfectly but I hate this and want to be able to use $ as a shortcut for jQuery! How can I get my $ back?

<script type='text/javascript' src='http://x.com/wp-includes/js/jquery/jquery.js?ver=1.10.2'></script>

<script>
window.fbAsyncInit = function () {
    FB.init({  // (this code straight from FB developer docs)
        appId: '1234123412341234',
        channelUrl: '//mysite.com/channel.html',
        status: true,
        cookie: true,
        xfbml: true
    });

    function checkLoginStatus(response) {
        if(response && response.status == 'connected') {
            jQuery('#login-btn').hide();
            jQuery('#logout-btn').show();
            console.log('User ID: ' + response.authResponse.userID);
        } else {
            jQuery('#login-btn').show();
            jQuery('#logout-btn').hide();
        }
    }

// Load the SDK asynchronously (this code straight from FB developer docs)
(function (d) {
    var js, id = 'facebook-jssdk',
        ref = d.getElementsByTagName('script')[0];
    if (d.getElementById(id)) {
        return;
    }
    js = d.createElement('script');
    js.id = id;
    js.async = true;
    js.src = "//connect.facebook.net/en_US/all.js";
    ref.parentNode.insertBefore(js, ref);
}(document));
</script>

Solution

  • Just use a self-executing function, and pass jQuery as argument $.

    jQuery.noConflict();
    (function ($) {
        FB.init({  // (this code straight from FB developer docs)
            appId: '1234123412341234',
            channelUrl: '//mysite.com/channel.html',
            status: true,
            cookie: true,
            xfbml: true
        });
    
        function checkLoginStatus(response) {
            if(response && response.status == 'connected') {
    
                $('#login-btn').hide();
                $('#logout-btn').show();
    
                console.log('User ID: ' + response.authResponse.userID);
    
            } else {
    
                $('#login-btn').show();
                $('#logout-btn').hide();
    
            }
        }
    })(jQuery);
    

    You can read more here