Google +1, share, javascript callback

Google plus button, you can set a callback attribute to a js function,

<g:plusone href="http://youtubeplaylist.net" 
   callback="plusClick"></g:plusone>

In the callback js function, you can check the state, if they have clicked +1 or removed +1.

    function plusClick(data) {
        if (data.state == "on") {
            alert("+1");
            // +1
        } else if (data.state == "off") {
            // -1 (user took their +1 Away)
            alert("-1");
        }
    }
    (function () {
        var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
        po.src = 'https://apis.google.com/js/plusone.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
    })();

There are some other js callback as well, such as onstartinteraction (when the +1 dialog popups up), onendinteraction (when +1 dialog close).

For more information, check out this google page, https://developers.google.com/+/plugins/share/#sharetag-parameters

Advertisements

Facebook share and like with javascript callback

1. Like button,

Here is the html of what url in the “like” box,

<div class="fb-like-box"></div>

You have to create a facebook application, and assign the “appId” in the fbAsyncInit method,

    window.fbAsyncInit = function () {
        FB.init({
            appId: '#Replace Your AppID#',
            status: true,
            cookie: true,
            xfbml: true,
            oauth: true
        });
        FB.Event.subscribe('edge.create', function (response) {
            alert('You liked the URL: ' + response);
        });
    };
    (function (d) {
        var js, id = 'facebook-jssdk';
        if (d.getElementById(id)) {
            return;
        }
        js = d.createElement('script');
        js.id = id;
        js.async = true;
        js.src = "//connect.facebook.net/en_US/all.js";
        d.getElementsByTagName('head')[0].appendChild(js);
    }(document));

With the FB.event.subscribe callback method, you can put some of your stuff, like award the guy who liked your site =)

2. Share button

This is calling FB.init(), then FB.ui() to load the dialog and with callback, the callback response, you can retrieve the post_id for your tracking.

window.fbAsyncInit = function () {
        FB.init({
            appId: '#Replace Your AppID#',
            status: true,
            cookie: true,
            xfbml: true,
            oauth: true
        });

        FB.ui(
        {
            method: 'feed',
            name: 'Facebook Dialogs',
            link: 'http://youtubeplaylist.net',
            picture: 'http://fbrell.com/f8.jpg',
            caption: 'Reference Documentation',
            description: 'Dialogs provide a simple, consistent interface for applications to interface with users.'
        },
            function (response) {
                if (response && response.post_id) {
                    alert('Post was published.');
                } else {
                    alert('Post was not published.');
                }
            }
        );

    };
    (function (d) {
        var js, id = 'facebook-jssdk';
        if (d.getElementById(id)) {
            return;
        }
        js = d.createElement('script');
        js.id = id;
        js.async = true;
        js.src = "//connect.facebook.net/en_US/all.js";
        d.getElementsByTagName('head')[0].appendChild(js);
    }(document));

Twitter, tweet button with javascript callback

Here is an example of using Twitter Web intents with js events callback.  This is the html anchor tag.

<a href="https://twitter.com/intent/tweet?text=&amp;url=http://youtubeplaylist.net&amp;via=ytubeplaylist" class="twitter-share-button">Tweet</a>

To allow the js events, you must include the widget.js to make it working. Here is the code in below,

    window.twttr = (function (d, s, id) {
        var t, js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return; js = d.createElement(s); js.id = id;
        js.src = "//platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js, fjs);
        return window.twttr || (t = { _e: [], ready: function (f) { t._e.push(f) } });
    }(document, "script", "twitter-wjs"));


Next, we use twttr.ready() to to bind events in this method, we can bind several events like, tweet, follow, retweet, favorite, click,

twttr.ready(function (twttr) {
        twttr.events.bind('tweet', function (event) {
            // Do something there
            alert("callback");
        });
		twttr.events.bind('follow', function(event) {
    		var followed_user_id = event.data.user_id;
    		var followed_screen_name = event.data.screen_name;
		});

		twttr.events.bind('retweet', function(event) {
		    var retweeted_tweet_id = event.data.source_tweet_id;
		});

		twttr.events.bind('favorite', function(event) {
		    var favorited_tweet_id = event.data.tweet_id;
		});
});

For more information, check out the twitter documentation, https://dev.twitter.com/docs/intents/events#waiting-for-asynchronous-resources

JQuery ajax request not working in IE9

I have some ajax get request on the web page and it works perfectly fine in Firefox and Chrome. But it is not working with IE at all. After some research, I found out I need to specify the dataType and allow cross domain.

Before I have,

            $.ajax({
                type: "GET",
                url: 'http://example.com/abc',
                error: function (xhr, statusText) {
						//log error                    
                },
                success: function (data) {                    
						//process data
                }
            });
        }

After I have specify the dataType, contentType and crossDomain, it works straight away.

            $.ajax({
                dataType: "jsonp",
                contentType: "text/json; charset=utf-8",
                crossDomain: true,
                type: "GET",
                url: 'http://example.com/abc',
                error: function (xhr, statusText) {
						//log error                    
                },
                success: function (data) {                    
						//process data
                }
            });
        }

This little tip saved my day!

twitter bootstrap modal popup, customized size and centralized location.

When I try to make bootstrap modal wider than the default. It is not centralized anymore, here we need to modify the css to adjust the left margin to the right px. Here is a block of handy code to adjust the modal width by a certain percentage of document width and adjust the left margin to centralize the modal as well.

$('#mymodal').modal({
        backdrop: true,
        keyboard: true
    }).css({
       'width': function () { 
           return ($(document).width() * .9) + 'px';  
       },
       'margin-left': function () { 
           return -($(this).width() / 2); 
       }
});

Create a custom HtmlHelper.TextBoxFor() to display label text as “placeholder” integrated with twitter bootstrap

We have TextBoxFor() and LabelFor() in MVC, they are binded with my model. If you are using twitter bootstrap and want to display the model property label as a placeholder in textboxes, what should you do.

Here is what I have done.

My model:

public class User
{
    [Display(Name="User name")]
    public string Username {get;set;}
}

Normally in the view we put,

@model User

<ol>
    <li>
        @Html.LabelFor(p=&gt;p.Username)
        @Html.TextBoxFor(p=&gt;p.Username)
    </li>
</ol>

image

If you want to display it as placeholder in twitter bootstrap,

image

Let’s create a TextBoxPlaceHolderFor() extension method of the htmlhelpers, remember to reference the namespace,

using System.Web.Mvc.Html;

So you can re-use the HtmlHelper.TextBoxFor() in your TextBoxPlaceHolderFor() method.

Here is the code with three overloads,

public static class TextBoxForExtensions
    {
        public static MvcHtmlString TextBoxPlaceHolderFor(this HtmlHelper html, Expression<Func> expression, object htmlAttributes)
        {
            var dict = new RouteValueDictionary(htmlAttributes);
            return html.TextBoxPlaceHolderFor(expression, dict);
        }
        public static MvcHtmlString TextBoxPlaceHolderFor(this HtmlHelper html, Expression<Func> expression)
        {
            var htmlAttributes = new Dictionary();
            return html.TextBoxPlaceHolderFor(expression, htmlAttributes);
        }

        public static MvcHtmlString TextBoxPlaceHolderFor(this HtmlHelper html, Expression<Func> expression, IDictionary htmlAttributes)
        {
            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
            string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
            string labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
            if (!String.IsNullOrEmpty(labelText))
            {
                if (htmlAttributes == null )
                {
                    htmlAttributes = new Dictionary();
                }
                htmlAttributes.Add("placeholder", labelText);
            }
            return html.TextBoxFor(expression, htmlAttributes);
        }

    }

When you call the methods you can do,

@Html.TextBoxPlaceHolderFor(m => m.UserName)

//or 

@Html.TextBoxPlaceHolderFor(m => m.UserName, new { @class="form-field" })


You are done. Now get your form neat and clean using the TextBoxPlaceHolderFor().