Pergunta

I've managed to finally get this code working, which fades divs in and out based on the hashtag in the URL and whether the divs touch the top or bottom of the window. The jQuery looks like this:

var distanceFromTop = $(window).scrollTop(),
    distanceFromBottom = $(window).scrollTop() + $(window).height();

var divOneFromTop = $("#div-one").offset().top,
    divOneFromBottom = divOneFromTop + $("#div-one").height();

if (window.location.hash == "#div-one" && distanceFromTop >= divOneFromTop && !(distanceFromBottom > divOneFromBottom)) {
    $(".div-one-info").fadeIn(300);
} else {
    $(".div-one-info").fadeOut(300);
}

var divTwoFromTop = $("#div-two").offset().top,
    divTwoFromBottom = divTwoFromTop + $("#div-two").height();

if (window.location.hash == "#div-two" && distanceFromTop >= divTwoFromTop && !(distanceFromBottom > divTwoFromBottom)) {
    $(".div-two-info").fadeIn(300);
} else {
    $(".div-two-info").fadeOut(300);
}

The thing is that I need around eight more divs and I'm repeating myself a ridiculous amount of time. Does anybody have an idea about how I could slim this down and make ita little more "automated", so I don't have to write, #div-one and divOne etc. all the time?

Foi útil?

Solução

Something like the following:

var id = window.location.hash;

var divFromTop = $(id).offset().top,
    divFromBottom = divFromTop + $(id).height();

if (distanceFromTop >= divFromTop && !(distanceFromBottom > divFromBottom)) {
    $(id.replace("#", ".") + "-info").fadeIn(300);
} else {
    $(id.replace("#", ".") + "-info").fadeOut(300);
}

You could probably make this a little more readable but the basic idea is that you use the document location hash to identify the necessary elements.

Outras dicas

You can use attribute starts with selector to iterate through your div, get the id and compare with the location hash:

$.each($('[id^="div-"]'), function () {
    var id = $(this).attr('id'),
        divOneFromTop = $(this).offset().top,
        divOneFromBottom = divOneFromTop + $(this).height();

    if (window.location.hash == "#" + id && distanceFromTop >= divOneFromTop && !(distanceFromBottom > divOneFromBottom)) {
        $("." + id + "-info").fadeIn(300);
    } else {
        $("." + id + "-info").fadeOut(300);
    }
});
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top