Showing alternative image if img src is not working properly - javascript

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

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>

Hidding field for a particular time

I have a text field that I need only to display for a certain period of time.
I need it to appear after 5pm and stop appearing at 7am daily.
The piece of text has been saved as a variable.
How do I do this?
Thanks
You can get time using Date() object and then show and hide your text. e.g
HTML:
<div class="someClass">Your text </div>
JavaScript:
var currentDate = new Date();
var currentTime = currentDate.getHours();
if(currentTime >=17 || currentTime <=7) {
document.getElementsByClassName('someClass')[0].style.visibility = 'visible';
} else {
document.getElementsByClassName('someClass')[0].style.visibility = 'hidden';
}

javascript image swap keeps looping

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.

Using JQuery to add a link to an element if a condition is met

I am very new to HTML, CSS and JavaScript. I am trying to use jQuery to make a button active or inactive depending on the time of day. I have managed to get the image to change correctly after defining the time now (d), an open time and a close time. However I am having problems assigning a link to the buttons depending on the time of day.
This code correctly applies a class if the time is between open and close. It also correctly applies the link to the ButtonOne div, only when the ManagersChatButtonActive class is applied, in a JSFiddle. However in SharePoint, were this will be, the link is also applied even when the time condition is not met.
How can I get the link to only be applied when the 'if' condition is met?
(This is my first time on Stack Overflow, so apologies if this is not very well laid out or explained).
$(document).ready(function() {
var d = new Date();
var open = new Date();
open.setHours(9);
open.setMinutes(0);
open.setSeconds(0);
var close = new Date();
close.setHours(18);
close.setMinutes(0);
close.setSeconds(0);
if (d >= open && d < close) {
$(".ButtonOne").addClass("ManagersChatButtonActive");
$(".ButtonOne").wrap('<a href="http://www.google.com"/>');
} else {
$(".ButtonOne").addClass("ManagersChatButtonInactive");
}
});
Make sure you wrap your method in the JQuery syntax for document on ready or on load as follows:
$(function(){
var d = new Date()
var open = new Date();
open.setHours(9);
open.setMinutes(0);
open.setSeconds(0);
var close = new Date();
close.setHours(18);
close.setMinutes(0);
close.setSeconds(0);
if (d >= open && d < close) {
$(".ButtonOne").addClass("ManagersChatButtonActive");
$(".ButtonOne").wrap('<a href="http://www.google.com"/>');
} else {
$(".ButtonOne").addClass("ManagersChatButtonInactive");
}
})
https://jsfiddle.net/aaronfranco/3xwhoh10/1/
It might also make more sense to use getTime() to use a UNIX timestamp, which is a number, instead of a date string.
$(function(){
var d = new Date().getTime();
var open = new Date();
open.setHours(9);
open.setMinutes(0);
open.setSeconds(0);
open = open.getTime()
var close = new Date();
close.setHours(18);
close.setMinutes(0);
close.setSeconds(0);
close = close.getTime()
if (d >= open && d < close) {
$(".ButtonOne").addClass("ManagersChatButtonActive");
$(".ButtonOne").wrap('<a href="http://www.google.com"/>');
} else {
$(".ButtonOne").addClass("ManagersChatButtonInactive");
}
})
Don't forget to get the current time with the getHours or getTime method. You want this to compare to your condition. These values do not have to be in a time-format, it also possible to just use some static numbers.
You can just do something like this:
var time = new Date(),
hours = time.getHours();
if (hours >= 9 && hours < 18) {
$(".ButtonOne").addClass("ManagersChatButtonActive");
$(".ButtonOne").wrap('<a href="http://www.google.com"/>');
} else {
$(".ButtonOne").addClass("ManagersChatButtonInactive");
}
Working example: https://jsfiddle.net/crix/7o4uhLxe/
Hope this helps!
I checked your code in browser with jQuery, but I don't know about SharePoint, so I guess if you just enclose your code which works fine with jQuery, in .ready() so that when document is ready only then your code is run and when the ".ButtonOne" element is initialized in dom:
$(document).ready(function(){
var d = new Date();
var open = new Date();
open.setHours(9);
open.setMinutes(0);
open.setSeconds(0);
console.info(d);
console.log(open);
var close = new Date();
close.setHours(18);
close.setMinutes(0);
close.setSeconds(0);
console.log(close);
if (d >= open && d < close) {
console.info("INSIDE");
$(".ButtonOne").addClass("ManagersChatButtonActive");
$(".ButtonOne").wrap('<a href="http://www.google.com"/>');
} else {
console.info("INSIDE ELSE");
$(".ButtonOne").addClass("ManagersChatButtonInactive");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="ButtonOne" >
This is the desired ButtonOne Div
</div>

using javascript/jQuery to show certain elements on certain dates?

Pretty much as the title. I have been asked if it is possible to have a specific banner shown in a section on a website on different days without any external user input.
My first thoughts are the use of javascript/jquery. We are limited with the functionality however as the site is controlled by the horror that is Netsuite.
Any help/ideas are appreciated :)
-Wayne
EDIT: With regard to your comment, it sounds like you want to load a different slideshow depending on the day of the week.
Here's a simple generic example of how it could be done.
// Insert the code that loads the individual slideshows in the functions below
var slideshows = [
function() { /* insert code to load some slideshow */ },
function() { /* insert code to load some other slideshow */ },
function() { /* insert code to load a different slideshow */ },
function() { /* insert code to load yet another slideshow */ }
];
// call a slideshow function depending on the day of week
slideshows[ new Date().getDate() % slideshows.length ]();
This will call a different function from the Array depending on the day of week. You don't need seven of them. It will automatically rotate.
There are other ways to approach this, but I'd need to see how the slideshows are set up. This is a simple approach.
If you have more than 7 different slideshows, it will need to be changed a bit.
EDIT: This answer assumes you meant different per day of week. Not sure if that was your intention.
This is probably better than my original answer since it doesn't require loading all the banners.
javascript only version
Example: http://jsfiddle.net/patrick_dw/5drgu/4/
var banners = [
"http://dummyimage.com/120x90/f00/fff.png&text=my+image",
"http://dummyimage.com/120x90/0f0/fff.png&text=my+image",
"http://dummyimage.com/120x90/00f/fff.png&text=my+image",
"http://dummyimage.com/120x90/ff0/fff.png&text=my+image"
];
var banner = new Image();
banner.src = banners[ new Date().getDate() % banners.length ];
document.getElementById('container').appendChild( banner );
jQuery version
Example: http://jsfiddle.net/patrick_dw/5drgu/7/
(changed it a bit so it doesn't start with an empty <img>)
var banners = [
"http://dummyimage.com/120x90/f00/fff.png&text=my+image",
"http://dummyimage.com/120x90/0f0/fff.png&text=my+image",
"http://dummyimage.com/120x90/00f/fff.png&text=my+image",
"http://dummyimage.com/120x90/ff0/fff.png&text=my+image"
];
var banner = $('<img>', { src:banners[ new Date().getDate() % banners.length ]})
.appendTo('#container');
html
<div id='container'></div>
Original answer:
Here's one way:
Example: http://jsfiddle.net/patrick_dw/5drgu/
var banners = $('#container img').hide();
banners.eq( new Date().getDate() % banners.length ).show();
html
<div id='container'>
<img src = "http://dummyimage.com/120x90/f00/fff.png&text=my+image" />
<img src = "http://dummyimage.com/120x90/0f0/fff.png&text=my+image" />
<img src = "http://dummyimage.com/120x90/00f/fff.png&text=my+image" />
<img src = "http://dummyimage.com/120x90/ff0/fff.png&text=my+image" />
</div>
The first thought should be server-side.
If that is not an option then you could do it with javascript/jquery with the limitations it brings. Javascript enabled browsers.
You could name your files accordingly ie. image-19-7-2011.jpg and use the Date() object to create the filename to use for the current date.
Something like
var d = new Date();
var filename = 'image-' + d.getDate() + '-' + d.getMonth() + '-' + d.getFullYear() + '.jpg';
document.getElementById('banner').src = '/path/to/' + filename;
example at http://jsfiddle.net/rZaqx/
var now = new Date();
var date = now.getMonth() + "-" + now.getDay();
switch(date) {
case "04-01":
$('<p>APRIL FOOLS!</p>').appendTo("body");
break;
case "01-01":
$('<p>Happy New Year!</p>').appendTo("body");
break;
}
This answer assumes you want a different banner image for each day of the week.
If you aren't able to update the banner in the backend then it would be possible just to have all the banners on the page, hidden with the CSS display: none.
Then just use something like:
var date = new Date();
$("#banner" + date.getDay()).show();
This will work if you have 7 elements named banner0 for Sunday, banner1 for Monday, etc.
Alternatively, if you just want to change the banner image then you could set your CSS like so:
div#banner { background-image: url(default.jpg)} // Common styling
div#banner.day0 { background-image: url(image0.jpg); } // Image for Sunday
div#banner.day1 { background-image: url(image1.jpg); } // Image for Monday
div#banner.day2 { background-image: url(image2.jpg); } // Image for Tuesday
Then your jQuery could look like:
var date = new Date();
$("div#banner").addClass("day" + date.getDay());
Of course, the issue with both these options are that you need to have a different banner for each day. They're just some ways you can do it (but definitely not the only ways)

Categories

Resources