Tutorial_js
Tutorial_js
md 4/5/2023
Counter App
Current Value + 0 -
2. You can replace each button by a label image, so we have to add 2 images.
<head>
<link href="css/style1.css" rel="stylesheet">
<script src="js/script.js"></script>
</head>
5. Add to the onclick attribute the call function decrease() to the minus button and increase() call to the
Plus button. Here an example:
1/6
Tutorial js.md 4/5/2023
6. Now add css rules for the images button as indicated in this preview:
count = 0;
function increase() {
/*catch an input element in a variable*/
myInput = document.getElementById("count");
/*displays the content of myInput to the console*/
console.log(myInput);
inputValue = myInput.value;
/*Convert to an integer then Increment the counter value by 1*/
count = parseInt(inputValue) + 1;
/*display the new counter value in input*/
myInput.value = count;
console.log(count);
}
function decrease() {
myInput = document.getElementById("count");
inputValue = myInput.value;
/*Convert to an integer then Decrease the counter value by 1*/
count = parseInt(inputValue) - 1;
myInput.value = count;
console.log(count);
}
Note: download the project code source named cours js and compare with your solution.
2/6
Tutorial js.md 4/5/2023
/* function that switch between the dark and the light Mode */
function switchTheme() {
3/6
Tutorial js.md 4/5/2023
if (isStyle1) {
styleLink.href = 'css/style2.css';
imgIcon.innerHTML = '<a onclick="switchTheme()" id="theme-toggle">
<img src="imag/light.png" alt="light" id="light"></a>';
isStyle1 = false;
} else {
styleLink.href = 'css/style1.css';
imgIcon.innerHTML = '<a onclick="switchTheme()" id="theme-toggle">
<img src="imag/dark.png" alt="dark" id="dark"></a>';
isStyle1 = true;
}
}
HTML:
<div>
<img id="gallery-image" src="">
</div>
<button onclick="prevImage()">Previous</button>
<button onclick="nextImage()">Next</button>
JavaScript:
const images = [
'https://example.com/image1.jpg',
'https://example.com/image2.jpg',
'https://example.com/image3.jpg'
];
let currentIndex = 0;
function showImage() {
const imageElement = document.getElementById('gallery-image');
imageElement.src = images[currentIndex];
}
4/6
Tutorial js.md 4/5/2023
function prevImage() {
currentIndex--;
if (currentIndex < 0) {
currentIndex = images.length - 1;
}
showImage();
}
function nextImage() {
currentIndex++;
if (currentIndex >= images.length) {
currentIndex = 0;
}
showImage();
}
This example sets up an array of image URLs and keeps track of the current index. When the "Previous" or
"Next" button is clicked, the index is updated and the corresponding image is displayed.
Exercise:
5/6
Tutorial js.md 4/5/2023
Solution
let currentIndex = 0;
6/6