Samuel Morris
Samuel Morris

Reputation: 19

function does not make it past else if

Why is my pastPres function not working? It is supposed to change the color for a time block in a calendar depending on whether that block is in the past present or future.

$(document).ready(function () {

    $(".saveBtn").on("click", function () {
        var description = $(this).siblings(".description").val();
        var time = $(this).parent().attr("id")
        localStorage.setItem(time, description)
    })

    function pastPres() {
        var blockTime = moment().hour()
        $(".time-block").each(function () {
            var time = $(this).attr("id")
            if (time < blockTime) {
                $(this).addClass("past")
            } else if(time > blockTime) {
                $(this).removeClass("past")
                $(this).addClass("future")
            } else {
               $(this).removeClass("future")
               $(this).addClass("present")
            }
        })
    }
 
    pastPres()

    var interval = setInterval(pastPres, 15000)

    $("#9am .description").val(localStorage.getItem("9am"))
    $("#10am .description").val(localStorage.getItem("10am"))
    $("#11am .description").val(localStorage.getItem("11am"))
    $("#12pm .description").val(localStorage.getItem("12pm"))
    $("#1pm .description").val(localStorage.getItem("1pm"))
    $("#2pm .description").val(localStorage.getItem("2pm"))
    $("#3pm .description").val(localStorage.getItem("3pm"))
    $("#4pm .description").val(localStorage.getItem("4pm"))
    $("#5pm .description").val(localStorage.getItem("5pm"))
    $("#currentDay").text(moment().format("MMMM DD, YYYY"))

})

Upvotes: 0

Views: 71

Answers (2)

Dmitriy Godlevski
Dmitriy Godlevski

Reputation: 620

You are comparing strings. You need to compare time values instead. Since you are using moment you can invoke a new moment instance for the time and let it handle parsing to military time:

function pastPres() {
    var blockTime = moment().hour();
    $(".time-block").each(function () {
        var time = moment($(this).attr("id"), ["hA"]).hour()
        if (time < blockTime) {
            $(this).addClass("past")
        } else if(time > blockTime) {
            $(this).removeClass("past")
            $(this).addClass("future")
        } else {
           $(this).removeClass("future")
           $(this).addClass("present")
        }
    })
}

Upvotes: 2

Phil
Phil

Reputation: 164809

Assuming your .time-block elements are the same as #9am, #10am, etc, it appears you're trying to compare a string to a number like

'9am' < 10

which as far as JavaScript is concerned, is false.

I suggest you add some better data to your elements like

<div id="9pm" data-hour="21" class="time-block">

and use

const time = $(this).data('hour')

Upvotes: 1

Related Questions