-1

How can I attach a function without any event to the small tag element? Basically I want the function to invoke just after the document is ready.

Pug:

each value, index in user.submissions
    small(data-end=value.endTime) Status

Javascript:

function() {
    const element = $(this);
    const endTime = element.data('end');
    const currentTime = new Date();
    if (Number(endTime) > Number(currentTime)) {
        element.html('Running');
    }
    else {
        element.html('Closed');
    } 
};

I have tried the following code. But that causes all the small tags having the same text. Whether I want the tag to have different text depending on its data attribute value.

$(document).ready(function(){
    function() {
    const element = $('.small');
    const endTime = element.data('end');
    const currentTime = new Date();
    if (Number(endTime) > Number(currentTime)) {
        element.html('Running');
    }
    else {
        element.html('Closed');
    }
};
  • 4
    What you posted as HTML is not HTML... – litelite Aug 07 '17 at 20:01
  • You don't need a function attached to an element to fire something on document.ready, that's what document.ready does ? – adeneo Aug 07 '17 at 20:02
  • "_I want the function to invoke just after the document is ready_" Well, add it in the [ready event](https://learn.jquery.com/using-jquery-core/document-ready/) of the document? – litelite Aug 07 '17 at 20:02
  • `just after the document is ready` - that should be a big clue to use `$(document).ready({code goes here});` – James Aug 07 '17 at 20:02

1 Answers1

2

If you want to run a function when the document is ready, attach the event to the DOMContentLoaded event on the document object:

document.addEventListener("DOMContentLoaded", function(event) {
    …
});

Or, if you're using jQuery:

$(function() {
    …
});
  • But that causes all the small tag having the same text. Whether I want the tag to have different text depending on its data attribute value. – nabila_ahmed Aug 07 '17 at 20:17