Saturday, February 23, 2013

CoffeeScript and JQuery

Writing JQuery code with CoffeeScript was bit of a Challenge for me. I sort of had to unlearn my previous coding habits so not to make my CoffeeScript look like JavaScript. With me its more of a coding style problem but overall writing DOM manipulation code with CoffeeScript (with JQuery) is more pleasant that I expected. It's certainly shorter.

Let's start with the HTML doc that we will be playing with.

<html>  
   <head>  
     <title></title>  
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
     <link href="css/mystyle.css" rel="stylesheet">  
     <script src="js/jquery-1.9.1.js" type="text/javascript"></script>  
     <script src="js/Control.js" type="text/javascript"></script>  
   </head>  
   <body>  
     <div id="hoverElem">Hover over <a href="#" id="target">this</a> to show message</div>  
     <div id="message" class="hidden">I be rollin' with CoffeeScript and   
     they be hatin'!</div>  
   </body>  
 </html>   

It's quite easy to figure out what I'm trying to do here. I have a target "this" when you hover over it, it shows some kind of message.

The CSS is also quite simple.

root { 
    display: block;
}

#message{
    border: 1px solid #9966cc;
    margin: 10px;
    padding: 10px;
    text-align: center;
}

.hidden{
    display: none;
}

The real work is again done with our CoffeScript file.

$ ->
  $('#target').mouseover (e) -> $('#message').removeClass 'hidden' 
    
  $('#target').mouseout (e) -> $('#message').addClass 'hidden'

The first line "$ ->" is equivalent to the document.ready() or $.function() for JQuery. The next two lines are where the work is done. The syntax is quite compact to handle a mouseover and mouseout events. The (e) element is the event parameter. The arrow part leads to inside of the function with the removeClass and addClass methods.

The sample here is quite trivial but it does show the basics of using CoffeeScript with JQuery. A couple of more weeks (or months) of puttering around with it I think I can get pretty good with CoffeeScript and another popular JavaScript libraries like underscore, knockout or maybe gmap.

Can't wait to try this out with a real project. Let's see if Odesk got some. *grin*