Hosted Project
Github Source Files
DOM Manipulation
Control Structures
Arrays
Array.forEach()
JavaScript CSS Manipulation
eventListeners
This project is very similar to the Testimonials JavaScript Project. I did find it a lot easier, however. For this image slider, when an arrow is clicked, the next image in the array shows up.
Before doing this project, I didn't realize how easy it was to make a slider project. I thought it was just a jQuery thing. Turns out I was wrong.
This took about 15 minutes to code
This took me 35 lines of code.
Image sliders aren't a jQuery thing. All I had to do was access different images from inside of an array. And to make accessing each image easier, I just needed to make sure images had the same name but different numbers so they can be accessed by an index.
A default image should be displayed when you load the page.
When you click the “left” button, one of five images should display, all the way until each of the five numbers display in sequence.
Repeat step 2 for the “right” button.
<!-- <head>는 생략. -->
<body>
<div class="container">
<div class="row max-height align-items-center">
<div class="col-9 col-md-10 mx-auto img-container">
<a class="btn btn-left"><i class="fas fa-caret-left"></i></a>
<a class="btn btn-right"><i class="fas fa-caret-right"></i></a>
</div>
</div>
</div>
<script>
// 사진 자료를 준비.
const pictures = ["img-1", "img-2", "img-3"];
// imageDIV라는 곳에 이미지를 띄울 것.
const buttons = document.querySelectorAll('.btn')
const imageDIV = document.querySelector('.img-container')
let counter = 0
buttons.forEach(function(button){
button.addEventListener('click', function(e){
// 왼쪽 버튼을 클릭하면
if (button.classList.contains('btn-left')){
// 카운터 감소
counter--
// 카운터가 0보다 작으면
if(counter < 0){
// pictures의 끝으로 돌아감
counter = pictures.length -1
}
// imageDIV의 background이미지를 pictures 이미지로 바꿈.
imageDIV.style.backgroundImage = `url('./img/${pictures[counter]}.jpeg')`
}
if (button.classList.contains('btn-right')){
counter++
// 카운터가 최대 크기보다 커지면, 0으로 다시 되돌아옴.
if(counter > pictures.length -1){
counter = 0
}
imageDIV.style.backgroundImage = `url('./img/${pictures[counter]}.jpeg')`
}
})
})
</script>
</body>
- 범위를 벗어나면 배열의 처음과 끝으로 되돌아오는 함수 설정
- document 전체 뿐만 아니라 일부분에 대해서 background 설정이 가능.