Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 and unobtrusive javascript

I've got a problem with linking unobtrusive js file with view.

I've got view named index.html.erb

...
<div id="fooBar">say bye!</div>
...

Also I've got js file index.js.erb

$("#fooBar").html("say hello!")

Currently I get say bye message, because javascript file are not executed.

What I'm doing wrong?

It seems to me that js.erb is not used for that purpose. And i just need to add script reference on normal .js file where view specific client logic is held

Thanks, Alexey

like image 749
Alexey Zakharov Avatar asked Feb 04 '26 23:02

Alexey Zakharov


2 Answers

Did you specify a render_with :js in your controller?

Unfortunately, the way you have it scripted there won't really work. You can only render one thing html or js. With Rails UJS when you click show (for example) it decides based on if you have JS to render dynamically or to render it with HTML. You can't render two things at once.

Try this: http://www.simonecarletti.com/blog/2010/06/unobtrusive-javascript-in-rails-3/

like image 96
maletor Avatar answered Feb 08 '26 00:02

maletor


Are you doing it after the element or the document loads?

Try

$(function() {
    $("#fooBar").html("say hello!")
});

assuming you are using jQuery which appears to be the case.

like image 39
Anurag Avatar answered Feb 08 '26 02:02

Anurag