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();
Related
How can i check when a value on input is changed.
I have a calendar and when i click on calendar it changes the value on input , but when im trying to see if it has changed its not working. i have tried AddEventListener, also jquery on change, also i sent a function on change to call it but none of them is working.
<input type="text" id="date" class="date" onchange="changed()" name="" >
function changed(){
alert("hello world");
}
Main js file for creating the calendar :
This function creates the calendar on my php file .
And then when on click it gets the value on the input with id #date
But When im trying to see if value has changed it is not working .
// Initialize the calendar by appending the HTML dates
function init_calendar(date) {
$(".tbody").empty();
$(".events-container").empty();
var calendar_days = $(".tbody");
var month = date.getMonth();
var year = date.getFullYear();
var day_count = days_in_month(month, year);
var row = $("<tr class='table-row'></tr>");
var today = date.getDate();
// Set date to 1 to find the first day of the month
date.setDate(1);
var first_day = date.getDay();
// 35+firstDay is the number of date elements to be added to the dates table
// 35 is from (7 days in a week) * (up to 5 rows of dates in a month)
for(var i=0; i<35+first_day; i++) {
// Since some of the elements will be blank,
// need to calculate actual date from index
var day = i-first_day+1;
// If it is a sunday, make a new row
if(i%7===0) {
calendar_days.append(row);
row = $("<tr class='table-row'></tr>");
}
// if current index isn't a day in this month, make it blank
if(i < first_day || day > day_count) {
var curr_date = $("<td class='table-date nil'>"+"</td>");
row.append(curr_date);
}
else {
var monthplusone = months[month];
var curr_date = $("<td class='table-date' id='"+day+"-"+monthplusone+"-"+year+"'>"+day+"</td>");
var events = check_events(day, month+1, year);
if(today===day && $(".active-date").length===0) {
curr_date.addClass("active-date");
let x = document.getElementById('date').value=day+"-"+monthplusone+"-"+year;
$('.table-date').ready(function () {
x.value;
});
show_events(events, months[month], day);
}
// If this date has any events, style it with .event-date
if(events.length!==0) {
curr_date.addClass("event-date");
}
// Set onClick handler for clicking a date
$('.table-date').on('click', function () {
document.getElementById('date').value = $(this).attr('id');
});
curr_date.click({events: events, month: months[month], day:day}, date_click);
row.append(curr_date);
}
}
// Append the last row and set the current year
calendar_days.append(row);
$(".year").text(year);
}
Notice that change is actually triggered when the input is not focused anymore.
document.getElementById("date").addEventListener("change", function () {
alert("hello world");
});
<input type="text" id="date" class="date" name="">
This works. Not sure where you're running into an issue.
function changed(){
console.log("hello world");
}
<input type="text" id="date" class="date" onchange="changed()" name="" >
EDIT: Shortened version of init_calender() for others interested in answering:
function setDate() {
document.getElementById("date").value = '19-Dec-2021'
}
I basically agree with #Spankied in that you should try and shorten your code to the point where you are having the issue. However, after looking at your code it seems to me that you want the following function
$('.table-date').on('click', function () {
document.getElementById('date').value = $(this).attr('id');
});
to not only change the value in your #date input but also trigger its change event-handler function. You can do that by changing it to something like
$('.table-date').on('click', function () {
document.getElementById('date').value = $(this).attr('id');
$("#date" ).change();
});
jQuery.change() without any arguments will trigger a predefined "change"-event on the DOM-object that is selected by the jQuery-object.
You can use js to do that:
let x = $(...) //select the input box
let val = x.value;
function repeat() {
if (val !== x.value) {
change()
}
}
setInterval(repeat, 100)
This checks if the result is the same.
This might make your site a bit slow and it might look odd but this will work in just every case
<script>
let Oldvalue = $('.date')[0].val();
setInterval(() => {
let currentValue = $('.data')[0].val()
if (Oldvalue != currentValue){
//do whatever but in end write this
Oldvalue = currentValue;
}
}, 10);
</script>
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.
I'm using the code by Arg0n from add class if date is today which works great! I was wondered if it's possible to add only one class, so if attribute data-date equals today add class .active, else add class to the previous date (next available data-date). So there will always be one element highlighted.
An added complication is the iframe which loads the active date's html file.
A visual diagram of the process may make it clearer
Hopefully any solutions will help someone else out there too. Any help appreciated.
$(document).ready(function(){
// Add class="active" to calendar archive
var currentDate = Date.parse((new Date()).toLocaleDateString());
$('.enewsarchive a').each(function(){
var specifiedDate = $(this).data('date');
var yr = $(this).data('date').substr(0,4);
var mth = $(this).data('date').substr(5,2);
var enewsurl = 'http://www.example.com/images/emails/' + yr + '/' + mth + '/' + specifiedDate + '.html';
var tdate = Date.parse(specifiedDate);
if (!isNaN(tdate) && tdate == currentDate){
$(this).addClass('active'); // today
$('#enews').attr('src',enewsurl); // change current iframe
} else if (!isNaN(tdate) && currentDate - tdate > 0){
$(this).addClass(''); // past dates
$('#enews').attr('src',enewsurl);
} else {
$(this).addClass(''); // future
}
});
// Load iframe with archives
$('.enewsarchive a').click(function(e){
e.preventDefault();
$('#enews').attr('src',$(this).attr('href'));
$('.enewsarchive a.active').removeClass('active');
$(this).addClass('active');
});
});
.enewsarchivepost{float:left}
.enewsarchive .active .enewsarchivecalendar{background:#c00;color:#fff}
.enewsarchivecalendar{padding:10px;width:100px;background:#eee}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="enews">
<div class="enewsiframe">
<iframe src="http://www.example.com/enews/2018/03/2018-03-01.html" id="enews" width="940" height="auto" frameborder="0" scrolling="auto" style="border:none;"></iframe>
</div>
<div class="enewsarchive">
<div class="enewsarchivepost">
<a href="http://www.example.com/enews/2018/04/2018-03-01.html" data-date="2018-04-01" target="enews">
<p class="enewsarchivecalendar">01<em>APR</em></p>
</a>
</div>
<div class="enewsarchivepost">
<a href="http://www.example.com/enews/2018/03/2018-03-14.html" data-date="2018-03-14" target="enews">
<p class="enewsarchivecalendar">14<em>MAR</em></p>
</a>
</div>
<div class="enewsarchivepost">
<a href="http://www.example.com/enews/2018/03/2018-03-08.html" data-date="2018-03-08" target="enews">
<p class="enewsarchivecalendar">08<em>MAR</em></p>
</a>
</div>
</div>
</div>
Try this one
$(document).ready(function(){
today = new Date();
today.setDate(today.getDate()+1);
var currentDate = Date.parse((today).toLocaleDateString());
date = [];
$('.enewsarchive a').each(function(){
const [year, month, day] = $(this).attr('data-date').split("-");
temp = new Date($(this).attr('data-date').replace( /(\d{2})-(\d{2})-(\d{4})/, "$1/$3/$2" ));
if (currentDate >= temp) {
date.push(temp);
}
});
curr = new Date(Math.max.apply(null, date.map(function(e) {
return new Date(e);
})));
attr = curr.getFullYear()+'-'+(("0" + (curr.getMonth() + 1)).slice(-2))+'-'+(("0" + curr.getDate()).slice(-2))
$('.enewsarchivepost a[data-date="'+attr+'"]').addClass('active');
// Load iframe with archives
$('.enewsarchive a').click(function(e){
e.preventDefault();
$('#enews').attr('src',$(this).attr('href'));
$('.enewsarchive a.active').removeClass('active');
$(this).addClass('active');
});
});
If I have understood your question correctly you need to add .active class in only one a tag at a time?
If this is what you are looking for you can simply use below code.
$(".enewsarchive a.active").removeClass('active'); //remove active class from a tag before adding it
$(this).addClass('active'); // today
Is this what you are looking for? Or have I misunderstood the question?
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();
};
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");