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

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)

Related

Converting Moment.js to Day.js

I recently started working on a Work Day Schedule project that requires me to use jQuery, HTML and Day.js. This project requires that I display a clock at the top of the page, text areas that can be written in and saved to local storage (this text stays even when page is reloaded) and the color of each time block is based on whether it is past(gray), present (red), or future (green).
I have displayed the clock and figured out how to keep text saved in the text area but I cannot figured out how to keep the time blocks appropriately colored based on what time it is.
This is my javascript. The documentation I found to help was sadly written in moment.js and I'm wondering how I would convert this to Day.js to meet the project requirements.
var dateTime = $('#dateTime');
var saveBtn = document.querySelector(".saveBtn");
var currentHour = moment().hour();
function printDateTime() {
var date = moment().format("dddd, MMM Do YYYY")
dateTime.text(date);
}
function hourTracker() {
$('.timeSchedule').each(function () {
var schedulehHour = $(this).attr("id").split("time")[1];
console.log("currentHour " + currentHour)
console.log("schedulehHour " + schedulehHour)
if (schedulehHour < currentHour) {
$(this).addClass("past");
}
else if (schedulehHour == currentHour) {
$(this).addClass("present");
}
else {
$(this).addClass("future");
}
})
}
$(".saveBtn").on("click", function () {
var value = $(this).siblings(".description").val();
var time = $(this).parent().attr("id");
localStorage.setItem(time, value);
})
$("#time08 .description").val(localStorage.getItem("time08"));
$("#time09 .description").val(localStorage.getItem("time09"));
$("#time10 .description").val(localStorage.getItem("time10"));
$("#time11 .description").val(localStorage.getItem("time11"));
$("#time12 .description").val(localStorage.getItem("time12"));
$("#time13 .description").val(localStorage.getItem("time13"));
$("#time14 .description").val(localStorage.getItem("time14"));
$("#time15 .description").val(localStorage.getItem("time15"));
$("#time16 .description").val(localStorage.getItem("time16"));
$("#time17 .description").val(localStorage.getItem("time17"));
printDateTime();
hourTracker();
I tried writing in moment.js but needs to be in day.js.

Is it possible to current time dynamicly displayed in web pages in chrome browser?

what I need is to display current time dynamically in the web page I'm visiting with chrome browser, just like it's inserted in the original web page, or can it be displayed as background...?
I don't get what you exactly want to do... but current time can easily be read using the Date object. Creating a new Date object without any parameters will result in the current time Date object.
To insert it into the page you can do something like this:
// Create a div and append it to the <body>
var div = document.createElement("div");
div.id = "time";
document.body.appendChild(div);
function clock() {
var now = new Date(),
h = now.getHours(),
m = now.getMinutes(),
s = now.getSeconds();
// Put the current time (hh:mm:ss) inside the div
div.textContent =
(h>9 ? "" : "0") + h + ":" +
(m>9 ? "" : "0") + m + ":" +
(s>9 ? "" : "0") + s;
}
// Execute clock() every 1000 milliseconds (1 second)
setInterval(clock, 1000);
The above code will insert a div inside the page and update its text every second with the current time, like a clock. Now you should style it to be always visible, something like this:
#time {
position: fixed;
z-index: 999999999;
top: 0;
left: 0;
}
The above CSS will fix the element on the top left corner of the page. You can style it like you want and move it to some other part of the page.

Dynamic content depending on weekday

I need some sort of script to display diffrent content depending on the day of the week, mainly images. This is what I've tried
<script>
function myFunction() {
var d = new Date();
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="img src="http://totalscript.ro/logo.png";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";
var x = document.getElementById("demo");
x.innerHTML=weekday[d.getDay()];
}
</script>
I want to make this able to display images. Can you help?
You can do the following:
var images = [
'http://my.site.com/img1.jpg',
'http://my.site.com/img2.jpg',
'http://my.site.com/img3.jpg',
'http://my.site.com/img4.jpg',
'http://my.site.com/img5.jpg',
'http://my.site.com/img6.jpg',
'http://my.site.com/img7.jpg',
];
function placeImage(id, images) {
document.getElementById(id).innerHTML = [
'<img src="',
images[(new Date()).getDay()],
'"/>'
].join('');
}
placeImage('demo', images);
Some Enhancements
Placing array of image sources outside the function will prevent recreation of array each time function is called
Using function parameters make it more generic and allow to populate for example another image container or take images from another source
[...].join('') is kind of string buffer that for old browsers may provide better performance
Not sure if you are just looking at how to assign an image to an item in JQuery? If that is it
$("#demo").attr("src","http://imageLocation");
or if you want to use your already created variable, which is using raw javascript:
x.attr("src","http://imageLocation");

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

Splash Page Video (jQuery Hide) Reveal Index Underneath Issue

I need to have a splash page, but I don't want to make it my index, so I am using this solution.
I am using this technique:
http://jsfiddle.net/JjvzT/
on this page:
http://www.kineticoriginsofrhythm.com/
But I cant get the "Enter" button to reveal the index page below. Any Suggestions? It just flickers and jumps back to the Video Splash Page.
Also whats the js cookie code that makes it only appear once per day?
Thank You Very Much.
Also, if you can save your "anti-Splash" debates for another time that would be great. Client "MUST HAVE" this splash page. Not my idea.
Change the href attribute for your "Enter" anchor to "#". Right now you are redirecting them to the same page after hiding the splash, which is forcing them to load the page in its initial state again.
EDIT: For the cookie,
jQuery(function(){
if(document.cookie.indexOf("firstvisit") != -1){
$("#splash").hide();
$("#container-index").show();
}
else{
$("#splash span").click(function() {
$("#splash").hide();
$("#container-index").show();
var expireDate = new Date();
/* sets expire date to current date + 1 day */
expireDate.setDate(expireDate.getDate() + 1);
var newCookie = "firstvisit=0;expires=" + expireDate.toUTCString();
document.cookie = newCookie;
});
}
});
Caveat: I haven't tested this. See here for more on JavaScript and cookies: http://www.w3schools.com/JS/js_cookies.asp
I took ZDYN's answer and created splash.js, which can simply be added to your splash page (not a hidden div) and to the page that you want to redirect from, ie. index.html or something.
Anyway, here's the commented, working code:
/*
1. Create a separate html page to be the splash page
2. Out a referrence to this script in the splash page
-put below the "jquery.js" script reference
<script type="text/javascript" src="Scripts/splash.js"></script>
3. Put a reference to this script in every page that you want to have the splash page appear on
-put below the "jquery.js" script reference
<script type="text/javascript" src="Scripts/splash.js"></script>
4. Set the "splashPageName" below to the file name of the splash page
5. Set the date variables below
*/
var splashPageName = "splash.html";
var endSplashDate = new Date("12/7/2011");
var expireCookieDate = new Date();
(function() {
var url = window.location.toString();
if (url.toLowerCase().indexOf(splashPageName) >= 0) {
/* sets expire date to date + 1 day */
expireCookieDate.setDate(expireCookieDate.getDate() + 1);
var newCookie = splashPageName + "=0;expires=" + expireCookieDate.toUTCString();
document.cookie = newCookie;
}
else {
if (document.cookie.indexOf(splashPageName) != -1) {
//stay here, they've already seen the splash page
}
else {
var today = new Date();
if (endSplashDate > today) {
window.location = splashPageName;
}
}
}
} ());
Try this
$(document).ready(function(){
$("#splash").click(function() {
$(this).hide();
$("#container-index").show();
});
});

Categories

Resources