2
\$\begingroup\$

I am using class "active" to keep track on which child to fade in and fade out in my gallery. Are there any other, better options for doing this?

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
#div_with_children{margin:0 auto;width:960px;height:499px;overflow:hidden}
.child{width:960px;height:500px}
</style>
</head>
<body>
<div id="div_with_children">
<div class="child" style="background:#0C3">1</div>
<div class="child" style="background:#993">2</div>
<div class="child" style="background:#F63">3</div>
<div class="child" style="background:#FC0">4</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
(function ($) {
    $.fn.bildspel_fade = function () {
        var $t = this,
            $c = $t.children(),
            $c0 = $c.eq(0),
            $c1 = $c.eq(-1),
            n = function () {
                var i = $t.children('.active').index(),
                    i1 = i + 1;
                $c.css('position', 'absolute');
                if ($c1.hasClass("active")) { // om man ÄR på sista
                    $c1.fadeOut(1000).removeClass('active');
                    $c0.addClass('active').fadeIn(1000);
                }
                else { // om man INTE ÄR på sista
                    $t.find('.active').fadeOut(1000).removeClass('active').next().addClass('active').fadeIn(1000);
                }
            };
        setInterval(n, 6000);
        $c.hide();
        $c0.addClass('active').fadeIn(1000);
    };
})(jQuery);
$(window).load(function () {
    $('#div_with_children').bildspel_fade();
});
</script>
</body>
</html>
\$\endgroup\$
1
\$\begingroup\$

Maybe using jQuery's $.data() to store a bool variable or something like that.

Also you could store a global variable with the active position (e.g. "3" for the 3rd item in the gallery), and then change it, using it along with the :eq() selector.

Either way, I think that the .active class approach is very useful because it gives you the chance to alter the CSS properties for that specific item on your gallery.

|improve this answer|||||
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.