WillSquire
9/16/2015 - 4:07 PM

Carousel (ES6)

Carousel (ES6)

import $ from './jquery-2.1.4.min.js';
import {Carousel} from './carousel.js';

$(document).ready(function() {
    "use strict";

    new Carousel('slide-left', 'slide-right', 'carousel-container');
});
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="stylesheet" href="assets/distribution/css/app.min.css">
    <script src="assets/distribution/js/app.min.js"></script>
</head>
<body>
<button type="button" id="slide-left">Left</button>
<button type="button" id="slide-right">Right</button>
<div class="carousel">
    <div id="carousel-container">
        <img src="assets/distribution/img/cats-animals-kittens-background.jpg" alt="Kitten">
        <img src="assets/distribution/img/header-kittens.jpg" alt="Kitten">
        <img src="assets/distribution/img/kitten-2.jpg" alt="Kitten">
        <img src="assets/distribution/img/kitten-smiling-1280x1024.jpg" alt="Kitten">
    </div>
</div>
</body>
</html>
export class Carousel {

    constructor(left_button_id, right_button_id, container_id) {
        "use strict";

        // Variables
        this.left_button =  document.getElementById(left_button_id);
        this.right_button = document.getElementById(right_button_id);
        this.carousel_container = document.getElementById(container_id);
        this.carousel_images = this.carousel_container.children;
        this.carousel_image_index = 0;

        this.carousel_container.style.marginLeft = '0px';

        // Event listeners
        this.left_button.addEventListener("click", this.slide_left.bind(this));
        this.right_button.addEventListener("click", this.slide_right.bind(this));
    }

    slide_left() {
        "use strict";

        if (this.carousel_image_index > 0) {

            this.carousel_image_index -= 1;
            this.position = -this.carousel_images[this.carousel_image_index].offsetLeft;
            this.carousel_container.style.marginLeft = this.position + 'px';

        }

    }

    slide_right() {
        "use strict";

        if ((this.carousel_image_index + 1) < this.carousel_images.length) {

            this.carousel_image_index += 1;
            this.position = -this.carousel_images[this.carousel_image_index].offsetLeft;
            this.carousel_container.style.marginLeft = this.position + 'px';

        }

    }

}