Did you use $(document).ready
or better Drupal.behaviors
?
This is from drupal docs:
When using jQuery it is standard for a large majority of situations to
wrap almost all code inside the $(document).ready() function, like
this:
$(document).ready(function () {
// Do some fancy stuff.
});
This ensures that our code will only run after the DOM has loaded and
all elements are available. However with Drupal there is an alternate
better method; using the functionality of Drupal.behaviors and once().
If used properly this will ensure that your code runs both on normal
page loads and when data is loaded by AJAX. The Drupal.behaviors
object is itself a property of the Drupal object, and when we want our
module/theme to add new jQuery behaviors, the best method is to simply
extend this object.
A really basic example:
Drupal.behaviors.myBehavior = {
attach: function (context, settings) {
// Using once() to apply the myCustomBehaviour effect when you want to do just run one function.
$(context).find('input.myCustomBehavior').once('myCustomBehavior').addClass('processed');
// ... left out the more complex examples
}
};
Quote from JavaScript API in Drupal 8