I would like to do something, which is not complicated, but I tried several times to iterate some code but I can't do it anymore.
Here is my problem:
By default, an image is displayed under which there are 2 buttons to change the image.
The default image is DAY.
The 2 buttons are DAY and NIGHT.
If I click on the NIGHT button, I would like the NIGHT image (which is not yet visible) to be displayed instead of the DAY image.
And so on, when I have the NIGHT image visible (and the DAY image is hidden) and I click on the DAY button, the DAY image appears instead of the NIGHT image.
I hope I have made myself clear.
Here is what I wrote in code:
HTML Code
<h2>What is your favourite time of day to programme?</h2>
<!-- image box -->
<div id="visuel">
<img id="img-day" src="../img/Capture - Image Day SVG.png">
<img id="img-night" src="../img/Capture - Image Night SVG.png">
</div>
<!-- option button -->
<div id="option-wrapper">
<button id="btnDay" onclick="displayDay('../img/Capture - Image Day SVG.png')" class="btn-option btn-option--active">Day</button>
<button id="btnNight" onclick="displayNight('../img/Capture - Image Night SVG.png')" class="btn-option" >Night</button>
<!-- OTHER OPTION
<button id="btnDay" onclick="displayDay();" class="btn-option btn-option--active">Day</button>
<button id="btnNight" onclick="displayNight();" class="btn-option>Day</button>
-->
</div>
JS Code
/* STEPS
1 - Select the element,
2 - Add an event listener,
2.1 - Click on the 'day' button to display the day image.
2.2 - Click on the other image to display the night image.
3 - DisplayDay/Night function
*/
// 1 - SELECTION OF ELEMENTS
/* 1.1 - Image Day/Night */
const imgDay = document.getElementById('imgDay');
const imgNight = document.getElementById('imgNight');
/* 1.2 - Button Day/Night */
const btnDay = document.getElementById('btnDay');
const btnNight = document.getElementById('btnNight');
// 2 - ADDING AN EVENT LISTENER
/* 2.1 - Choice time day */
btnDay.addEventListener('click', () => {
displayDay();
})
/* 2.2 - Choice time night */
btnNight.addEventListener('click', () => {
displayNight();
})
// 3 - FONCTION DISPLAY
/* -------- FIRST OPTION -------- */
/* 3.1 - Display Day */
function displayDay(imgDay) {
imgDay.setAttribute('src', '../img/Capture - Image Day SVG.png');
}
/* 3.2 - Display Night */
function displayNight(imgNight) {
imgNight.setAttribute('src', '../img/Capture - Image Night SVG.png');
}
/* -------- SECOND OPTION -------- */
/* 3.1 - Display Day */
function displayDay() {
imgDay.style.display = "block";
}
/* 3.1 - Display Night */
function displayNight() {
imgNight.style.display = "none";
}
There is probably an error on my event listener and more.
The error in the console:
Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
My code has no head or tail and I'm starting to lose my mind too.
Are there any kind souls here to enlighten/help me?
Thank you in advance guys !