12장 자바스크립트와 jQuery 라이브러리 응용

응용 예제 12-1 입력 양식 포커스 자동 설정

414페이지

코드 12-1 autofocus.html
<!DOCTYPE html>
<html>
<head>
    <title>Event</title>
    <script>
        // 이벤트를 연결합니다.
        window.onload = function () {
            // 문서 객체를 선택합니다.
            var input_1 = document.querySelectorAll('input')[0];
            var input_2 = document.querySelectorAll('input')[1];
            // input_1
            input_1.onkeydown = function () {
                // 글자 개수가 여섯 개 이상일 경우
                if (6 <= input_1.value.length) {
                    // input_2 문서 객체로 초점을 이동합니다.
                    input_2.focus();
                }
            };
            // input_2
            input_2.onkeydown = function (event) {
                // 이벤트 객체를 추출합니다.
                var event = event || window.event;
                // 사용자의 입력이 '백 스페이스'이고 입력된 글자가 없는 경우
                if (event.keyCode == 8 && input_2.value.length == 0) {
                    input_1.focus();
                }
            };
        };
    </script>
</head>
<body>
    <input type="text" maxlength="6">
    <span>-</span>
    <input type="text" maxlength="7">
</body>
</html>

응용 예제 12-2 프레임 애니메이션

417페이지

코드 12-3 frameanimation.html
<!DOCTYPE html>
<html>
<head>
    <title>Frame Animation</title>
    <script>
        window.onload = function () {
            // 변수를 선언합니다.
            var count = 0;
            var image = document.getElementById('image');
            var frames = [
                '0.png', '1.png', '2.png', '3.png', '4.png',
                '5.png', '6.png', '7.png', '8.png', '9.png',
                '10.png', '11.png', '12.png', '13.png', '14.png',
            ];
            // 타이머 반복을 시작합니다.
            setInterval(function () {
                image.src = frames[count % frames.length];
                count = count + 1;
            }, 1000 / 20);
        };
    </script>
</head>
<body>
    <img id="image">
</body>
</html>

응용 예제 12-3 문서 객체 생성

420페이지

코드 12-5 jqueryCreateAppend_1.html
<!DOCTYPE html>
<html>
<head>
    <title>jQuery DOM</title>
    <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
    <script>
        // 이벤트를 연결합니다.
        $(document).ready(function () {
            // 10회 반복합니다.
            for (var i = 0; i < 10; i++) {
                // 문서 객체를 생성합니다.
                $('<h1>Create Document Object + ' + i + '</h1>').css({
                    backgroundColor: 'black',
                    color: 'red'  
                }).appendTo('body');
            }
        });
    </script>
</head>
<body>

</body>
</html>
코드 12-6 jqueryCreateAppend_2.html
<!DOCTYPE html>
<html>
<head>
    <title>jQuery DOM</title>
    <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
    <script>
        // 이벤트를 연결합니다.
        $(document).ready(function () {
            // 10회 반복합니다.
            for (var i = 0; i < 10; i++) {
                // 문서 객체를 생성합니다.
                var $dynamic = $('<h1>Create Document Object + ' + i + '</h1>').css({
                        backgroundColor: 'black',
                        color: 'red'
                    });
                
                // 문서 객체를 추가합니다.
                $('body').append($dynamic);
            }
        });
    </script>
</head>
<body>

</body>
</html>

응용 예제 12-4 무한 스크롤

425페이지

코드 12-7 infinityScroll.html
<!DOCTYPE html>
<html>
<head>
    <title>Infinity Scroll</title>
    <script src="https://code.jquery.com/jquery-3.1.0.js"> </script>
    <script>
        // 이벤트를 연결합니다.
        $(document).ready(function () {
            // 문서 객체 추가 함수
            var appendDocument = function () {
                for (var i = 0; i < 20; i++) {
                    // 문서 객체를 생성합니다.
                    $('<h1>Infinity Scroll</h1>').appendTo('body');
                }
            };
            // 초기에 문서 객체를 추가합니다.
            appendDocument();
            // 이벤트를 연결합니다.
            $(window).scroll(function () {
                // 변수를 선언합니다.
                var scrollHeight = $(window).scrollTop() + $(window).height();
                var documentHeight = $(document).height();
                // 검사합니다.
                if (scrollHeight == documentHeight) {
                    appendDocument();
                }
            });
        });
    </script>
</head>
<body>

</body>
</html>

스크롤을 내리면 계속해서 요소가 추가됩니다.

응용 예제 12-5 LightBox 플러그인 사용

427페이지

코드 12-9 lightbox.html
<!DOCTYPE html>
<html>
<head>
    <title>LightBox</title>
    <link rel="stylesheet" href="jquery.lightbox-0.5.css" / >
    <script src="https://code.jquery.com/jquery-3.1.0.js"> </script>
    <script src="jquery.lightbox-0.5.js"> </script>
    <script>
        // 이벤트를 연결합니다.
        $(document).ready(function () {
            $('a.light').lightBox();
        });
    </script>
</head>
<body>
    <a class="light" href="image1.jpg">LightBox</a>
    <a class="light" href="image2.jpg">LightBox</a>
    <a class="light" href="image3.jpg">LightBox</a>
</body>
</html>

응용 예제 12-6 Masonry 플러그인 사용

430페이지

코드 12-10 jqueryMasonry.html
<!DOCTYPE html>
<html>
<head>
    <title>Masonry</title>
    <style>
        * { margin: 0; padding: 0; }
        .box { 
            background: black;
            margin: 5px;
        }
    </style>
    <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
    <script src="https://masonry.desandro.com/masonry.pkgd.min.js"></script>
    <script>
        // 이벤트를 연결합니다.
        $(document).ready(function () {
            // 문서 객체를 생성합니다.
            for (var i = 0; i < 100; i++) {
                $('<div></div>').addClass('box').css({
                    width: 100,
                    height: Math.floor(Math.random() * 100) + 50
                }).appendTo('body');
            }

            // Masonry 플러그인을 적용합니다.
            $('body').masonry({
                columnWidth: 110
            });
        });
    </script>
</head>
<body>

</body>
</html>

응용 예제 12-7 jQuery 라이브러리를 사용한 갤러리 구현

433페이지

코드 12-17 gallery.html
<!DOCTYPE html>
<html>
<head>
    <title>Slider</title>
    <style>
        div.item:nth-child(1) { background: blueviolet; }
        div.item:nth-child(2) { background: pink; }
        div.item:nth-child(3) { background-color: burlywood; }
    </style>
    <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
    <script>
        $(document).ready(function () {
            // 변수를 선언합니다.
            var width = $('[data-role="slider"]').attr('data-width');
            var height = $('[data-role="slider"]').attr('data-height');
            var count = $('[data-role="slider"] div.item').length;
            
            // 스타일을 적용합니다.
            $('[data-role="slider"]').css({
                position: 'relative',
                overflow: 'hidden',
                width: width,
                height: height
            }).find('.container').css({
                position: 'absolute',
                width: count * width,
                overflow: 'hidden'
            }).find('.item').css({
                width: width,
                height: height,
                float: 'left'
            });
            // 변수를 선언합니다.
            var currentPage = 0;
            var changePage = function () {
                $('[data-role="slider"] > .container').animate({
                    left: -currentPage * width
                }, 500);
            };
            // 이벤트를 연결합니다.
            $('#left-button').click(function () {
                if (currentPage > 0) {
                    // 왼쪽으로 이동
                    currentPage = currentPage - 1;
                    changePage();
                }
            });
            $('#right-button').click(function () {
                if (currentPage < count - 1) {
                    // 오른쪽으로 이동
                    currentPage = currentPage + 1;
                    changePage();
                }
            });
        });
    </script>
</head>
<body>
    <div data-role="slider" data-width="500" data-height="300">
        <div class="container">
            <div class="item">
                <h1>Lorem ipsum dolor sit amet</h1>
                <p>Lorem ipsum dolor sit amet, consectetur </p>
            </div>
            <div class="item">
                <h1>Proin in urna turpis.</h1>
                <p>Lorem ipsum dolor sit amet, consectetur </p>
            </div>
            <div class="item">
                <h1>Duis malesuada lorem neque.</h1>
                <p>Lorem ipsum dolor sit amet, consectetur </p>
            </div>
        </div>
    </div>
    <button id="left-button"></button>
    <button id="right-button"></button>
</body>
</html>