javascript image swap keeps looping - javascript

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;
}

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>

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.

Related

How to use a function to open a link in html

I'm creating a website thats going to work like an online advent calendar; I want to be able to make sure that a link wont open until the correct day. Heres what I have so far:
<area shape="rect" coords="0,0,90,150" href="https://www.youtube.com/watch?v=dQw4w9WgXcQ" alt="1" target="_blank" onClick="return canOpen(this)">
<script>
function canOpen(isTrue) {
var isOpen = new Date("Dec "+isTrue+", 2020 00:00:00").getTime();
var currentTime = new Date().getTime();
var timeDifference = isOpen - currentTime;
if (timeDifference > 0) {
<! Go to link>
}
else {
<! Show popup "You can't open this yet!>
}
}
</script>
How could I make it so that you can go to the link if it is past the date in question, and how would I get the value of alt out of the link and into the script?
Thanks for any help.
You can use Element.getAttribute() to get attribute alt as event date for check in script.
Then check if the current date passed event date, redirect by change site's location, or do anything else you like otherwise, if the element has redirect as default behavior (like a tag), you will need return false; to prevent default behavior.
function canOpen(element) {
var isOpen = new Date("Dec "+element.getAttribute("alt")+", 2020 00:00:00").getTime();
var currentTime = new Date().getTime();
var timeDifference = isOpen - currentTime;
if (timeDifference > 0) {
window.location.href = element.getAttribute("href");
} else {
alert("Not yet!");
// return false; // for `a` tag
}
}
I created two functions, one to set the date, and one to check if the link can open. If the release date has passed, the href of the link changes from "#" to the Youtube link. The date updates every second with setInterval.
Example on JSFiddle
Also, did I just get RickRolled?
<a id="premiere-link" href="#">Youtube Link</a>
<script>
// setInterval(canOpen, 1000);
let month, day, year, time;
const link = document.getElementById('premiere-link');
setDate(); //set date immediatly on page load
setInterval(setDate, 1000); //update date every second
function setDate() {
var dateObj = new Date();
month = dateObj.getUTCMonth() + 1; //months from 1-12
day = dateObj.getUTCDate();
year = dateObj.getUTCFullYear();
time = dateObj.getTime();
}
function canOpen(month, day){
//set month and day for release
if (month >= 11 && day >= 1) {
alert('You just got RickRolled')
link.setAttribute('href', 'https://www.youtube.com/watch?v=dQw4w9WgXcQ');
} else {
link.setAttribute('href', '#');
alert('You have to wait to get RickRolled')
}
}
link.onclick = () => {canOpen(month, day)};
</script>

How to assign Javascript Image object to existing Img element of JSP

JSP code is written as below,
< img src='<%=imageURL%>' id='advt-image-top' border='0' alt=''" /><br/>
Where the value of imageURL is like,
http://1.2.3.4:5678/ads/avw.php?zoneid=1234567890&cb=INSERT_RANDOM_NUMBER_HERE
(Sample URL which fetches random advertisement image from Ad-Server)
Now, same JSP page contains javascript-code like below:
$(document).ready(function() {
var imgAd = new Image();
imgAd.src = '<%=imageURL%>';
imgAd.onload = function(){
if((this.width == 1 && this.height == 1)){
document.getElementById('advt-image-top').src='img/default_top.jpg';
}
}
}
Above javascript code checks - if image returned from ad-server is of size 1x1, then it should be replaced with default-image.
Problem is, above entire code-snippet executes "imageURL" twice in order to fetch one image from ad-server : one to check whether image-returned-from-ad-server is of size 1x1 and other during tag execution.
How can I optimize above code so that "imageURL" is executed only once?
How can I assign Image() object of javascript (after 1x1 validation is passed) to JSP's 'advt-image-top' element?
Thanks in advance.
You just need a minor adjustment to your javascript code, there is no need to create an Image:
$(document).ready(function() {
var imgAd = document.getElementById('advt-image-top');
imgAd.onload = function(){
if((this.width == 1 && this.height == 1)){
imgAd.src='img/default_top.jpg';
}
}
}
However, the image might get loaded before the document ready fires and lose the onload event, so you might want to load the default url in your tag:
< img src='img/default_top.jpg' id='advt-image-top' border='0' alt=''" /><br/>
...and apply the remote url by code:
$(document).ready(function() {
var imgAd = document.getElementById('advt-image-top');
imgAd.onload = function(){
if((this.width == 1 && this.height == 1)){
imgAd.src='img/default_top.jpg';
}
}
imgAd.src='<%=imageURL%>';
}
EDIT: probably the best way is to remove the img tag altogether from the jsp and write everything with javascript. Supposing that the image is contained in an element with id "container":
$(document).ready(function() {
var imgAd = new Image();
imgAd.onload = function(){
if((this.width == 1 && this.height == 1)){
imgAd.src='img/default_top.jpg';
}
}
imgAd.src='<%=imageURL%>';
imgAd.id='adv-image-top';
imgAd.border=0;
document.getElementById('container').appendChild(imgAd);
}
#dipanda, Thanks for your comments. Helped me solve my problem.
var $imgObj = $("<img/>",{src:"<%=imageURL%>"});
$imgObj.load(function(){
var imgJS = $imgObj[0];
if(imgJS.height == 1 && imgJS.width == 1){
document.getElementById('advt-image-top').src='img/default_top.jpg';
}else{
if($("#advt-image-top")!=null && $("#advt-image-top")!=undefined){
$("container").append($imgObj);
}
}
};

Image rotater in javascript only - no jquery

UPDATE: The answer below seemed to work, but if I have links in my text in the descriptions variable, it doesn't seem to replace the text at all. If i remove tags, or any html tags from all the text I am trying to replace, it works. Issue is, I need the text to be replaced to be html format :(
I am trying to get an image to fade, with text outside of the image to fade as well, and have another set appear in same place.
jquery can not be used due to the environment.
I came up with this, the only issue is that the very first thing that happens is the first image fades at the very start and the same image appears. Then it starts working normal after that first "glitch". After that, if seems to work perfectly.
Can someone point out my silly mistake?
<script type="text/javascript">
var links = ["http://www.firstlink.com","http://www.secondlink.com","http://www.thirdlink.com"];
var images = ["1stimage.jpg","2ndimage.jpg","3rdimage.jpg"];
var descriptions=["this is the first set of rotating text", "Now we have another set of text, in this large paragraph. Write whatever we want here", "and this is the last set of text, we have 3 images. We can add more images and more text."]
var i = 0;
var renew = setInterval(function(){
if(links.length == i){
i = 0;
}
else {
document.getElementById("bannerImage").src = images[i];
fadeIn(document.getElementById("bannerImage"), 1000);
document.getElementById("bannerLink").href = links[i];
document.getElementById("p1").innerHTML= descriptions[i];
i++;
}
},5000);
</script><script type="text/javascript">
function fadeIn(el, time) {
el.style.opacity = 0;
el.style.display = "block";
var last = +new Date();
var tick = function() {
el.style.opacity = +el.style.opacity + (new Date() - last) / time;
last = +new Date();
if (+el.style.opacity < 1) {
(window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16)
}
};
tick();
}
</script><img alt="some text" height="83" id="bannerImage" src="1stimage.jpg" width="633" />
<p id="p1">this is the first set of rotating text</p>
Change this
var images = ["1stimage.jpg","2ndimage.jpg","3rdimage.jpg"];
var descriptions=["this is the first set of rotating text", "Now we have another set of text, in this large paragraph. Write whatever we want here", "and this is the last set of text, we have 3 images. We can add more images and more text."]
to this
var images = ["2ndimage.jpg","3rdimage.jpg","1stimage.jpg"];
var descriptions=["Now we have another set of text, in this large paragraph. Write whatever we want here", "and this is the last set of text, we have 3 images. We can add more images and more text.", "this is the first set of rotating text"]

Image display based on time

I'm trying to create an image rotator that displays certain images at certain times, but also rotates at other times in the day.
When I first created it, I just had it rotate every three seconds. That worked fine. But once I added the code to make a different image show up at different times, it quit working all together. Part of the problem is I'm confused about where I should put the setInterval and clearInterval. Anyway, here;s the code.
<img id="mainImage" src="/arts/rotatorpics/artzone.jpg" />
JS:
var myImage = document.getElementById("mainImage");
var imageArray = ["arts/rotatorpics/artzone.jpg",
"arts/rotatorpics/bach.jpg",
"arts/rotatorpics/burns.jpg"];
var imageIndex = 0;
var changeImage = function() {
mainImage.setAttribute("src", imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
var newDay = new Date(); //create a new date object
var dayNight = newDay.getHours(); //gets the time of day in hours
function displayImages() {
if (dayNight >= 10 && dayNight <= 12) {
mainImage.setAttribute("src", imageArray[1]);
} else if (dayNight >= 17 && dayNight <= 19) {
mainImage.setAttribute("src", imageArray[2]);
} else {
var intervalHandle = setInterval(changeImage, 3000);
}
myImage.onclick = function() {
clearInterval(intervalHandle);
};
}​
first of all, all your variables seem to be are global, please dont do that, use an anonymous function-wrapper which executes your code (immediately (read about IIFE here. this is not part of your problem, but just good and clean coding style.
(function() {
// your code here
})();
then i think one of your problems is your displayImages-function, which you declare but never call!
just should call it at the end of your code (or just leave it out)
displayImages();
if you want your images not to be swapped between 10-12 and 17-19 your code should then work as expected. if the images should swap even at this times, you shouldnt put the setInterval into the last else (inside your displayImages-function

Showing alternative image if img src is not working properly

I'm working on a web page and I have this function which is showing the pic of the day of a parent site
function LoadPage() {
var today = new Date();
var yyyy = today.getFullYear();
var mm = today.getMonth()+ 1;
var dd = today.getDate();
var url="http://myparentsite"+yyyymmdd+"/image.jpg";
document.getElementById("img").setAttribute("src",url);
}
The pic of the day is usually set in the morning so I've a problem between midnight and 7-8 am during those hours the browser will show the "?" of "image not found".
How can I set it to show the image of the day before?
I tried
var dd2 = today.getDate() -1;
var url2="http://myparentsite"+yyyymmdd2+"/image.jpg";
but I don't know how to handle it in the function and in the Html.
Simple answer is have the parent site reference a constant image location, when you have a new daily image then overwrite the image with the new one and archive the old daily image.
<img src='http://myparentsite/imageOfTheDay.jpg'/>
otherwise you can check for an error and set it to yesterday's image
document.getElementById("img").onError = function() {
var dd2 = today.getDate() -1;
var url2="http://myparentsite"+yyyymmdd2+"/image.jpg";
document.getElementById("img").setAttribute("src",url2);
}
or check the date of the request and determine what image to show
var now = new Date();
var now_utc_hour = now.getUTCHours();
url = "http://myparentsite"+yyyymmdd+"/image.jpg";
if( now_utc_hour > 7 && now_utc_hour < 8 ) "http://myparentsite"+yyyymmdd2+"/image.jpg";
document.getElementById("img").setAttribute("src",url);
Basically, you need to handle an event on the image.
document.getElementById("img").onError = function() {
// the image didn't load properly, change the src attribute
document.getElementById("img").setAttribute("src", url2);
}
document.getElementById("img").setAttribute("src",url);
Try This:
<img src="http://myparentsite/imageOfTheDay.jpg" alt="" onerror="this.src='http://myparentsite/alternateImageOfTheDay.jpg'"/>
-Arpit

Categories

Resources