leonidus
leonidus

Reputation: 103

How can I change the background of a div with jQuery?

This is the situation:

I have a blog with several posts. Each post has images inside of it. With jQuery I am alreay wrapping the first image of each post so I can give it a unique styling.

Next to the styling I would also like to grab the first image of a post and use it as the header. The header already has a background so it should be replaced by, indeed, the first image of a post.

if ($("body").is("#permalink") && $(".imgwrapper").length>0) {
var firstImage = $(".imgwrapper").attr('src')
  $('#header-bg').css('background-image', "url(" + firstImage + ")")

}

Somehow the above code is not working and is giving me the following error in the console: resource interpreted as image but transferred with mime type text/html

Your help is much appreciated!

Upvotes: 0

Views: 81

Answers (5)

leonidus
leonidus

Reputation: 103

Solved it, Still thanks for all the help and thinking along! This worked:

if ($("body").is("#permalink") && $(".imgwrapper").length>0) {
  var firstImage = $(".imgwrapper img").attr('src')
  $('#header-bg').css('background-image', "url(" + firstImage + ")")

}

The mistake I made here was that I did not target the image but the wrapper only.

Upvotes: 0

M.G.Manikandan
M.G.Manikandan

Reputation: 993

Can you check the value of firstImage. If the URL returned as expected by you. There is nothing wrong in the code.

"resource interpreted as image but transferred with mime type text/html"

The Content-Type (response header) is set as text/html for the image URL (firstName). But, as we include that url in background image, browser expects the URL to return an image (content-type: image/*).

Browser will automatically interpret and display it as image. If you got broken image, open the image url in new tab and check the content. It might return some HTML content itself.

Upvotes: 1

smoore4
smoore4

Reputation: 4866

Something like this works:

http://jsfiddle.net/9Zk8G/

HTML

<div class="imgwrapper">
<img src="" />
</div>

JS

var firstImage="http://cdn-careers.sstatic.net/careers/gethired/img/3478c54721cd466fb6f7d3afe16e97d4.gif";  
$( "<img/>" ).attr( "src", firstImage ).appendTo( ".imgwrapper" );

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337560

You don't need the url() part in the css property. Try this:

if ($("body").is("#permalink") && $(".imgwrapper").length > 0) {
    $('#header-bg').css('background-image', $(".imgwrapper").attr('src'))
}

Upvotes: 0

MACMAN
MACMAN

Reputation: 1971

if ($("body").is("#permalink") && $(".imgwrapper").length>0) {
var firstImage = $(".imgwrapper").attr('src');
$('#header-bg').css('background-image', "url(" + firstImage + ")");

}

Is that because you are missing ";"

Upvotes: 0

Related Questions