Image Slider by HTML, CSS and JavaScript
index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Change Bg color</title>
</head>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: monospace;
}
#main{
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
background: url(https://source.unsplash.com/random/?animal)no-repeat center center/cover;
}
#main h1{
color: white;
margin-bottom: 1rem;
}
#img-container {
width: 56rem;
height: 36rem;
background: url(https://source.unsplash.com/random/?animal)no-repeat center center/cover;
/* background: url(https://source.unsplash.com/random/?city);
background-repeat: no-repeat;
background-position: center center;
background-size: cover;
background-attachment: fixed; */
border: 2px solid black;
border-radius: 10px;
position: relative;
}
.left {
font-size: 4rem;
position: absolute;
top: 50%;
left: -21px;
transform: translate(-50%, -50%);
cursor: pointer;
color: white;
}
.right {
font-size: 4rem;
position: absolute;
top: 50%;
right: -21px;
transform: translate(50%, -50%);
cursor: pointer;
color: white;
}
</style>
<body>
<main id="main">
<h1>Image Slider</h1>
<div id="img-container">
<span type="button" class="left"><</span>
<span type="button" class="right">></span>
</div>
</main>
<script>
const imgArr = ['elephant.jpg', 'giraffe.jpg', 'mountains.jpg', 'parrot.jpg', 'rabbit.jpg', 'squirrel.jpg'];
const imgContainer = document.getElementById('img-container');
const spanBtn = document.querySelectorAll('span[type=button]');
const main = document.getElementById('main');
console.log(main);
let count = 0;
spanBtn.forEach((btn) => {
btn.addEventListener('click', () => {
if (btn.classList.contains('left')) {
count--;
if (count < 0) {
count = imgArr.length - 1;
}
imgContainer.style.background = `url('./images/${imgArr[count]}')no-repeat center center/cover`;
main.style.background = `url('./images/${imgArr[count]}')no-repeat center center/cover`;
}
else if (btn.classList.contains('right')) {
count++;
if (count > imgArr.length - 1) {
count = 0;
}
imgContainer.style.background = `url('./images/${imgArr[count]}')no-repeat center center/cover`;
main.style.background = `url('./images/${imgArr[count]}')no-repeat center center/cover`;
}
});
});
</script>
</body>
0 Comments