I want to display images on a website. Let's imagine "image1" on mondays "Image2" on tuesdays "Image3" on wednesdays and so on ! How do i achieve this in javascript? The images are placed in a function. How do take the images from there and show it on website?
CodePudding user response:
If you really only have access to the frontend, you could use switch
:
const image = document.getElementById('dog-img');
switch (new Date().getDay()) {
case 0: // Sunday
image.src = 'dog1.png';
break;
case 1: // Monday
image.src = 'dog2.png';
break;
case 2: // Tuesday
image.src = 'dog3.png';
break;
case 3: // Wednesday
image.src = 'dog4.png';
break;
case 4: // Thursday
image.src = 'dog5.png';
break;
case 5: // Friday
image.src = 'dog6.png';
break;
case 6: // Saturday
image.src = 'dog7.png';
}
<img id="dog-img" src="">
CodePudding user response:
You could get the integer of the day of the week and map it to an array of images:
const image = document.getElementById('image');
const imagesArray = [
"https://images.unsplash.com/photo-1508185159346-bb1c5e93ebb4?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=55cf14db6ed80a0410e229368963e9d8&auto=format&fit=crop&w=1900&q=80", // Sunday
"https://images.unsplash.com/photo-1495480393121-409eb65c7fbe?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=05ea43dbe96aba57d48b792c93752068&auto=format&fit=crop&w=1351&q=80", // Monday
"https://images.unsplash.com/photo-1501611724492-c09bebdba1ac?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=ebdb0480ffed49bd075fd85c54dd3317&auto=format&fit=crop&w=1491&q=80", // Tuesday
"https://images.unsplash.com/photo-1417106338293-88a3c25ea0be?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=d1565ecb73a2b38784db60c3b68ab3b8&auto=format&fit=crop&w=1352&q=80", // Wednesday
"https://images.unsplash.com/photo-1500520198921-6d4704f98092?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=ac4bc726064d0be43ba92476ccae1a75&auto=format&fit=crop&w=1225&q=80", // Thursday
"https://images.unsplash.com/photo-1504966981333-1ac8809be1ca?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=9a1325446cbf9b56f6ee549623a50696&auto=format&fit=crop&w=1350&q=80", // Friday
"https://images.unsplash.com/photo-1437075130536-230e17c888b5?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=ff573beba18e5bf45eb0cccaa2c862b3&auto=format&fit=crop&w=1350&q=80", // Saturday
];
const dayInteger = new Date().getDay();
image.src = imagesArray[dayInteger]
img {
width: 100%
}
<img id="image" src="">