Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JQuery to add a link to an element if a condition is met

I am very new to HTML, CSS and JavaScript. I am trying to use jQuery to make a button active or inactive depending on the time of day. I have managed to get the image to change correctly after defining the time now (d), an open time and a close time. However I am having problems assigning a link to the buttons depending on the time of day.

This code correctly applies a class if the time is between open and close. It also correctly applies the link to the ButtonOne div, only when the ManagersChatButtonActive class is applied, in a JSFiddle. However in SharePoint, were this will be, the link is also applied even when the time condition is not met.

How can I get the link to only be applied when the 'if' condition is met?

(This is my first time on Stack Overflow, so apologies if this is not very well laid out or explained).

$(document).ready(function() {
    var d = new Date();
    var open = new Date();
    open.setHours(9);
    open.setMinutes(0);
    open.setSeconds(0);

    var close = new Date();
    close.setHours(18);
    close.setMinutes(0);
    close.setSeconds(0);

    if (d >= open && d < close) {
        $(".ButtonOne").addClass("ManagersChatButtonActive");
        $(".ButtonOne").wrap('<a href="http://www.google.com"/>');
    } else {
        $(".ButtonOne").addClass("ManagersChatButtonInactive");
    }
});
like image 787
Andy Gill Avatar asked Apr 04 '16 15:04

Andy Gill


1 Answers

Make sure you wrap your method in the JQuery syntax for document on ready or on load as follows:

$(function(){
  var d = new Date()

  var open = new Date();
  open.setHours(9);
  open.setMinutes(0);
  open.setSeconds(0);

  var close = new Date();
  close.setHours(18);
  close.setMinutes(0);
  close.setSeconds(0);

  if (d >= open && d < close) {

    $(".ButtonOne").addClass("ManagersChatButtonActive");
    $(".ButtonOne").wrap('<a href="http://www.google.com"/>');
  } else {
    $(".ButtonOne").addClass("ManagersChatButtonInactive");
  }
})

https://jsfiddle.net/aaronfranco/3xwhoh10/1/

It might also make more sense to use getTime() to use a UNIX timestamp, which is a number, instead of a date string.

$(function(){
  var d = new Date().getTime();

  var open = new Date();
  open.setHours(9);
  open.setMinutes(0);
  open.setSeconds(0);
  open = open.getTime()

  var close = new Date();
  close.setHours(18);
  close.setMinutes(0);
  close.setSeconds(0);
  close = close.getTime()

  if (d >= open && d < close) {

    $(".ButtonOne").addClass("ManagersChatButtonActive");
    $(".ButtonOne").wrap('<a href="http://www.google.com"/>');
  } else {
    $(".ButtonOne").addClass("ManagersChatButtonInactive");
  }
})
like image 56
Aaron Franco Avatar answered Oct 21 '22 15:10

Aaron Franco