warm__tape
warm__tape

Reputation: 80

Set background image of parent div based on attribute of child div on mouseover

For some reason this doesn't want to work for me. I've got the below code.

When hovering over the homeShowingWrapper div, the background of the homeHero div should change to the value of the data-featured-image attribute of the homeShowingWrapper div.

Here's my HTML structure:

<div id="homeHero">
    <div class="homeShowingWrapper" data-featured-image="/uploads/Hover-Background.jpg">
        Content
    </div>
</div>

And my JQuery function:

jQuery( document ).ready( function( $ ) {

    $("#homeHero").css("background-image" , "url(/uploads/Initial-Background.jpg);");

    $(".homeShowingWrapper").mouseover(function() {

        // Background-image
        var background = $(this).attr('data-featured-image');

        $("#homeHero").css("background-image" , "url(" + background + ");");

    });

});

Any idea why the $("#homeHero").css("background-image" , "url(" + background + ");"); line doesn't apply the background image?

Upvotes: 0

Views: 141

Answers (1)

Jeramiah Harland
Jeramiah Harland

Reputation: 864

As Nawed Khan mentioned in the comments, the correct way of reading the data attribute is with data().

I set up a jsFiddle to troubleshoot and found that, not only did I need to use data('featured-image'), but the semi-colon in the jQuery .css() needs to be omitted for it to work.

Upvotes: 2

Related Questions