I'm very bad with Ajax and jquery and javascript in general and especially bad in Rails so forgive the obtuseness of this question.
I have a link in my Rails 4 app that I want it to execute a simple hide/show jquery code to hide or show a column based on a cookie value.
I'd like to do this without calling separate js or coffee scripts, but right when the link is clicked without reloading the page.
I've got all the Rails code working to write the cookie value and show or hide the column but by reloading the page, so now I'm trying to do with a bit less obtrusively via Ajax.
In the good ol' days before Rails I would do something like:
onclick='javascript: hideShow(this)'
Or something similar, can't quite remember the proper syntax.
How can I do this in the Rails world? I read somewhere that you can use a link_to
with a block but that throws an error.
My link looks like this:
= link_to "<span class='btn btn-sm btn-primary'>#{dogtag_icon}</span>".html_safe, users_flip_show_dogtag_path, title: icon_title, remote: true
I'm using SLIM templates so I tried creating a block like this:
= link_to "<span class='btn btn-sm btn-primary'>#{dogtag_icon}</span>".html_safe, users_flip_show_dogtag_path, title: icon_title, remote: true do
- dogtag_show_value = cookies[:show_library_dogtags].to_i
javascript:
if (#{dogtag_show_value} == 1) {
$('.dogTag').show();
} else {
$('.dogTag').hide();
}
Rails did not like that one bit.
I should also explain that the users_flip_show_dogtag_path
is important because it's the controller method where the cookie gets set to 0 or 1, I'd like to keep it so as to avoid writing that code in the view template.
If I ammend the link to something like this:
= link_to "<span class='btn btn-sm btn-primary'>#{dogtag_icon}</span>".html_safe do
It doesn't even appear in the view.
It would seem like such a simple thing to do yet I can't figure it out. Google searches have not proved useful.
Any help would be appreciated, thanks.
Edit:
Sorry for the double edit, wrong question
I'm using mccannf's answer and it seems to be working. Now I just need a way to set the visibility of the column on load based on the cookie value. I'm doing this in the viewer top but it doesn't work:
javascript:
if (#{@dogtag_show_value} == '1') {
$('.dogTag').show();
} else {
$('.dogTag').hide();
}
Thanks again.
Note: I solved the above by simply putting the code at the bottom of the page after the DOM element had been created. By having it at the top it was trying to execute before the DOM element existed. I know, stupid mistake!