Facebook Share Link

Let’s say you have an awesome social network, a dating platform for cars, and you want to share your cars profile on Facebook. It should look like this. How do you do that?

share

First of all you should load Facebooks JavaScript SDK. Insert this code below the “body” tag in your page.

<div id="fb-root"></div>
<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&appId=99999999999999&version=v2.0";
  fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));
</script>

Replace 99999999999999 with your Facebook App ID. Next you need a JS function to trigger the share dialog. That can look like this:

function share_my_car(kfz, kfz_id, image_url){
  url_to_share = "http://contactmycar.de/cars/" + kfz_id;
  FB.ui({ method: 'feed',
          name: kfz,
          caption: 'Mein Fahrzeug auf ContactMyCar',
          picture: image_url,
          link: url_to_share }, function(response) {});
}

And finally you need a link/button to trigger the JS function. I used a link.

<a onclick="share_my_car('<%= car.kfz %>', '<%= car.id %>', '<%= car.image_url %>'); return false;" href="">
 Fahrzeug auf Facebook teilen
 </a>

That’s it.

Comparison of Application Level Package Managers

I have to work with a lot (9) of different package managers at my daily work at VersionEye. Part of our mission is it to make manual updating of dependencies extinct, because it’s a manual and time consuming task which nobody enjoys. That’s why we are building a notification system for open source software libraries to make Continuous Updating easy and fun. And since we support several programming languages – 8 at this point! – I get to write crawlers and parsers for all of them. To give you a better overview over the strengths and weaknesses of these package managers, I picked the most popular one for each language and will compare them. The contenders are:

  • RubyGems / Bundler (Ruby)
  • PIP / PyPI (Python)
  • Packagist / Composer (PHP)
  • NPM (Node.JS)
  • Bower (JS, CSS, HTML)
  • CocoaPods (Objective-C)
  • Maven (Java)
  • Lein (Clojure)

Comparison Matrix

Here are the results of my comparison.

Comparison of Package Managers

You can read the complete article on the VersionEye Blog and follow the discussion on hacker news and Reddit.

How to track page views in a SinglePage App

The google analytics snippet tracks regular page views every time the page gets reloaded. That happens if you navigate to another page or your reload the current page.

But if you have a AJAX heavy SinglePage Application, for example build with Backbone.JS or ember.js, than the default code snippet from Google is not enough. Another use case is if you want to track a JavaScript/CSS popups in Google Analytics.

Well. All you need is the default GA snippet. Which looks like this.


var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXX-Y']);
_gaq.push(['_trackPageview']);

(function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

The good thing is that you can trigger page views with the JavaScript Google provides you. All you need to do is to trigger this code.

  _gaq.push(['_trackPageview', '/popup']);

The last parameter is a fictional path. This is what you will see in the analytics. You could call this code in the “onclick” event of a button or link. I wrote this convenience method.


function page_view(path){
 if (_gaq){
   _gaq.push(['_trackPageview', path]);
 } else {
   ga('send', 'pageview', path);
 }
}

With that I am now able to track JavaScript popups, click on js/css Tabs and clicks in SinglePage Applications. All visible in Google Analytics.

Improving the Dependency Wheel at the GitMerge Hackathon

Last week I attended to the GitMerge Conference in Berlin. It was sponsored by GitHub and Google. On Saturday their was the hackathon day. I found somebody who want to contribute to the dependency wheel project. Many Thanks to Coding46 for his contributions!

The dependency wheel project is a JavaScript Library which enables you to draw a circle of dots and connect the dots according to his dependencies. Here is an example:

687474703a2f2f6d656469612d63616368652d6563352e70696e7465726573742e636f6d2f75706c6f61642f37323632303631323731313836373532325f475551696f6b76555f632e6a7067

I integrated this library into the VersionEye project to display dependencies of Software Libraries. Some users complaint that they can’t see the direction of the dependency. In the graph above you can’t see if dom4j is requesting pull-parser or pull-parser is requesting dom4j.

At the GitMerge Hackathon we did some brainstorming how we could solve this problem. We decided to solve the problem with different color. If you go with the mouse cursor over a dot we highlight the outgoing dependencies with a violet color and the incoming dependencies with a green color. Here is an example.

Screen Shot 2013-05-15 at 11.08.16 AM

In the graph above you can directly see the directions. Actionpack depends for example on activesupport, activemodel, builder, erubis, journey, rack, rack-cache, rack-test and sprockets. 2 other dependencies in the circle are depending on Actionpack. Actionmailer and railties are both depending on actionpack.

If you now move the curser to the actionmailer dot, the color of the connection to actionpack changes to green.

Screen Shot 2013-05-15 at 11.15.55 AM

Again many Thanks to Coding46 for his contributions and his help. Without him this wouldn’t be done.

jQuery textbox hinter in IE8

Maybe you know the jQuery textbox hinter. That is a JavaScript lib. that adds an text and a css class to input textbox in a HTML page. The idea behind this technic is to show a hint in a textbox. That can look like this here:

And as soon you click into the textbox the hint disappears. The jQuery textbox hinter makes a good job but in the IE8 it does not work and in my case it broke the whole jQuery code. The Problem was that in the javascript code of jQuery textbox hinter the name of the one attribute is “class”. That is keyword and it seems that makes the code IE8 broken.

I renamed the attribute and after the refactoring it worked fine in IE8. Here is my refactored version of the jQuery textbox hinter.


/*
 * jQuery - Textbox Hinter plugin v1.0
 * http://www.aakashweb.com/
 * Copyright 2010, Aakash Chakravarthy
 * Released under the MIT License.
 */

(function($){
   $.fn.tbHinter = function(options) {

   var defaults = {
      text: 'Enter a text ...',
      styleclass: ''
   };

   var options = $.extend(defaults, options);

   return this.each(function(){

      $(this).focus(function(){
         if($(this).val() == options.text){
            $(this).val('');
            $(this).removeClass(options.styleclass);
         }
      });

      $(this).blur(function(){
         if($(this).val() == ''){
            $(this).val(options.text);
            $(this).addClass(options.styleclass);
         }
      });

      $(this).blur();

   });
};
})(jQuery);

.gitignore

If you want that git is ignoring some files for you you just have to create the “.gitignore” file in your project root. Here you can add all the files you don’t want have in your git repository. For example some meta files from IntelliJ IDEA.

*.iml
*.ipr
*.iws
.idea/

jQuery Conference

I was the whole weekend on the jQuery conference in Mountain View by Microsoft. It was a nerdy weekend 🙂

I was suprised that Microsoft is hosting a conference like jQuery. But they do! Thank you! The Microsoft conference center is pretty cool. In the guarden there is beach volleyball place and a basketball place. The conference rooms are big and you have on every table power outlets for your Notebook.

It was funy to see so many MacBooks in a Microsoft building.

jQuery Conference
jQuery Conference

It was a good weekend. I meet some pretty smart guys and learned new stuff. It is always good to learn new stuff.

validateMonth

Das folgende JavaScript prüft beim verlassen eines Textfeldes, ob die Eingabe größer als 12 ist. Wenn das der Fall ist, dann wird das Textfeld auf 12 gesetzt.

function validateMonth(input){
  if (input.value > 12) {
    input.value = 12;
  }
}

aufgerufen wird das ganze wie folgt:

   <input type="text"   value=""   onblur="validateMonth(this)"   />

Avoid none number-keys

Das folgende JavaScript verhindert die Eingabe von Buchstaben und Sonderzahlen. Es lässt nur natürliche Zahlen als gültige Eingabe zu.

function isNumberKey(evt) {
  var charCode = (evt.which) ? evt.which : event.keyCode
  if (charCode > 31 &amp;&amp; (charCode < 48 || charCode > 57))
    return false;
  return true;
}

Es muss im onkeypress Attribut eines Textfeldes wie folgt aufgerufen werden:

  <input type="text"  value=""  onkeypress="return isNumberKey(event)"  />

Wenn es richtig eingebunden ist, dann nimmt das Textfeld nur natürliche Zahlen als Eingabe an. Andere Eingaben werden einfach ignoriert.

Uncheck all checkboxes

Das folgende JavaScript iteriert über alle checkboxen in einem Formular und deselektiert jedes einzelne von ihnen.

function uncheckAll(){
  for (i = 0; i < document.FormName.elements.length; i++){
    if ( document.FormName.elements[i].type = "checkbox" ){
      document.FormName.elements[i].checked = false;
    }
  }
}

Das entsprechende Formular in dem die Checkboxen liegen, sollte mit der ID “FormName” markiert sein. Wenn das Formular eine andere ID hat, dann muss dementsprechend die Funktion angepasst werden.

Das folgende Script iteriert über alle Formulare eines Dokumentes und über alle Checkboxen im jeweiligen Formular. Mit anderen Worten: Alle Checkboxen auf der Seite werden deselektiert.

function uncheckAll() {
  for (z = 0 ; z < document.forms.length; z++){
    for (i = 0 ; i < document.forms[z].elements.length; i++) {
      if ( document.forms[z].elements[i].type == "checkbox" ){
        document.forms[z].elements[i].checked = false;
      }
    }
  }
}

getCookieValue in JavaScript

Here is my version of “getCookieValue” in JavaScript:

function getCookieValue( name ) {
    var all_cookies = document.cookie.split( ';' );
    var cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    for ( i = 0; i &amp;lt; all_cookies.length; i++ ) {
        cookie = all_cookies[i].split( '=' );
        cookie_name = cookie[0].replace(/^\s+|\s+$/g, '');
        if ( cookie_name == name ) {
            cookie_value = unescape( cookie[1].replace(/^\s+|\s+$/g, '') );
            return cookie_value;
            break;
        }
        cookie = '';
        cookie_name = '';
    }
    return null;
}

AJAX

Note for me. AJAX Code.

 var http;

 function keepSessionOpen(){
    window.setTimeout('keepSessionOpen()', 1200000); // 1 200 000 = every 20 minutes
    var myurl = "#{statusBean.link}/page/status.xhtml";
    http = http.open("POST", myurl, true);
    http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    http.setRequestHeader("Connection", "Keep-Alive");
    http.onreadystatechange = useHttpResponse;
    http.send(null);
 }

 function getHTTPObject() {
    if (typeof XMLHttpRequest != 'undefined') {
        return new XMLHttpRequest();
    }
    try {
        return new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            return new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {
            alert(e);
        }
    }
    return false;
 }

function useHttpResponse() {
    if (http.readyState == 4 && this.status != 200) {
        alert(this.status);
    }
}