Eric Walley
Eric Walley

Reputation: 1

Change a css div or body background image based on current URL

The reason I need to do this is that the website I'm working on uses the exact same template to display dynamic content for multiple pages. All pages replicate the exact same div id's because they display the content the same way (except for the header content!). The header content shortens however the div id's still remain within the source code.

The blog index page needs to display 1 background image while every other page on the website displays another background image.

Thanks in advance for any help.

Upvotes: 0

Views: 3923

Answers (3)

Eric Walley
Eric Walley

Reputation: 1

This works:

<script language="javascript">
$(document).ready(function() {
if (window.location.href.indexOf('INDEX_URL') != -1) {
//Change background
$('#DIV_ID').css({'background-image': 'url(http://URL.com/images/BG.jpg)', 'background-repeat': 'repeat-x', 'background-position': 'center top', 'width': '100%!important', 'min-height': '400px'});
}
});
</script>

The flaw that this code has though is that if you insert a directory into "INDEX_URL" such as /folder/, any page after /folder/ will have that background.

Upvotes: 0

user8710
user8710

Reputation:

I often give the body class a name based on the template or request path. I know you said that they all use the same template, but that template takes params and one of the params should be

body_class

And whatever controller/dynamic thing you have populating your site and rendering the template, should pass in 'home' when you're at /. In my previous experience, I would pass in other things as well so that /blog/category/post might have a body class like

<body class="post two-column-a">

Then your selectors are something like:

body { ... }
body.home { ... }

Upvotes: 1

This snippet of code will do what you want:

if (window.location.href.indexOf('somepart_of_the_url') != -1) {
    //Change background to some div
    $('#somediv').css('backgroundImage','url(images/mybackgroundimage.jpg)');
    //Change background to page body
    $("document.body").css('backgroundImage','url(images/mybackgroundimage.jpg)');
}

Upvotes: 1

Related Questions