How to change this javascript to coffeescript?
$(document).ready(function(){
$('a[href^="#"]').on('click',function (e) {
e.preventDefault();
var target = this.hash;
var $target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});
I tried this code in my rails project,but it doesn't work
$(document).on 'page:change', ->
$('a[href^="#"]').click (event) ->
event.preventDefault()
target = this.hash
$target = $(target)
$('html, body').stop().animate{
'scrollTop': $target.offset().top
}, 900,
'swing', ->
window.location.hash = target
Do I have something wrong?
1 Answer 1
I think this will work:
$(document).ready ()=>
$('a[href^="#"]').on 'click', (e)=>
e.preventDefault()
target = @hash
$target = $(target)
$('html, body').stop().animate scrollTop:$target.offset().top, 900, 'swing', ()=>
window.location.hash = target
You asked if you've did something wrong, so here's a couple of things to keep in mind (sorry if this is obvious to you already):
The first line of your CoffeeScript version is completely different than the JavaScript version. (
document.readyvs.document.on('page-change'))CoffeeScript is whitespace-sensitive. I don't know if its just the StackOverflow formatting or in your actual code, but without leading spaces in your second line, the callback passed to
$(document).on 'page:change', ->is a no-op. In other words, the Javascript version would be$(document).on('page:change', function(){});Similarly, the spaces that indent lines 9 (the one that starts with
'scrollTop') and 11 (the one that starts with'swing') are likely to cause problems also.
Comments
Explore related questions
See similar questions with these tags.
returnstatements at the end of each block. But yes, online JS to CoffeeScript converters are your friend.$(document).on('page:change', function() {}); // ..instead$(document).on('page:change', function() { //... Second mistake is hereanimate{- lost whitespace again. Remember that сoffee uses significant whitespace to delimit blocks of code.