user1374796
user1374796

Reputation: 1582

Smooth css change transitions

I've setup a jQuery function that changes the body background colour when a certain div comes into view, e.g. the body background colour is black, when #block-three (that contains black text), the body background colour changes to white, and changes back when this goes out of view. This works fine, it's just very sudden though, I'm looking for a much smoother transition between background colours, fading between colours as you scroll (if possible).
jsFiddle demo: http://jsfiddle.net/neal_fletcher/TB53d/

HTML:

<div id="block-one" class="block">
    <div class="inner-block">Test</div>
    <div class="inner-block"></div>
    <div class="inner-block"></div>
</div>
<div id="block-two" class="block">
    <div class="inner-block">Test</div>
</div>
<div id="block-three" class="block">
    <div class="inner-block">Test</div>
    <div class="inner-block"></div>
</div>
<div id="block-four" class="block">
    <div class="inner-block">Test</div>
    <div class="inner-block"></div>
    <div class="inner-block"></div>
</div>
<div id="block-five" class="block">
    <div class="inner-block">Test</div>
    <div class="inner-block"></div>
    <div class="inner-block"></div>
</div>

jQuery:

var blockHeight = [];
$(".block").each(function () {
    blockHeight.push($(this).height());
});

function hoverCurrentItem() {
    var sIndex = 0;
    var totalHeight = 0;
    var scrolled = $(window).scrollTop();
    for (var i in blockHeight) {
        totalHeight += blockHeight[i];
        if (totalHeight > scrolled) {
            break;
        } else {
            sIndex++;
        }
    }

    var $sItem = $(".block").eq(sIndex);
    if (!$sItem.hasClass("selected")) {
        $(".selected").removeClass("selected");
        $sItem.addClass("selected");
    }
    if ($("#block-three").hasClass("selected")) {
        $("body").css("background-color", "white");
    } else {
        $("body").css("background-color", "black");
    }
}
hoverCurrentItem();

$(window).scroll(function (e) {
    hoverCurrentItem()
});

Any suggestions would be greatly appreciated!

Upvotes: 4

Views: 16198

Answers (1)

DaniP
DaniP

Reputation: 38262

You could use transition with CSS:

body {
    background-color: black;
    transition:all 1s;
}

The Demo Fiddle

Upvotes: 14

Related Questions