allegutta
allegutta

Reputation: 5644

How to change CSS (background-image) from JQuery in Rails?

I am trying to change the background image in the body tag in my Rails app. I have tried it from items.js.coffee (I have table called items) and from application.js. I cant make it work from either.

I have tried to change the background color, and thats working from application.js but not from items.js.coffee.

So my question is: How can I change the background image and must all changes in CSS be done from application.js?

items.js.coffee:

$ ->
    $(document).ready ->
        if something
            $("body").css "background-image", "url(rails.png)"

bootstrap_and_overrides.css.less:

body { 
    padding-top: 60px;
    background-color: black;
    background-image:url('HypeTrans.png');
    background-repeat:no-repeat;
    background-attachment:fixed;
    background-position: 50% 50%;
}

Upvotes: 2

Views: 4691

Answers (3)

lukerandall
lukerandall

Reputation: 2212

It seems that the most likely explanation is that you are not including the items.js file in your layout or application.js if you're using the asset pipeline.

In development mode, view the source of the rendered page* and confirm that items.js is being included on the page. If it is not, and assuming you are using Rails 3.1+ - I'd suggest you review the Asset Pipeline Rails Guide to see how to add files to your manifest.

  • I suggest this as it should work whether or not you are using the asset pipeline, as in development mode files in your application.js manifest are included individually.

Update

Related to this, is the fact that if you are referring to assets served from the asset pipeline, they will appear under /assets, so your code should be

$("body").css "background-image", "url('/assets/rails.png')"

Upvotes: 3

Richlewis
Richlewis

Reputation: 15374

Why dont you just change background-image to background in the

bootstrap_and_overrides.css.less

so make it look like this

body { 
padding-top: 60px;
background-color: black;
background:url('HypeTrans.png');
background-repeat:no-repeat;
background-attachment:fixed;
background-position: 50% 50%;

}

Upvotes: 0

The Mechanic
The Mechanic

Reputation: 2329

i m showing you one of the way to write css code in javascript so you can try this

$(function(){
    if(something){
        $("body").css({
            'background-image':'url(path of the image)'
        })
    }
})

in this way you can write css

Upvotes: 0

Related Questions