Fede
Fede

Reputation: 1716

writing jquery with coffeescript

How do I write this on coffeescript? I can't get the second function.

$(document).ready(function() {  
        $('.box_container').hover(function(){   
            var width = $(this).outerWidth() / 2;  
            $(this).find('.left').animate({ right :0  },{queue:false,duration:300});  
            $(this).find('.right').animate({ left :0  },{queue:false,duration:300});  
        }, function(){  

            $(this).find('.left').animate({ right : width},{queue:false,duration:300});  
            $(this).find('.right').animate({ left : width},{queue:false,duration:300});  

        });  

});  

Upvotes: 0

Views: 3843

Answers (3)

kiddorails
kiddorails

Reputation: 13014

The traditional coffeescript for your mentioned code will look something like:

jQuery ->
  $('.box_container').hover ->
      width = $(@).outerWidth()/2
      $(@).find('.left').animate
        right: 0
       ,
        queue:false
        duration: 3000
      $(@).find('.right').animate
        left: 0
       ,
        queue:false
        duration: 3000

   ,
    ->
      $(@).find('.left').animate
        right: width
       ,
        queue: false
        duration: 3000
      $(@).find('.right').animate
        left: width
       ,
        queue: false
        duration: 3000

Here is the link with side-by-side JS view. I do understand that it looks very complicated than the original JS itself.

So, here goes the simplistic coffeescript with parens, this also denotes how second function can be incorporated.

jQuery ->
  $('.box_container').hover ->
      width = $(@).outerWidth()/2
      $(@).find('.left').animate({right: 0}, {queue:false, duration: 3000 });
      $(@).find('.right').animate({left: 0}, {queue:false, duration: 3000 });
   ,
    ->
      $(@).find('.left').animate({right: width}, {queue: false, duration: 3000});
      $(@).find('.right').animate({left: width}, {queue: false, duration: 3000});

Happy coffey-ing :)

Upvotes: 1

Alex Wayne
Alex Wayne

Reputation: 187004

Parens make this simpler.

$('.box_container').hover(
  ->
    # function one content
    doStuff()

  ->
    # function two content
    doMoreStuff()
)

Upvotes: 0

Ben McCormick
Ben McCormick

Reputation: 25718

$(document).ready ->
    arg1 = ->   
        width = $(this).outerWidth() / 2
        $(this).find('.left').animate { right :0  },{queue:false,duration:300}  
        $(this).find('.right').animate { left :0  },{queue:false,duration:300} 
    arg2 = ->
        $(this).find('.left').animate { right : width}, {queue:false,duration:300} 
        $(this).find('.right').animate { left : width}, {queue:false,duration:300}  

    $('.box_container').hover arg1, arg2

I would do it like this (I like to keep the parens for the jQuery functions because I think the chaining becomes unreadable without them)

Upvotes: 4

Related Questions