-1

How do I check if a preset date (Sept. 13, 2013) is equal to the current date in JQuery - and then run an script if that's true. Here's the code I have right now, but it doesn't work. Thanks!

<script type="text/javascript"> 
$(document).scroll(function () {
    var y = $(this).scrollTop();
    var x = $("#third").position();
    var date = new Date();
    var today = new Date(2013,09,13);
    $("#dot").hide();
    if (y > (x.top - 50) && date == today) {
     $("#dot").show();
        $("#dot").addClass(
            "animation");
    }
    else {
        $("#dot").removeClass(
            "animation");
    }
});</script>
user2155400
  • 589
  • 5
  • 16
  • 1
    This is not necessarily related to jQuery – Jeffrey Sep 13 '13 at 18:23
  • Animating an object in css if you scroll past a certain div and if the preset date is equal to the current date. – user2155400 Sep 13 '13 at 18:24
  • possible duplicate of [Comparing date part only without comparing time in javascript](http://stackoverflow.com/questions/2698725/comparing-date-part-only-without-comparing-time-in-javascript) – sudhansu63 Sep 13 '13 at 18:38

2 Answers2

2

It's because Date stores both date and time. When You write new Date(2013, 09, 13), the value is equals to the midnigth of that day (so the time is 00:00:00 and when You write new Date(), the value is set current date and time, so it's true that's those two are not equal ;).

To solve this, you can change line:

if (y > (x.top - 50) && date == today) {

into

var tomorrow = new Date(2013, 09, 14);
tomorrow.setHours(0, 0, 0, 0);
if (y > (x.top - 50) && date > today && date < tomorrow) {
...

or just change

var date = new Date();
var today = new Date(2013,09,13);

into

var date = new Date();
date.setHours(0,0,0,0);
var today = new Date(2013,09,13);

to set current time to midnight, as described in this link. That link helped me to find the answer :).

Community
  • 1
  • 1
Lukasz M
  • 5,635
  • 2
  • 22
  • 29
0

your date object contains time value as well, hence it will never match with the preset date. You need to trim off the time part prior to compare.

var date = new Date();
   date.setDate(date.getYear(), date.getMonth(), date.getDay());
var today = new Date(2013,09,13)

then compare

if(date == today )
{
 alert(true);
}
else
{
alert(false);
}
sudhansu63
  • 6,025
  • 4
  • 39
  • 52