Technologies Used
| Technology | Purpose |
|---|---|
| HTML | Creates the webpage structure |
| CSS | Styles the slider |
| JavaScript | Changes images dynamically |
Important Elements
Image
<img id="sliderImage">
This image changes every time the user clicks a button.
Previous Button
<button id="previousBtn">
Moves backward.
Next Button
<button id="nextBtn">
Moves forward.
CSS Styling
Important properties:
| Property | Purpose |
|---|---|
| display:flex | Align items in one row |
| justify-content | Center horizontally |
| align-items | Center vertically |
| object-fit | Prevent image stretching |
| border-radius | Rounded corners |
| box-shadow | Shadow effect |
JavaScript Logic
JavaScript makes the slider interactive.
It performs five main tasks:
Step 1
Select HTML elements.
document.getElementById()
Step 2
Store image paths inside an array.
images
↓
Image1
Image2
Image3
Image4
Step 3
Keep track of the current image.
currentIndex
↓
0
Step 4
Update the image source.
sliderImage.src
↓
images[currentIndex]
Step 5
Respond to button clicks.
Click
↓
Increase index
↓
Show new image
Variables
Variables store data.
Example:
let currentIndex = 0;
Think of a variable as a box that stores information.
currentIndex
↓
0
Constants
const sliderImage
Used for values that never change.
Why?
Because the image element itself never changes.
Only its content changes.
Arrays
Instead of writing
image1
image2
image3
image4
we write
images[]
↓
0 → image1
1 → image2
2 → image3
3 → image4
Arrays store multiple values together.
Array Index
Arrays start from 0.
images[0]
↓
image1
images[2]
↓
image3
Functions
Functions are reusable blocks of code.
Instead of writing
Change image
five times,
we create
showImage()
Whenever needed,
showImage();
runs automatically.
Benefits:
- Cleaner code
- Reusable
- Easier to maintain
DOM Manipulation
DOM stands for
Document Object Model
JavaScript interacts with HTML using the DOM.
HTML
↓
DOM
↓
JavaScript
Example
document.getElementById("sliderImage")
means
"Find the image in HTML."
Event Listeners
An Event Listener waits for something to happen.
Example:
Click Button
↓
Run Function
Increment Operator
currentIndex++;
means
currentIndex = currentIndex + 1;
Example
0 -> 1 -> 2 -> 3
Decrement Operator
currentIndex--;
means
currentIndex = currentIndex - 1;
Example
3 -> 2 -> 1
Conditional Statements
if()
used for decision making.
Example
if(currentIndex >= images.length)
If we reach the last image,
start from the beginning.
Image Length
images.length
returns
4
if there are four images.
This prevents hardcoding values.
OUTPUT
Check out my project Image Slider here : https://project1-b3f69b.gitlab.io/Image%20Slider/index.html
References :
https://www.w3schools.com/howto/howto_css_smooth_scroll.asp#section1
https://www.w3schools.com/howto/howto_js_slideshow.asp

Top comments (0)