13

I would like to invoke a javascript function (without JQuery) when the onclick even fires from a link_to tag in haml. How can I do this?

Sandah Aung
  • 6,156
  • 15
  • 56
  • 98

4 Answers4

21

Here’s how to do it using Rails link_to in haml:

= link_to "my link", "", :onclick => "my_function(); return false"
edouardbriere
  • 1,170
  • 8
  • 12
  • This answer was more helpful. – rcd Sep 24 '13 at 16:04
  • @YuraVasylenko the (); executes the function. my_function without is "Hey, i'm a function"... with (); "Hey i'm a function execute me". You could pass my_function as a parameter (pass the whole function) if you pass my_function(); you pass the result of executing the function – slindsey3000 Jun 17 '16 at 15:59
13

I think this could work:

link_to "your link", href, :onclick => "jsFunction"

Or, doing everything JS side:

document.body.addEventListener('click',function(e)
{
    var target = e.target || e.srcElement;
    if (target.tagName.toLowerCase() !== 'a')
    {
        return e;//not clicked on link
    }
    //a link was clicked, maybe check class or id or other stuff to narrow it down
    //if a link you were interested in was clicked:
    return theClickFunction.apply(target,[e]);
},false);
Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
9

The pure HAML equivalent to @edouardbriere's answer:

%a{href: '#', onclick: 'my_function(); return false;'} my link
Felix Livni
  • 1,164
  • 13
  • 24
-3
<a onclick="YOURMETHOD;"/>A link</a>

if you would also like to prevent the location change add return false after your method call.

AMember
  • 3,037
  • 2
  • 33
  • 64