vendredi 29 septembre 2017

jquery click conditional statement based on selector top position

I am attempting to create my very first jQuery post slider.

The slider has previous and next buttons which offset the top position of the div containing all the post items. ie. increments or decrements the top position value by the '.post-item' height.

I am facing difficulty with a conditional statement to disable the previous and next buttons based on the value of the CSS top property of the div. For example, disable previous button if top position > 0

I am new to programming and I was hoping to learn by others examples pertaining to my situation, to better grasp the concepts. Any help and guidance on how to best achieve this would be a huge help for me. At the bottom of the post I have included my rather embarrassing progress on one of my attempts.

JavaScript Source

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

        $('.prev-btn').click(function () {
                $(".posts-body").animate({
                    top: "+=142"
                }, {"duration": 400, "easing": "easeOutBack"});

        });

        $('.next-btn').click(function () {
            $(".posts-body").animate({
                top: "-=142"
            }, {"duration": 400, "easing": "easeOutBack"});
        });
    });
})(jQuery);

HTML Markup

<div class="buttons">
    <span class="prev-btn ">Up</span>
    <span class="next-btn ">Down</span>
</div>
<div class="post-slider">
    <div class="posts-body">
        <div class="post-item">
            <h1>Placeholder Text</h1>
        </div>
        <div class="post-item">
            <h1>Placeholder Text</h1>
        </div>
        <div class="post-item">
            <h1>Placeholder Text</h1>
        </div>
        <div class="post-item">
            <h1>Placeholder Text</h1>
        </div>
    </div>
</div>

Failed Attempt

(function ($) {
        $(document).ready(function () {
            $('.prev-btn').click(function () {
                var selector = document.querySelector(".posts-body");
                var offset = selector.offsetTop;

                if (selector.css("top") > 0) {
                    $(".posts-body").animate({
                        top: "+=142"
                    }, {"duration": 400, "easing": "easeOutBack"});
                }
                console.log(offset);

            });

            $('.next-btn').click(function () {

                var selector = document.querySelector(".posts-body");
                var offset = selector.offsetTop;

                $(".posts-body").animate({
                    top: "-=142"
                }, {"duration": 400, "easing": "easeOutBack"});

                console.log(offset);
            });
        });
    })(jQuery);

Thanking you very much for your time and help.

Aucun commentaire:

Enregistrer un commentaire