Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write this coffeescript so it doesn't refresh my page?

This is my first Coffeescript function and can't figure out how to get this to not refresh my page after the user clicks and the event is fired:

jQuery ->
  $(".answer_link").click -> 
    $val = $(this).attr 'id'
    $id = $val.replace(/answer_link_/, '')
    $input = "#new_answer_" + $id
    $($input).toggle 'slow'

Thanks!

like image 726
Inc1982 Avatar asked Feb 02 '12 13:02

Inc1982


People also ask

How do you write a function in CoffeeScript?

To define a function here, we have to use a thin arrow (->). Behind the scenes, the CoffeeScript compiler converts the arrow in to the function definition in JavaScript as shown below. (function() {}); It is not mandatory to use the return keyword in CoffeeScript.

How do I use CoffeeScript in HTML?

You simple need to add a <script type="text/coffeescript" src="app. coffee"></script> to execute coffee script code in an HTML file. In other cases, I've seen people use the attributes of type="coffeescript" and type="coffee" , so they might work for you as well. Save this answer.

Should you use CoffeeScript?

CoffeeScript is something that makes even good JavaScript code better. CoffeeScript compiled code can do everything that natively written JavaScript code can, only the code produced by using CoffeeScript is way shorter, and much easier to read.


1 Answers

I think this is a question about jQuery or JavaScript. you can use .preventDefault() to do this:

jQuery ->
  $(".answer_link").click (event)->

    #like this
    event.preventDefault()

    $val = $(this).attr 'id'
    $id = $val.replace(/answer_link_/, '')
    $input = "#new_answer_" + $id
    $($input).toggle 'slow'

more info about preventDefault.

like image 156
island205 Avatar answered Sep 28 '22 00:09

island205