jQuery - combining variable with image src to replace image attr - javascript

Below is my script which is suppose to show the user a greeting message based on their local time. I got the script from another stack overflow answer, but am having trouble with replacing the image src. I get the following error
Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:8888/neil-wp/imgurl%20+%20second.jpg
$(document).ready(function () {
datetoday = new Date(); // create new Date()
timenow = datetoday.getTime(); // grabbing the time it is now
datetoday.setTime(timenow); // setting the time now to datetoday variable
hournow = datetoday.getHours(); //the hour it is
imgselector = $('#greeting-img')
imgpath = 'wp-content/themes/neil/img/'
if (hournow >= 16.5) { // if it is after 4:30pm
imgselector.attr("src","imgpath + goodevening.gif");
}
else if (hournow >= 12) { // if it is after 12pm
imgselector.attr("src","imgpath + goodafternoon.gif");
}
else if (hournow >= 0) { // if it is after midnight
imgselector.attr("src","imgpath + goodmorning.gif");
}
});
// Wait for window load
$(window).load(function() {
$(".greeting").delay(2000).fadeOut("200");
});
Here is my HTML
<div class="greeting">
<div class="greeting-inner">
<img id="greeting-img" src="">
</div>
</div>

as imgpath is variable, use:
imgselector.attr("src",imgpath + "goodmorning.gif");

Related

Display different logo on website depending on date

I've been trying to display a different logo on my website depending on the date (to add a christmas logo that will automatically be displayed in december).
Here's what I've got for now:
<img class="logo" id="global_logo" style="height:56%; margin-top:12px;" src="">
<script>
function initLogo(){
var GlobalDate = date.getMonth()+1;
var GlobalLogo = document.getElementById("global_logo");
if (GlobalDate == 12) {
GlobalLogo.src = "xmas_mgmods-animated.gif"
}else{
GlobalLogo.src = "logo1.png"
}
/**/
alert('Script working');
}
initLogo();
</script>
I've got two problems: first, the logo is not showing up at all (no logo is)
Second: I want to know if I can set the script to also change the style applied for each logo (the style="height:56%; margin-top:12px;"is only needed for the gif, and not for the png).
I've tried to add a line instead of changing the source depending of the ID:
function initLogo(){
var GlobalDate = date.getMonth()+1;
var content = document.getElementById("global_logo");
var GlobalIcon = "";
if (GlobalDate == 12) {
html += "<img class='logo' src='logo1.png'>";
}else{
html += "<img class='logo' style='height:56%; margin-top:12px;' src='xmas_mgmods-animated.gif'>";
}
content.innerHTML += GlobalIcon;
alert('Script working');
}
It doesn't work...
You were using date without having it defined anywhere, assuming you copied it from somewhere else; it was supposed to be an instance of Date.
function initLogo(){
const date = new Date();
var GlobalDate = date.getMonth()+1;
var GlobalLogo = document.getElementById("global_logo");
if(GlobalDate == 12) {
GlobalLogo.innerHTML = `<img class="logo" src="xmas_mgmods-animated.gif" style="height:56%; margin-top:12px;">`;
}
else {
GlobalLogo.innerHTML = `<img class="logo" src="logo1.png">`;
}
}
initLogo();
<div id="global_logo"></div>

Stuck on incrementing date in JavaScript

I am trying to create a page that grabs a set of PDFs sorted by date. I can't seem to increment the date correctly. I'm not sure what's going wrong here. I rewrote the code twice now. No luck.
The current issue is that the set variables for the date do not keep the value of the date as a whole. IE incrementing from 12, 31, 2018, or in the case of the URL format 20181231, should result urlIncremented=20190101. January 1st, 2019, but the result of my code is urlIncremented=20181232.
The end result of one loop if set to June 8th 2018, should be: url20180608
I've searched for advice on here, and found a JS file called Date.JS; I've imported it and it was looking promising but just consoles out a part of its code, namely:
function () {
if (this._isSecond) {
this._isSecond=false;
return this;
}
if (this._same) {
this._same=this._is=false;
var o1=this.toObject(),
o2=(arguments[0] || new Date()).toObject(),
v="",
k=j.toLowerCase();
for (var m=(px.length-1); m>-1; m--) {
v=px[m].toLowerCase();
if (o1[v]!=o2[v]) {
return false;
}
if (k==v) {
break;
}
}
return true;
}
if (j.substring(j.length-1)!="s") {
j+="s";
}
return this["add"+j](this._orient);
}
Just a heads up I do not yet know jQuery, I was just playing with it to see if it would help..
Here is my actual code.
let url = "blank",
firstRun = true;
/*
function setDateByIncrement(currentSetDate){
let newDate,
currentDate = new Date(),
day = currentDate.getDate()+1,
month = currentDate.getMonth() + 1,
year = currentDate.getFullYear();
console.log(newDate);
newDate = (year+month+day);
console.log(newDate);
return newDate;
}
*/
// use on First run to set the url and date.
//3
function setURL(){
let urlIncremented = url + dateIncrementMethod();
return urlIncremented;
}
// will open x number of new windows containing URL
//2
function grabOpenPDF(maxNumberDays){
let urlSet = setURL();
//Set the variable for max days.
for(let x = 0; x < maxNumberDays; x++){
//window.open(urlSet);
console.log("It works: " + x);
urlSet = setURL();
}
}
/* TODO Add automatic download for MASS print.
function downloadPDF(){
}
*/
//Starts the task.
//1
function start(load){
console.log("Current Address: " + url);
if(load === 1){
console.log("Event load active. ");
let maxDay = document.querySelector('#maxNumberDays').value;;
grabOpenPDF(maxDay);
}else{
console.log("Event load skip. ")
let maxDay = document.getElementById('maxNumberDays').value;
}
}
//4
function dateIncrementMethod(current){
let dateIncrement;
if(firstRun=== true){
var today = new Date($('#date-input').val());
console.log("FirstRun check in 4. ")
}
firstRun = false;
var tomorrow = today.add(1).day;
console.log(tomorrow);
return tomorrow;
}
/* Possibly Deprecated
//let dateIncrement;
let date = new Date($('#date-input').val());
console.log(date);
day = date.getDate() + 1;
if(firstRun === true){
month = date.getMonth() + 1;
year = date.getFullYear();
//dateIncrement = (parseToAPI(year, month, day));
firstRun = false;
parseToAPI(year, month, day);
}else{
day = date.getDate()+1;
parseToAPI(year, month, day);
}
}
*/
function parseToAPI(year, month, day){
let apiDate;
console.log("Entered parse");
this.day = day;
this.month = month;
let d = this.day.toString(),
m = this.month.toString();
if(d.length === 1){
console.log("Entered First IF");
this.day = ('0') + day;
//console.log(day);
}
if(m.length === 1){
console.log("Entered Second IF")
this.month = ('0') + month;
}
apiDate = (year + "" + "" + month + "" + day);
console.log(apiDate);
return apiDate;
}
<!DOCTYPE html>
<html>
<script src="https://code.jquery.com/jquery-2.0.3.js"></script>
<script src="https://doc-0k-6g-docs.googleusercontent.com/docs/securesc/77gdpvi38k94jj7nmfcm2n3tq7a0ifhu/ehjuusajghqnne5r2ncfvj30cmbll20p/1545105600000/17500114768188980350/17500114768188980350/1CDff-uWGahZX7aLt6WQfV1-R5PFHwiK8?e=download&nonce=52qkphatg2scm&user=17500114768188980350&hash=3uc9iql9m90vcrv3a7mhg8fdjce1b4fe.js"></script>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input type="date" id="date-input" required />
<input type="maxNumberDays" id="maxNumberDays" max="31" required />
<button id="startPDFApp" onClick="start()">Print PDFs</button>
<button id="startPDFApp" onClick="start(1)">Load PDFs</button>
<div id="info"></div>
</body>
</html>
While I haven't invested enough time trying to understand what you're really trying to do, it seems like there's a lot of unnecessary code. I'll leave it to you to decipher what you need.
I can only express that the below code is in an in-between state. It includes a number of changes, most of which I'll point out, but I didn't want to change it too drastically that it all looked foreign. So even the code below has much to be improved on.
Significant changes include:
Because your URL is increasing by one, you may benefit by using a function generator. Inside it increases the date by calling setDate on itself using it's own date + 1. It also uses a string function, padStart, to ensure months and days are always two-digit.
Getting rid of firstRun variable as it is no longer needed
Inside your grabOpenPDF, all you need to do is get the next value returned by the URL generator function
let URL_GEN = UrlGenerator('blank'),
URL = URL_GEN.next().value;
//Starts the task.
//1
function start(load) {
let startDate = new Date(document.querySelector('#date-input').value)
// overwrite global with values
URL_GEN = UrlGenerator('blank', startDate)
URL = URL_GEN.next().value
console.log("Current Address: " + URL);
if (load === 1) {
console.log("Event load active.");
let maxDay = document.querySelector('#maxNumberDays').value;
grabOpenPDF(maxDay);
} else {
console.log("Event load skip.")
let maxDay = document.getElementById('maxNumberDays').value;
}
}
/* URL generator */
function* UrlGenerator(url, dt=new Date()) {
while (true){
yield url + dt.getFullYear() + (''+(dt.getMonth()+1)).padStart(2,'0') + (''+dt.getDate()).padStart(2,'0');
// increase day for next iteration
dt.setDate(dt.getDate()+1);
}
}
// will open x number of new windows containing URL
function grabOpenPDF(maxNumberDays) {
//Set the variable for max days.
for (let i=0; i < maxNumberDays; i++) {
console.log("It works: " + i, URL);
URL = URL_GEN.next().value;
}
}
<script src="https://doc-0k-6g-docs.googleusercontent.com/docs/securesc/77gdpvi38k94jj7nmfcm2n3tq7a0ifhu/ehjuusajghqnne5r2ncfvj30cmbll20p/1545105600000/17500114768188980350/17500114768188980350/1CDff-uWGahZX7aLt6WQfV1-R5PFHwiK8?e=download&nonce=52qkphatg2scm&user=17500114768188980350&hash=3uc9iql9m90vcrv3a7mhg8fdjce1b4fe.js"></script>
<input type="date" id="date-input" value="12/29/2018" required />
<input type="maxNumberDays" id="maxNumberDays" value="5" max="31" required />
<button id="startPDFApp" onClick="start()">Print PDFs</button>
<button id="startPDFApp" onClick="start(1)">Load PDFs</button>
<div id="info"></div>
This can be further improved by better management of your globals, more straightforward code (more simply laid out), and perhaps better naming conventions. Also, it's generally a no-no to be putting event handlers directly in the HTML these days, you could bind those event dynamically via JavaScript.
I can't seem to increment the date correctly.
If you have a dates like "20181231" with a format YYYYMMDD, you must parse it to the date parts, increment the day, then format it back to an appropriate string. A date manipulation library can help, or you can write a custom function.
You can do it without generating a Date, but it's a bit more code and logic.
E.g.
// Accept date string in format YYYYMMDD
// and return next date in same format
function getNextDate(s) {
let z = n => ('0'+n).slice(-2);
let [y, m, d] = s.match(/^\d{4}|\d{2}/g);
let date = new Date(y, m-1, d);
date.setDate(date.getDate() + 1);
return date.getFullYear() + z(date.getMonth()+1) + z(date.getDate());
}
['20181230','20181231','20190101'].forEach(
s => console.log(`${s} => ${getNextDate(s)}`)
);
You can also use a library like moment.js:
function getNextDate(s) {
return moment(s, 'YYYYMMDD')
.add(1, 'day')
.format('YYYYMMDD');
}
['20181230','20181231','20190101'].forEach(
s => console.log(`${s} => ${getNextDate(s)}`)
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
If you are using moment.js for other things, include it. But if this is the only date stuff you need it for, it's a bit of overhead you don't need.
A lot of your code is a little unclear and the logic is not obvious, in regards to what should happen. Here is what I could gleam:
User should enter a Date, that is required
When user click Load PDF, a list of dates should be calculated
Assuming today until selected date, with a max of 31 days in the future
The script checks if a PDF exists for each of the days in the list
I suspect you were just looking for a way to generate a pattern for the days. I may have more here than you need.
$(function() {
function grabOpenPDF(end) {
var current = new Date();
end.setDate(end.getDate() + 1);
var urls = [];
while (current < end) {
urls.push({
name: $.datepicker.formatDate("yymmdd", current),
url: "https://example.com/getpdf.php?date=" + $.datepicker.formatDate("yymmdd", current),
hit: null
});
current.setDate(current.getDate() + 1);
};
console.log(urls);
$.each(urls, function(k, v) {
$.ajax({
url: v.url,
success: function(data) {
v.hit = true;
$("#info").append("<div>" + (k + 1) + ". " + v.url + ", hit: " + v.hit.toString() + "</div>");
},
error: function(data) {
v.hit = false;
$("#info").append("<div>" + (k + 1) + ". " + v.url + ", hit: " + v.hit.toString() + "</div>");
}
});
});
}
var dtInp = $("#date-input").datepicker({
dateFormat: "mm/dd/yy",
maxDate: "+31d",
minDate: new Date()
});
$(".today").html($.datepicker.formatDate("mm/dd/yy", new Date()));
$("#printPDF").click();
$("#startPDF").click(function(e) {
e.preventDefault();
$("#info").html("");
if ($("#date-input").val() === "") {
$("#date-input").focus();
return false;
}
console.log("Event load active.");
grabOpenPDF(dtInp.datepicker("getDate"));
});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://doc-0k-6g-docs.googleusercontent.com/docs/securesc/77gdpvi38k94jj7nmfcm2n3tq7a0ifhu/ehjuusajghqnne5r2ncfvj30cmbll20p/1545105600000/17500114768188980350/17500114768188980350/1CDff-uWGahZX7aLt6WQfV1-R5PFHwiK8?e=download&nonce=52qkphatg2scm&user=17500114768188980350&hash=3uc9iql9m90vcrv3a7mhg8fdjce1b4fe.js"></script>
<div class="ui-widget ui-widget-content" style="padding: 7px;">
<p>From <span class="today">Today</span> until <input type="text" id="date-input" placeholder="mm/dd/yy" required style="border: 0; width: 8em; border-radius: 0; border-bottom: 1px solid #eee;" /></p>
<button id="printPDF">Print PDFs</button>
<button id="startPDF">Load PDFs</button>
<div id="info"></div>
</div>
As I mentioned, you can use jQuery and jQuery UI to help you out. Take a look: http://api.jqueryui.com/datepicker/
When the user clicks on the field, they can select a date between today and 31 days into the future. they can then click the "Load PDF" button and it will grab the PDFs by iterating each day and performing some action.
Good reference for incrementing the date: Incrementing a date in JavaScript
Personally, I would push this off to the server instead of doing this in the browser. Assuming there is a DB of PDFs, it would be faster to send a start and end date to the server and have it perform a SELECT query and return the results. You're sending two bits of data to the server and getting a list of results versus hammering around for PDFs hoping to find your nail. using the above example, you could set the option, minDate: "-6m" and just limit the range the user might select a start and end date.
Hope this helps. Feel free to comment and ask for more clarity if needed.

Impossible to use JavaScript twice in a page

I am the new administrator of a website I did not created (professionnals did, I'm just an IT student beginning with JavaScript). I wanted to add a timer on the homepage of the website with the following working code I founded on the Internet:
<script language="JavaScript1.2">
//##################################################
// Author: ricocheting.com
// For: public release (freeware)
// Date: 4/24/2003 (update: 6/26/2009)
// Description: displays the amount of time until the "dateFuture" entered below.
// NOTE: the month entered must be one less than current month. ie; 0=January, 11=December
// NOTE: the hour is in 24 hour format. 0=12am, 15=3pm etc
// format: dateFuture = new Date(year,month-1,day,hour,min,sec)
// example: dateFuture = new Date(2003,03,26,14,15,00) = April 26, 2003 - 2:15:00 pm
dateFuture = new Date(2014,10,25,20,00,00);
// TESTING: comment out the line below to print out the "dateFuture" for testing purposes
//document.write(dateFuture +"<br />");
//###################################
//nothing beyond this point
function GetCount(){
dateNow = new Date(); //grab current date
amount = dateFuture.getTime() - dateNow.getTime(); //calc milliseconds between dates
delete dateNow;
adversaire = "Saastal";
// time is already past
if(amount < 0){
document.getElementById('countbox').innerHTML="Le match Sion - " + adversaire + " a débuté !";
}
// date is still good
else{
days=0;hours=0;mins=0;secs=0;out="";
amount = Math.floor(amount/1000);//kill the "milliseconds" so just secs
days=Math.floor(amount/86400);//days
amount=amount%86400;
hours=Math.floor(amount/3600);//hours
amount=amount%3600;
mins=Math.floor(amount/60);//minutes
amount=amount%60;
secs=Math.floor(amount);//seconds
if(days != 0){out += days +" jour"+((days!=1)?"s":"")+", ";}
if(days != 0 || hours != 0){out += hours +" heure"+((hours!=1)?"s":"")+", ";}
if(days != 0 || hours != 0 || mins != 0){out += mins +" minute"+((mins!=1)?"s":"")+", ";}
out += secs +" seconde"+((secs!=1)?"s":"");
document.getElementById('countbox').innerHTML="Temps restant avant Sion - " + adversaire + " : " + out;
setTimeout("GetCount()", 1000);
}
}
window.onload=GetCount;//call when everything has loaded
</script>
<div id="countbox"></div>
The only problem is that when I add this code (which works), then another JavaScript code already on the page (scrolling text) doesn't work anymore. Here is the code of the scrolling text but what is important is that I founded it with "Right click/view page source" and I cannot change it, except for the text part (in the admin page, I have a textbox in which I write the text that is going to scroll and according to the following code, this text is just a variable part of the JavaScript function) :
<h3 class="replace">Agenda</h3>
<script language="JavaScript1.2">
// Distributed by http://www.hypergurl.com
// Scrollers width here (in pixels)
var scrollerwidth="180px";
// Scrollers height here
var scrollerheight="100px";
// Scrollers speed here (larger is faster 1-10)
var scrollerspeed=1;
/* Scrollers content goes here! Keep all of the message on the same line!
* var scrollercontent='<font face="Arial" color="green" size="5">
* <b>Place your content here.<br>
* vous pouvez inclure des balises HTML, des hyperliens
* Script distributed by Hypergurl.com.
* The scrolling massage will now pause on mouseover.<br>
* Thanks David for the update!</b></font>'
* le texte de la marquee doit être inclu dans une balise <div> ... </div>
* ATTENTION: les aphostrophes doivent impérativement être échappés!!!!
*/
var txt = ' '
+ 'HERE IS THE TEXT I CAN WRITE'
var scrollercontent = ''
+ txt
+ '';
var pauseit=1;
// Change nothing below!
scrollerspeed=(document.all)? scrollerspeed : Math.max(1, scrollerspeed-1) //slow speed down by 1 for NS
var copyspeed=scrollerspeed
var iedom=document.all||document.getElementById
var actualheight=''
var cross_scroller, ns_scroller
var pausespeed=(pauseit==0)? copyspeed: 0
function populate(){
if (iedom){
cross_scroller=document.getElementById? document.getElementById("iescroller") : document.all.iescroller
cross_scroller.style.top=parseInt(scrollerheight)+8+"px"
cross_scroller.innerHTML=scrollercontent
actualheight=cross_scroller.offsetHeight
}
else if (document.layers){
ns_scroller=document.ns_scroller.document.ns_scroller2
ns_scroller.top=parseInt(scrollerheight)+8
ns_scroller.document.write(scrollercontent)
ns_scroller.document.close()
actualheight=ns_scroller.document.height
}
lefttime=setInterval("scrollscroller()",50)
}
window.onload=populate
function scrollscroller(){
if (iedom){
if (parseInt(cross_scroller.style.top)>(actualheight*(-1)+8))
cross_scroller.style.top=parseInt(cross_scroller.style.top)-copyspeed+"px"
else
cross_scroller.style.top=parseInt(scrollerheight)+8+"px"
}
else if (document.layers){
if (ns_scroller.top>(actualheight*(-1)+8))
ns_scroller.top-=copyspeed
else
ns_scroller.top=parseInt(scrollerheight)+8
}
}
if (iedom||document.layers){
with (document){
if (iedom){
write('<div style="position:relative;width:'+scrollerwidth+';height:'+scrollerheight+';overflow:hidden" onMouseover="copyspeed=pausespeed" onMouseout="copyspeed=scrollerspeed">')
write('<div id="iescroller" style="position:absolute;left:0px;top:0px;width:100%;">')
write('</div></div>')
}
else if (document.layers){
write('<ilayer width='+scrollerwidth+' height='+scrollerheight+' name="ns_scroller">')
write('<layer name="ns_scroller2" width='+scrollerwidth+' height='+scrollerheight+' left=0 top=0 onMouseover="copyspeed=pausespeed" onMouseout="copyspeed=scrollerspeed"></layer>')
write('</ilayer>')
}
}
}
So my question is: do you know a way to let these two JavaScript functions work on the same page? I just want to have my timer either on the homepage, either in the scrolling text (which is also on the homepage, in the right column)...
Thank you in advance for you help.
Kinds regards,
user3507737
It looks like you're overwriting the first script's window.onload call by including the second script, which has its own .onload call.
I would remove the two lines that begin with window.onload from the scripts included above, and add a third <script> tag in your page that does the following:
window.onload = function () {
GetCount();
populate();
};
This should get both your scripts running.
You assign an action to the window.onload event twice. In the first block of javascript you have window.onload=GetCount; and in the second you have window.onload=populate (which needs a semicolon at the end, by the way).
You can only assign one function to the onload event, so it would be best to make a function that calls both GetCount and populate and assign this new function to your window.onload. See more in this answer.
You need to remove the current code that binds to onload and replace it with something like:
window.onload = function () {
populate();
GetCount();
};

Open overlay if today is current day

I'm in the process of making a Christmas calendar, and I have an overlay which should open if the date is ex 1.12.13, otherwise it should alert the amount of days until it's available. I've tried a lot of different things but can't get it to work.
Here is what should be displayed if date is something:
<!-- overlayed element, which is styled with external stylesheet -->
<div class="apple_overlay black" id="photo1">
<img src="images/onecom.png" alt="onecom" width="496" height="496" />
<div class="details">
<h2>December 1st</h2>
<p>
Some script that does something
</p>
</div>
</div>
What I have tried
function dooropen(door) {
today=new Date();
daynow=today.getDate();
monthnow=today.getMonth();
if (monthnow!=11 && monthnow!=0) {
alert("This feature opens in December. Please come back then.");
return false;
}
if (daynow==door-1) {
alert("Come back tomorrow to see what's behind that door!");
return false;
}
if (door>daynow) {
alert("You\'ll have to wait "+(door-daynow)+" days before that door's available!");
return false;
}
}
This may work, as i can see you may have some different div for each day of the month since you are using numeric id id="photo1">, so you can try to get the dates :
var today = new Date();
var dd = today.getDate() + 1;
var mm = today.getMonth() + 1;
after that get the main parent of all divs and put it in a jquery object:
var $number_of_objects = $("#parent_div img");
once you have all those you need to put them inside a for loop to count them and match to later exit the function:
for (var i = 1; i < $number_of_objects.length; i++) {
console.log("value of i " + i);
if(i == dd){
console.log(' break');
break;
}
$("#apple img[rel='#photo"+i+"']").overlay({
effect: 'apple'
});
}
it should give you a good start point to improve it and add more feature to the script :)
happy coding
<script>
var date = new Date(),
year = date.getYear(),
month = date.getMonth()+1,
day = date.getDate();
if(day == 13){ // today is 13
code
}else{
code
}
</script>
Just show the element you want at the end of your method..
$('#photo1').show();

Remember image number in JavaScript slide show across pages

I have a pure html+JavaScript slideshow I am making. The slideshow is in a sidebar of the website that is loaded with php for each page that has the slideshow sidebar. The only page without the sidebar is the main page.
The slide show is working fine. However, understandably, each time I go to a new page with the sidebar, the slideshow starts over. Makes sense since the javascript reloads with each new page.
I would like to find some way to have the slideshow remember its place so that when I go to a new page the slide show just continues where it left off on the previous page. I can only think of two solutions, one seem brute force, and one I don't know how to do:
Write the current image number to a file and read it each time the
slideshow loads.
Somehow use ajax, but I haven't learned to use ajax
yet (would it work?).
Any suggestions? Oh, and please I'm learning javascript, jQuery and ajax are next, but...
Here is my code:
simpleslideshow.html:
<html>
initializeSlideShow();
<table width="100">
<tr>
<td align="left"> <div id="previous"> Previous</div></td>
<td align="right"> <div id="next">Next</div></td>
<td align="right"> <div id="auto">auto</div></td>
<td align="right"> <div id="stop">stop</div></td>
</tr>
</table>
<img src="" id="slideshow-image" width="400px" height="auto" style="display:block;"/>
simpleslideshow.js:
var inaterval_ID = 0;
var image_number = 0;
var num_images = images_with_captions.length;
function change_image(increment){
image_number = image_number + increment;
image_number = (image_number + num_images) % num_images;
var string = images_with_captions[image_number].source;
document.getElementById("slideshow-image").src = string;
}
function initializeSlideShow() {
//var string = images_with_captions[0].source;
//document.getElementById("slideshow-image").src = string;
auto();
}
function auto() {
interval_ID = setInterval("change_image(1)", 1000);
}
function stop() {
clearInterval(interval_ID);
}
image_caption_list.js:
var images_with_captions = new Array(
{
source: "http://www.picgifs.com/clip-art/flowers-and-plants/flowers/clip-art-flowers-435833.jpg",
caption: "flower 1"
},
{
source: "http://www.picgifs.com/clip-art/flowers-and-plants/flowers/clip-art-flowers-511058.jpg",
caption: "flower 2"
},
{
source: "http://www.picgifs.com/clip-art/flowers-and-plants/flowers/clip-art-flowers-380016.jpg",
caption: "flower 3"
}
);
Edit: I can't get a jsfiddle to work. But here is a live version that may or may not be up for a while:
You can save the current slide value to either a cookie or localStorage each time you change to a new slide and then when you start up the slideshow on a new page, you can read the previous slide value and start from that slide number.
Here's reading the previous slide number:
function initializeSlideShow() {
// get prior slideshow num
var lastSlideNum = +readCookie("lastSlideNum");
// if there was a prior slideshow num, set that as the last one we used
if (lastSlideNum) {
image_number = lastSlideNum;
}
auto();
}
Here's saving the slideshow number each time it changes:
function change_image(increment){
image_number = (image_number + increment) % num_images;
// remember what slide we're on for subsequent page loads
createCookie("lastSlideNum", image_number);
var string = images_with_captions[image_number].source;
document.getElementById("slideshow-image").src = string;
}
And, here's a simple cookie library:
// createCookie()
// name and value are strings
// days is the number of days until cookie expiration
// path is optional and should start with a leading "/"
// and can limit which pages on your site can
// read the cookie.
// By default, all pages on the site can read
// the cookie if path is not specified
function createCookie(name, value, days, path) {
var date, expires = "";
path = path || "/";
if (days) {
date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires=" + date.toGMTString();
}
document.cookie = name + "=" + value + expires + "; path=" + path;
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
A localStorage implementation (which would not remember the slide in IE versions before IE8) would look like this:
function initializeSlideShow() {
// get prior slideshow num
var lastSlideNum;
// localStorage requires IE8 or newer
// if no localStorage, then we just don't remember the previous slide number
if (window.localStorage) {
lastSlideNum = +localStorage["lastSlideNum"];
// if there was a prior slideshow num, set that as the last one we used
if (lastSlideNum) {
image_number = lastSlideNum;
}
auto();
}
Here's saving the slideshow number each time it changes:
function change_image(increment){
image_number = (image_number + increment) % num_images;
// remember what slide we're on for subsequent page loads
if (window.localStorage) {
localStorage["lastSlideNum"] = image_number;
}
var string = images_with_captions[image_number].source;
document.getElementById("slideshow-image").src = string;
}

Categories

Resources