Skip to content

Instantly share code, notes, and snippets.

@startinggravity
Last active March 11, 2020 14:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save startinggravity/275ef1e296b6aadbe390ef185626e692 to your computer and use it in GitHub Desktop.
Save startinggravity/275ef1e296b6aadbe390ef185626e692 to your computer and use it in GitHub Desktop.
jQuery for Drupal
<!-- Fake data. -->
<div class="view-content">
<div class="unit">
<div class="unit-shortname">
SQN-01
</div>
<div class="unit-onoff">
On
</div>
<div class="unit-days">
<span class="unit-days__days unit-days__days--on">
2020-01-04
</span>
<span class="unit-days__label">
Operating Days
</span>
</div>
<div class="unit-percentage">
33%
<span class="unit-percentage__label">
Percentage Online
</span>
</div>
<div class="unit-rating">
Qualified
<span class="unit-rating__label">
Grid Rating
</span>
</div>
<div class="unit-risk">
<span class="unit-risk__green">
Green
</span>
<span class="unit-risk__label">
ORAM/EOOS Risk
</span>
</div>
</div>
<div class="unit">
<div class="unit-shortname">
SQN-02
</div>
<div class="unit-onoff">
On
</div>
<div class="unit-days">
<span class="unit-days__days unit-days__days--on">
2020-02-02
</span>
<span class="unit-days__label">
Operating Days
</span>
</div>
<div class="unit-percentage">
77%
<span class="unit-percentage__label">
Percentage Online
</span>
</div>
<div class="unit-rating">
Qualified
<span class="unit-rating__label">
Grid Rating
</span>
</div>
<div class="unit-risk">
<span class="unit-risk__green">
Green
</span>
<span class="unit-risk__label">
ORAM/EOOS Risk
</span>
</div>
</div>
</div>
/**
* This file chnages the restart date field to an "operating days" number when
* the unit status block is displayed.
**/
(function ($, Drupal) {
'use strict';
Drupal.behaviors.daysSince = {
attach: function (context, settings) {
$('.unit', context).once('daysSince').each(function(i, obj) {
// Get the restart date.
const restartDate = $('.unit-days__days--on', this).text();
// Get and format today's date.
const d = new Date();
const month = d.getMonth() + 1;
const day = d.getDate();
const todayDate = d.getFullYear() + '-' +
(('' + month).length < 2 ? '0' : '') + month + '-' +
(('' + day).length < 2 ? '0' : '') + day;
const today = new Date(todayDate);
const restart = new Date(restartDate);
const differenceDays = (today.getTime() - restart.getTime()) / (1000 * 3600 * 24);
// Change the restart date to "operating days" when the unit is on.
$('.unit-days__days--on', this).text(differenceDays);
// Change the operating days number to "zero" when the unit is off.
$('.unit-days__days--off').text('0');
// Make the "operating days" number visible after the change to avoid a
// flash of the restart date.
$('.unit-days__days').css("visibility", "visible");
});
}
};
})(jQuery, Drupal);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment