简体   繁体   中英

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";
    }else{
        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
end

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

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 %>

The above solution is nice in that it uses css only. However, ideally, css is separated from html and as much as possible logic is abstracted from view files. To make this cleaner, I would be inclined to create a helper method which is passed the percentage health variable and returns a className eg

helper_file.rb

def health(percentage)
  case percentage
    when > 0.5
      "goodHealth"
    when > 0.25
      "mediocreHealth"
    when > 0
      "poorHealth"
    else
      ""
  end 
end

view.erb

<body class="<%=health(percentage) %>">

styles.css

.illHealth {background-color: red;}
.mediocreHealth {background-color: yellow;}
.goodHealth {background-color: green;}
.noHealth {background-color: grey;}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM