Setting dynamic css-background image in wordpress post [jQuery]

I have a site based on wordpress and I want to change the header image for every single post. As every post has its own ‘id’, I want to make a jquery function which would read the post ‘id’ (for example id=”post-8″) and would set a background image named the same way, so I just have to make a new image and upload it everytime I write a new post, and no css changes would be needed.

I have very bare idea of jquery, but my bro’s help I got the following code:

Read More
var txt1 = "post-";
        for (var i=0; i<1000; i++){
        var elementId = txt1.concat(i);
        var postimg1 = "url(../images/";
        var postimg2 = ".jpg)";
        var postimgfull = postimg1 + elementId + postimg2;
        var element =  $("#" + elementId);
        if (element != null) {
            $(".posthead").css('background-image', postimgfull);
        }else {
            break;
        }

But using that I don’t get the image named “post-8.jpg”, what I get is an image named “post-999.jpg”.

Can you help me here?

Thankyou mates!

Related posts

Leave a Reply

1 comment

  1. I guess everything goes fine in your code except there should be

    element.css('background-image', postimgfull);

    in stead of

    $(".posthead").css('background-image', postimgfull);

    and it should be good to go.