0

If i have a background image defined as:

#header
{
    width: 100%;
    background: url(/Content/images/header.jpg) -0 0 no-repeat;
}

and i want to overwrite that after the page loads. Shouldn't this code work?

$("#header").css('background-image', '/Content/images/aff/header_<%=affiliateID%>.jpg')

EDIT: As stated, the script needs to run after the page loads...and here's where things get slightly complicated. It's an MVC app...this code sits in the masterpage but is nested down inside a 'RenderPartial' control: [on my.Master]

 <% Html.RenderPartial("showLoginStatus"); %>

Then within that showLoginStatus.ascx control is:

<script type="text/javascript">
$(document).ready(function(){
    $("#header").css('background-image', '/Content/images/aff/header_<%=affiliateID%>.jpg')
    alert('this');
}
</script>

when adding the 'document.ready' wrapper, the altert never fires. So something related to when that control is rendered is mucking things up. My changed background is probably processed....it's just re-written because it exists in the stylesheet. (all i have to do is remove it from there?) [scurries off to try that]

justSteve
  • 5,444
  • 19
  • 72
  • 137
  • 1
    Check this out: http://stackoverflow.com/questions/253689/switching-div-background-image-with-jquery and http://jquery-howto.blogspot.com/2009/08/can-set-change-css-background-image.html – Jason Evans Jun 18 '10 at 14:19

2 Answers2

2

You need to do it after page load and thats made with:

$(document).ready(function(){
  $("#header").css('background-image', 'url(/Content/images/aff/header_<%=affiliateID%>.jpg)');
});
Marks
  • 3,613
  • 5
  • 31
  • 46
  • Ok...seems obvious and i'm betting this is where my fail traces to. However....when i place the '.ready' bit in, the alert no longer fires. So complete details in my edited question. – justSteve Jun 18 '10 at 15:36
  • Dont know if you fixed already, but seems like you just forgot the semikolon at the end of the css() method. besides of this, it should work. – Marks Jun 21 '10 at 08:25
0

Use this

$(document).ready(function(){
    $("#header").css('background', 'url(/Content/images/aff/header_<%=affiliateID%>.jpg) no-repeat');
});

You also have to add "no-repeat".

It you need to use multiple styles, try this:

$(document).ready(function(){
    $("#header").css({
      'width':'50%',
     'background':'url(/Content/images/aff/header_<%=affiliateID%>.jpg) no-repeat'
  });
});
Happy
  • 881
  • 7
  • 16
  • 32