Norto23
Norto23

Reputation: 2269

replace css header image dynamically

I have a css based layout with a generic header image at the top of the page in my Rails app. There is a Course model will have a optional logo image which will hopefully replace the header image if it is present, when a user is viewing the course material. Is this possible and how do I go about it?

The css for the header is below...

#header{height:116px;width:100%;background:url('logo.jpg') top center no-repeat;}

The app is located at ... and when the user logs in, and clicks on a course, I want the course logo to replace the header image.

Upvotes: 1

Views: 976

Answers (3)

Arsen7
Arsen7

Reputation: 12830

If I understood your problem correctly, some model defines a logo. In such case I would not mess with CSS - or at least not with assets files, because they are expected to be static.

You may define the logo in the layout: app/viev/layouts/application.html.erb Just create there something like this:

<head>
  ..
  <style type="text/css">
    #header { background-image: url("<%= @logo_path || 'logo.jpg' %>"); }
  </style>

or

<head>
  <% if @logo_path %>
    <style type="text/css"> #header { .... } </style>
  <% end %>

Then, in some controllers or actions or some views, just set the instance variable @logo_path if you want to have the logo different from the default.

In your static CSS you may define the default background-image, and just make sure that this rule from your layout has bigger importance than the rule from your static assets. If in doubt, add !important clause to the rule in layout.

Of course, if talking about dynamically you mean JavaScript, then you may just include the script and the logo path directly in an onclick attribute of given element, in a way similar to this:

<span onclick="replace_logo('<%= model.logo_path %>')">....</span>

The function replace_logo will not be difficult to write.

Upvotes: 1

Danish M.
Danish M.

Reputation: 997

I would just include that small specific portion of css in my main code and use a simple if...else statement, and change 'logo.jpg' depending on whether the user is logged in or not.

For example, if the user is logged in, the variable for the logo would be changed from the default value. If the user isn't logged in, then use the original logo.

Can't really provide more detail as there is no code to work with.

Upvotes: 0

Yuri  Barbashov
Yuri Barbashov

Reputation: 5437

u can do in two ways by defining different classes for each images u want to show in header and then change claa depends on some variable(controller or action name ...etc) or by adding yield :style in head and overwriting header style depends on your requirements by using content_for :style.

Upvotes: 0

Related Questions