HTML, open link click anywhere on page - javascript

I have code for clickable background that I want to use but when I click on background its always open. How to make this code to work one per day BUT at most easiest way possible... with cookie or something else. I really need help with this. Thanks!
<body onclick="location.href='test.html';">

You can use localStorage.
<script>
function onBodyClick() {
var lastOpened = localStorage.getItem('body-opened'); // You can use another identifier instead of 'body-opened'
if (lastOpened && new Date(lastOpened).toDateString() === new Date().toDateString()) {
return true;
} else {
localStorage.setItem('body-opened', new Date().toDateString());
document.location.href = 'test.htm';
}
}
</script>
<body onclick="onBodyClick()"></body>

If you want to restrict the user to open the link only once per day. You can do something like this:
<body onclick="openLink()">
<script>
function openLink() {
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();
today = mm + '/' + dd + '/' + yyyy;
// As date object returns time as well. Which we dont need. So we remove that.
if(localStorage.getItem('date') == today) {
alert('come back tomorrow');
} else {
localStorage.setItem('date', today);
location.href='test.html';
}
}
</script>

Related

Javascript multiple var arrays

I have the following bit of javascript that blocks off dates in a calendar and displays a message instead:
var unavailableDates = ["28-7-2017", "29-7-2017", "30-7-2017", "31-7-2017", "28-8-2017", "24-12-2017", "25-12-2017", "26-12-2017", "1-1-2018", "30-3-2018", "31-3-2018", "1-4-2018", "1-2-2018", "7-5-2018", "28-5-2018", "6-8-2018", "27-8-2018", "24-12-2018", "25-12-2018", "26-12-2018", "1-1-2019"];
jQuery(function($) {
$("#Booking1arrivaldate").datepicker({
minDate: 5,
beforeShowDay: function(date) {
dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
if ($.inArray(dmy, unavailableDates) == -1) {
return [true, ""];
} else {
return [false, "", "Closed to the public for drop off and collection."];
}
}
});
});
If someone tries to select one of the dates within the var unavailableDates then it won't let them and instead displays the message.
However I need to add another var with a completely different message if those dates are selected. I have tried a few combinations of the if statement but keep getting errors in my code.
Any ideas?

Set a cookie for 1 hour and check for it on load

I want to do a little animation when an user visits the site but I don't want it to show every time the user switches between the subpages. At the moment it does the animation every time and I don't know why.
Here is my code:
$(document).ready(function() {
"use strict";
if (document.cookie.indexOf('visited') > -1) {
// They've been here before.
alert("hello again");
}
else {
// set a new cookie
var d = new Date();
d.setTime(d.getTime() + (3600 * 1000));
document.cookie = "visited=yes;" + "expires=" + d.toUTCString() + ";path=/";
// slide in navbar
sleep(100);
document.getElementById("navlist").style.left = "63%";
}
});
You can simple use sessionStorage instead of cookies like so:
$(document).ready(function(){
if(sessionStorage.getItem("visitedBefore") == undefined){
sessionStorage.setItem("visitedBefore", "1");
alert("Welcome for the first time!");
}
});
Here is the JSFiddle demo

add class if date is today

I have some boxes that represent the squares in an advent calendar. I've defined the date for each box in the data attribute which I'm using to compare against the current day. I'm trying to add a class 'today' to the box that represents the current day. I've created a fiddle to demonstrate this. How can I fix it so that today class is added to the appropriate box?
JSFiddle
$(function() {
var currentDate = Date.now();
$(".grid-item").each(function() {
var specifiedDate = $(this).data('date');
var date = Date.parse(specifiedDate);
if (!isNaN(date) == currentDate) {
$(this).addClass('today');
}
else if(!isNaN(date) && currentDate - date > 0) {
$(this).addClass('past');
}
else {
$(this).addClass('future');
}
});
});
You don't have to use Date.now() as this doesn't outputs the dates similar to the data attributes have. Instead you have to create current date as this and check in the conditions like:
$(function() {
var date = new Date(),
currentDate = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
$(".grid-item").each(function() {
var specifiedDate = $(this).data('date');
if (specifiedDate == currentDate) {
$(this).addClass('today');
} else if (currentDate > specifiedDate) {
$(this).addClass('past');
} else {
$(this).addClass('future');
}
});
});
.grid-item {
height: 170px;
width: 170px;
float: left;
background: red;
margin: 10px;
}
.today {
background: yellow;
border: red 1px solid;
}
.past {
background: black;
border: red 1px solid;
}
.future {
background: blue;
border: red 1px solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="grid-item" data-date="2015-11-23">
</div>
<div class="grid-item" data-date="2015-11-24">
</div>
<div class="grid-item" data-date="2015-11-25">
</div>
<div class="grid-item" data-date="2015-11-26">
</div>
<div class="grid-item" data-date="2015-11-27">
</div>
<div class="grid-item" data-date="2015-11-28">
</div>
<div class="grid-item" data-date="2015-11-29">
</div>
You can add class to current date using following jquery, just replace your jquery with following :-
$(function() {
var d =new Date();
var curmonth = d.getMonth()+1;
var curDate = d.getFullYear()+"-"+curmonth+"-"+d.getDate();
$(".grid-item[data-date="+curDate+"]").addClass("today");
});
A possible solution
jsfiddle
$(function() {
var currentDate = Date.now();
var a = new Date(currentDate);
$(".grid-item").each(function() {
var specifiedDate = $(this).data('date');
var date = Date.parse(specifiedDate);
var b = new Date(date);
if (!isNaN(b) && b.getMonth() == a.getMonth() && b.getDay()== a.getDay() && b.getYear() == a.getYear()) {
$(this).addClass('today');
}
else if(!isNaN(b) && a - b > 0) {
$(this).addClass('past');
}
else {
$(this).addClass('future');
}
});
});
See this JSFiddle
JavaScript
$(function() {
var currentDate = Date.parse((new Date()).toLocaleDateString());
$(".grid-item").each(function() {
var specifiedDate = $(this).data('date');
var date = Date.parse(specifiedDate);
if (!isNaN(date) && date == currentDate) {
$(this).addClass('today');
}
else if(!isNaN(date) && currentDate - date > 0) {
$(this).addClass('past');
}
else {
$(this).addClass('future');
}
});
});
There is a single mistake in your code. Date.now() gives you the current timestamp in milliseconds. While you have a date in the data-date which will not match in any case. Correct way will be to compare the date instead of timestamps. Or just take the date without the time for comparison
The easiest solution would be to create new Date() object, and set it's hours, minutes and seconds to 0 like that:
currentDate = new Date();
currentDate.setHours(0);
currentDate.setMinutes(0);
currentDate.setSeconds(0);
and then:
var date = new Date(specifiedDate);
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
Note that I am also setting date's hours, minutes and second to 0 due timezones (this can be fixed, but as I said, it seems to be the easiest way)
Or you can simply use :
$(function() {
$(".grid-item").each(function() {
$('.grid-item').eq(new Date().getDay()-1).addClass('today');
});
});
FIDDLE
Try This code
$(function() {
var currentDate = new Date();
$(".grid-item").each(function() {
var specifiedDate = $(this).data('date');
var date = new Date(specifiedDate);
if(date.setHours(0,0,0,0) == currentDate.setHours(0,0,0,0)){
$(this).addClass('today');
}
});
});
this code works for me last day. hope this helps you..
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){
dd='0'+dd
}
if(mm<10){
mm='0'+mm
}
var today = yyyy+'-'+mm+'-'+dd;
if (date == today) {
$(this).addClass('today');
}
make sure two dates are same format..

Jquery DatePicker change highlighted color onSelect of a particular date

I have this code of Jquery datepicker that I am working on.
What I want to do is change the color of the current highlighted date to grey when I click on anyother date, and the color of the clicked date to green.
The tricky part is that only the ones which are grey can turn green and viceversa but no other dates can turn into green on click.
I dont understand what I am doing wrong. Or is it that my code is completely wrong.
If anyone can help.
here's the code
$(function() {
var togo=['10/25/2013']
var datesArray=['10/27/2013','10/28/2013']
var datesArray1=['10/25/2013','10/26/2013']
var datesArray2=['10/24/2013']
$( "#datepicker" ).datepicker({
numberOfMonths: 2,
selectMultiple:true,
beforeShowDay: function (date) {
var theday = (date.getMonth()+1) +'/'+
date.getDate()+ '/' +
date.getFullYear();
return [true,$.inArray(theday, datesArray2) >=0?"specialDate":($.inArray(theday, datesArray)>=0?"specialDate2":($.inArray(theday, datesArray1)>=0?"specialDate1":''))];
},
onSelect: function(date){
console.log("clicked"+date);
return [true,$.inArray(date, togo) >=0?"specialDate":($.inArray(date, datesArray1)>=0?"specialDate1":'')] ;
}
});
//$.inArray(theday, datesArray) >=0?"specialDate":'specialDate1'
});
For a clearer picture of what I am doing and what I want heres a JSFiddle
http://jsfiddle.net/pratik24/Kyt2w/3/
thanks.
onSelect does not behave like beforeShowDay. You cannot return an array with [true/false, class, popup]. Instead, you will have to apply the class manually in the function.
I'm not sure exactly what you are trying to do, but I would rearrange your code a bit. I made a array with the gray dates, then a variable with the green date. I never change the array, but update the green date on click, and then call a refresh on the datepicker:
$(function () {
var togo = [ '10/25/2013' ];
var redDates = [ '10/27/2013', '10/28/2013' ];
var grayDates = [ '10/24/2013', '10/25/2013', '10/26/2013' ];
var greenDate = '10/24/2013';
$("#datepicker").datepicker({
numberOfMonths: 2,
selectMultiple: true,
beforeShowDay: function (date) {
var theday = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();
return [true, greenDate == theday ? "specialDate" : ($.inArray(theday, redDates) >= 0 ? "specialDate2" : ($.inArray(theday, grayDates) >= 0 ? "specialDate1" : ""))];
},
onSelect: function (dateStr) {
var date = new Date(dateStr);
var theday = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();
if ($.inArray(theday, grayDates) >= 0) {
greenDate = theday;
}
$('#datepicker').datepicker("refresh");
}
});
});
I wasn't sure what togo was for, but this should get you started.
Demo: http://jsfiddle.net/xU47h/3/

JavaScript Clock won't display correctly

I've been teaching myself JavaScript and i'm still fairly new, i've tried to make a clock feature to add to my site, however, I can't see to get it to display, this is my full code:
<html>
<head>
<script type="text/javascript">
function tick() {
var hours, minutes, seconds, ap;
var intHours, intMinutes, intSeconds;
var today;
today = new Date();
intHours = today.getHours();
intMinutes = today.getMinutes();
intSeconds = today.getSeconds();
if (intHours == 0) {
hours = "12:";
ap = "Midnight";
} else if (intHours < 12) {
hours = intHours + ":";
ap = "a.m";
} else if (intHours == 12) {
hours = "12:";
ap = "noon";
} else {
intHours = intHours - 12
hours = intHours + ":";
ap = "p.m.";
}
if (intMinutes < 10) {
minutes = "0" + intMinutes + ":";
} else {
minutes = intMinutes + ":";
}
if (intSeconds < 10) {
seconds = "0" + intSeconds + " ";
} else {
seconds = intSeconds + " ";
}
timeString = hours + minutes + seconds + ap;
Clock.innerHTML = timeString;
window.setTimeout("tick();", 100);
}
//--></script>
</head>
<body>
<div id="Clock" align="center" style="font-family: Verdana; font-size: 10px; color:#000000"></div>
</body>
</html>
As I said, I run it and as far as I can see, it should run fine, as I said i'm a bit new, so maybe someone could help me out.
Thanks again people.
EDIT: Before anyone says, I am fully aware that there are premade working examples of this kind of thing, such as jQuery clocks etc, but I wanted to make one myself from scratch.
It is not starting, mainly because you need to call the function at least once initially:
tick();
Where ever you are learning HTML and JavaScript from, stop learning from there immediately; the code habits and methods you are learning are very, very poor and outdated.
Problems include:
not having a DOCTYPE: <!DOCTYPE html>
accessing div#Clock as a global variable Clock, which is deprecated, and should be document.getElementById('Clock');
using a string to setTimeout, when it should really be setTimeout(tick, 100);
using the deprecated align attribute, when you should use text-align: center; in CSS
using the 'old-browser' JavaScript comment-out trick
using inline CSS via the style attribute, which constitutes poor separation of presentation and content
First, you need to run your function tick() somewhere. It doesn't do anything if you only define it. In the body onLoad event for example.
Second, your element should be properly set in a var. You should get the element by id:
var Clock = document.getElementById('Clock');
Just change your last two lines from
window.setTimeout("tick();", 100);
}
to
}
window.setInterval(tick, 1000);
Demo: http://jsfiddle.net/naveen/3PQ8B/1/
Update: missed the document.getElementById part :)
<html>
<head>
<script type="text/javascript">
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
t=setTimeout('startTime()',500);
}
function checkTime(i)
{
if (i<10)
{
i="0" + i;
}
return i;
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>

Categories