Wil Hoskins Wil Hoskins - 1 year ago 121
Javascript Question

Using javascript_tag to change page background color in rails

I'm creating an application to track player characters. I thought it would be cool to have the character's page's background change depending on the current percentage of its maximum health. I'm trying to use the 'javascript_tag' tag to change it dynamically.

Here is the code snippet from the show_html_erb file:

<% javascript_tag do %>
var perc = @character.getPercentHealth.to_json %>";
if (perc > .5) {
document.body.style.backgroundColor = "green";
}else if(perc > .25) {
document.body.style.backgroundColor = "yellow";
}else if(perc > 0){
document.body.style.backgroundColor = "red";
document.body.style.backgroundColor = "grey";
<% end %>

For additional reference, here is the getPercentHealth method from my character.rb file:

def getPercentHealth
perc = 0.00
perc = hitpoints / maxHP
return perc

It runs smoothly, but does not change the background color. Any suggestions?

Answer Source

You don't need to use JavaScript for that unless you want to? You can just do:

<% if @character.getPercentHeath > 5 %>
<body style="background-color: red;">
<% end %>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download