Javascript conditionals in RJS

Something you can’t seem to do in RJS is to do conditional checking with the client side DOM.

For example, I want to be able to investigate an element to see if it has the CSS display tag set to none. The solution is to blend javascript and RJS together.

To do this you append the javascript as a string to the page object like this:

# Javascript check to see if the element is visible
page << "if ($('div_element').style.display == 'none') {" 
# Wow - this is like being in a PROPER if statement!
# RJS stuff to make the element visible 
page.replace_html 'div_element', :partial => 'some_partial' 
page['div_element'].visual_effect :blind_down 
# back to javascript 
page << '}' 

Thanks to Rails Casts for that particular little tidbit!

Subscribe via RSS

Back to all blog posts