# 캐러셀(carousel) 만들기

{% embed url="<https://www.instagram.com/p/CgR7vVBIplk/?utm_source=ig_embed&ig_rid=a74342d3-00d2-41c6-b839-c3c51376bd06>" %}
캐러셀 대표적 예시 (instagram)
{% endembed %}

그럼 이미지 3장으로 간단한 캐러셀을 만들어보자.

<figure><img src="https://3814826491-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJyHOwztPxBT3bLpisjCt%2Fuploads%2FY6d35nA6eqLvXHjyJG5r%2F%EC%BA%90%EB%9F%AC%EC%85%80.gif?alt=media&#x26;token=ba606d29-9af6-4aad-99be-936307d8e186" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3814826491-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJyHOwztPxBT3bLpisjCt%2Fuploads%2FZmtaJXbcOB513NghvOE5%2FScreenshot_1.png?alt=media&#x26;token=a5e811da-0a37-4764-9eab-aef6dc34acf8" alt=""><figcaption></figcaption></figure>

이미지를 이런식으로 배치하고 버튼을 눌렀을 때 다른 이미지를 슬라이드 해주면 되겠다.

{% code title="js010.html" %}

```html
<div class="slide-container">
    <div class="slide-box">
      <img src="img/color1.png">
    </div>
    <div class="slide-box">
      <img src="img/color2.png">
    </div>
    <div class="slide-box">
      <img src="img/color3.png">
    </div>
</div>
```

{% endcode %}

{% code title="main.css" %}

```css

.slide-container {
    width: 300vw;
    transition: all 1s;
}

.slide-box {
    width: 100vw;
    float: left;
}
.slide-box img{
    width: 100%;
}
```

{% endcode %}

이렇게 하면 아래 스크롤 생김

slide-container 를 div로 감싸고 스타일을 주면&#x20;

이미지 3개가 가로로 배치되고 나머지 2개의 이미지는 감춰진다.

```
<div style="overflow: hidden"> </div>
```

이렇게 하고 버튼을 누를 때마다&#x20;

slide-container css에 아래 속성 중 하나를 주면 변경 됨&#x20;

```
margin-left: -200vw;
transform: translateX(-100vw);
```

{% code title="js010.html" %}

```html
<button class="slide-1">1</button>
<button class="slide-2">2</button>
<button class="slide-3">3</button>

<script>
  $('.slide-2').on('click', function (){
    $('.slide-container').css('transform', 'translateX(-100vw)');
  })
</script>
```

{% endcode %}

🎈Intellij 여러 줄 편집

&#x20; Alt +Shift + Insert or Alt + 드래그&#x20;

✨ 과제. 1번과 3번 버튼도 완료해보자&#x20;

✨ 과제. 완료한사람은 이전, 다음 버튼 추가하고 기능을 만들어보자.&#x20;

{% code title="js010.html" %}

```html
<script>
  $('.slide-1').on('click', function (){
    $('.slide-container').css('transform', 'translateX(0vw)');
  })

  $('.slide-2').on('click', function (){
    $('.slide-container').css('transform', 'translateX(-100vw)');
  })
  $('.slide-3').on('click', function (){
    $('.slide-container').css('transform', 'translateX(-200vw)');
  })

</script>

<button class="slide-4">이전</button>
<button class="slide-5">다음</button>

<script>
  var picture = 1;

  $('.slide-4').on('click', function (){
    if(picture == 3){
      $('.slide-container').css('transform', 'translateX(-100vw)');
      picture--;
    }else if(picture == 2){
      $('.slide-container').css('transform', 'translateX(0vw)');
      picture--;
    }
  })

  $('.slide-5').on('click', function (){
    if(picture == 1){
      $('.slide-container').css('transform', 'translateX(-100vw)');
      picture++;
    }else if(picture == 2){
      $('.slide-container').css('transform', 'translateX(-200vw)');
      picture++;
    }
  })
</script>

```

{% endcode %}

.slide-4 -5 이렇게 하면 헷갈리지 않나?

prev next class 로 변경

네이밍의 중요성!&#x20;

사진이 무조건 3장으로 고정일까?

4장 5장 그 이상이 되면 어떻게 해야할까? (확장성 고려)

```javascript
  $('.prev').on('click', function (){
    $('.slide-container').css('transform', 'translateX(-'+(picture-2)+'00vw)');
    picture--;
  })

  $('.next').on('click', function (){
      $('.slide-container').css('transform', 'translateX(-'+picture+'00vw)');
      picture++;
  })
```

&#x20;  이렇게 하면 완성

🔥이렇게 하면 두가지 오류가 있음 찾아보고 수정 해보자.&#x20;

1. 1번사진일때 이전 버튼을 계속 눌릴경우 or 마지막 사진일때 다음버튼을 계속 눌릴경우
2. n번 버튼을 누를 때 그이후엔 정상적 동작 안함&#x20;

{% code title="js010.html" %}

```html
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap demo</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-4bw+/aepP/YC94hEpVNVgiZdgIC5+VKNBQNGCHeKRQN+PtmoHDEXuppvnDJzQIu9" crossorigin="anonymous">

    <link rel="stylesheet" href="main.css">
    <script src="https://code.jquery.com/jquery-3.7.0.min.js" integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous"></script>

</head>
<body>

<div class="black-bg1">
    <div class="white-bg">
        <h4>로그인하세요</h4>
        <form >
            <div class="mb-3">
                <input type="text" class="form-control" id="email">
            </div>
            <div class="mb-3">
                <input type="password" class="form-control" id="password">
            </div>
            <button type="submit" id="submit" class="btn btn-primary">Submit</button>
            <button type="button" class="btn btn-danger" id="close">닫기</button>
        </form>

    </div>
</div>

<nav class="navbar navbar-light bg-light">
    <div class="container-fluid">
        <a class="navbar-brand" href="#">Offcanvas navbar</a>
        <span class="badge bg-dark ms-auto mx-3">Dark 🌛</span>
        <button class="navbar-toggler" type="button">
            <span class="navbar-toggler-icon "></span>
        </button>
    </div>
</nav>

<ul class="list-group" id="list1">
    <li class="list-group-item">An item</li>
    <li class="list-group-item">A second item</li>
    <li class="list-group-item">A third item</li>
    <li class="list-group-item">A fourth item</li>
    <li class="list-group-item">And a fifth one</li>
</ul>

<button id="loginBtn" type="button" class="btn btn-primary">
    버튼
</button>

<div class="alert alert-danger">
    <span id="sec">5</span>초 이내에 구매 시 사은품 증정!
</div>

<div style="overflow: hidden">
    <div class="slide-container">
        <div class="slide-box">
            <img src="img/color1.png">
        </div>
        <div class="slide-box">
            <img src="img/color2.png">
        </div>
        <div class="slide-box">
            <img src="img/color3.png">
        </div>
    </div>
</div>

<button class="slide-1">1</button>
<button class="slide-2">2</button>
<button class="slide-3">3</button>

<script>
    $('.slide-2').on('click', function (){
        $('.slide-container').css('transform', 'translateX(-100vw)');
    })
</script>

<script>
    $('#loginBtn').on('click', function(){
        $('.black-bg1').addClass('show-modal1');

    });

    $('#close').on('click', function() {
        $('.black-bg1').removeClass('show-modal1');
    })

    $('.navbar-toggler').on('click', function() {
        $('.list-group').toggleClass('lg-open');
    });


    $('form').on('submit', function (e){
        console.log(document.getElementById('email').value);
        if($('#email').val() == ''){
            alert('아이디를 입력하세요');
            e.preventDefault();  // 폼 전송 막는 코드
        }

        var regExp = /^([\w\.\_\-])*[a-zA-Z0-9]+([\w\.\_\-])*([a-zA-Z0-9])+([\w\.\_\-])+@([a-zA-Z0-9]+\.)+[a-zA-Z0-9]{2,8}$/i;

        if(!regExp.test($('#email').val())){
            alert("이메일 형식을 확인하세요");
            e.preventDefault();
        }


        if($('#password').val() == ''){
            alert('패스워드를 입력하세요');
        }else if($('#password').val().length <4){
            alert('패스워드는 4자 이상이어야 합니다.');
        }


    });


    //badge 클릭 시 글자를 Dark > Light 변경

    var count = 0;
    $('.badge').on('click', function (){
        count++;
        // count += 1;
        // count = count+1;
        console.log(count);
        console.log(count % 2);

        if(count % 2 === 0){
            $('.badge').html('Dark 🌛');
            $('.navbar').removeClass('navbar-dark');
            $('.navbar').removeClass('bg-dark');
            $('.navbar').addClass('navbar-light')
            $('.navbar').addClass('bg-light')
        }else if(count %2 === 1){
            $('.badge').html('Light 🌞');
            $('.navbar').removeClass('navbar-light');
            $('.navbar').removeClass('bg-light');
            $('.navbar').addClass('navbar-dark')
            $('.navbar').addClass('bg-dark')
        }
    });

    var sec = 5;

    var interval = setInterval(function () {
        sec--;
        console.log(sec);
        //4 3 2 1 0 -1 -2
        if(sec > 0){
            $('#sec').html(sec);
        }else if(sec == 0){
            $('.alert').hide();
            stop();
        }
    }, 1000)

    function stop(){
        clearInterval(interval)
    }


    </script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-HwwvtgBNo3bZJJLYd8oVXjrBZt8cqVSpeBNS5n7C8IVInixGAoxmnlMuBnhbgrkm" crossorigin="anonymous"></script>
</body>
</html>
```

{% endcode %}

![](https://3814826491-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJyHOwztPxBT3bLpisjCt%2Fuploads%2Fb4YABEoB177iNnDYCFZy%2Fcolor1.png?alt=media\&token=c24f6647-25f4-45c5-8196-99b5c0b0e4a1)

<figure><img src="https://3814826491-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJyHOwztPxBT3bLpisjCt%2Fuploads%2Fgobm3gsukVSRhNJIeBp2%2Fcolor2.png?alt=media&#x26;token=ccb17371-c9e7-4160-a3f4-e2f519031f60" alt=""><figcaption></figcaption></figure>

![](https://3814826491-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJyHOwztPxBT3bLpisjCt%2Fuploads%2FAg0peJlF88aBJbBzYIMi%2Fcolor3.png?alt=media\&token=da1a4c28-02a1-450a-8b61-fba965a87d0c)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://leeans-dev-book.gitbook.io/docs/lecture/javascript/carousel.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
