Reputation: 55
I'm trying to have a image that changes automatically depending upon the date. So I have a default image, then at a holiday, it changes automatically to a holiday themed image. The code seems to work, but when you put it in a page, the code keeps looping. Any help would be much appreciated. Thanks in advance.
<img id="Logo" src="/images/default.png" alt="Default Image" onload="logo(this)" />
function logo(img) {
var d = new Date();
var Today = d.getDate();
var Month = d.getMonth();
var src;
if (Month === 4 && (Today >= 21 && Today <= 23)) {
src = "/images/holiday.png";
} else {
src = "/images/default.png";
}
img.src=src;
}
Upvotes: 0
Views: 86
Reputation: 65806
The problem is that your function is set to run on the load
event of the image. The function then swaps the src
of the image, thus causing a new image to load, and so you get another load
event occurring, which swaps the image source and so on.
Set your function to run on the load
event of the window
instead:
// Set your function to run when the window is loaded
window.addEventListener("load", logo);
// Get your element reference
var img = document.getElementById("Logo");
// This is your callback function
function logo() {
var d = new Date();
var Today = d.getDate();
var Month = d.getMonth();
var src;
if (Month === 4 && (Today >= 21 && Today <= 23)) {
src = "/images/holiday.png";
} else {
src = "/images/default.png";
}
img.src=src;
}
<img id="Logo" src="/images/default.png" alt="Default Image">
But, really this is not a great approach because the image will only be swapped after the default image loads, so the user will see the default image briefly and then they will see it change to the desired image. Instead, you should just set the initial source of the image dynamically so that only one image is ever loaded.
If you place your <script>
element just prior to the closing body
tag (</body>
), the browser will have already parsed the img
element into memory, but it won't have a src
set for it yet, so the user won't see anything at that point. Then the script runs and sets the src
to the right image. In the end, only one image is loaded and no event handlers need to be set up.
<body>
<img id="Logo" src="" alt="Correct Image">
<script>
// Just determine the appropriate source:
var d = new Date();
var Today = d.getDate();
var Month = d.getMonth();
var src;
if (Month === 4 && (Today >= 21 && Today <= 23)) {
src = "/images/holiday.png";
} else {
src = "/images/default.png";
}
// And then set the image to it:
document.getElementById("Logo").src = src;
</script>
</body>
Upvotes: 1
Reputation: 49803
By setting onload
of your img
, you cause logo
to get called when an image is loaded, which loads a new image, which causes logo
to get called, which...
So either you need to have logo
not always change the image, or you want logo
called under different circumstances.
Upvotes: 0