I have some simple dom manipulation I want to make using javascript without jquery. I can't seem to figure out how to prevent this code from firing twice.
Almost all examples I find use jQuery, but I do not want to add jQuery just for this. I'm trying to use es6 with babel here.
((() => {
Drupal.behaviors.node_page_filters_sales = {
attach: (context, settings) => {
const usaButton = document.querySelector('[data-sales-switcher="83"]');
usaButton.style.border = '6px solid orange';
}
};
})());
This code works, but it is run twice. Once when there selector queried does not exist, giving me a typeError, and one when it does, executing the code as expected.
It seems like it's related to BigPipe. If i turn that off, things seem to work as normal, firing once. But I obviously want BigPipe turned on. I'm clearly missing something that needs to be done when dealing with it.
For a little more detail, this is in a custom module. The custom module creates a block plugin. The javascript (snippet above) is part of the custom module's library that's attached to the block template.
UPDATED CODE EXAMPLE
The inline style was just for testing purposes. I'm attempting to check multiple buttons and add/remove classes based on a variable. See below.
// Determine default region.
let defaultLocation = '83';
if (defaultLocation === '83') {
document.querySelector('.tid-83').classList.add('active');
}
I also notice that the javascript works as expected and is only executed once if I'm not logged in. When logged in, it fires twice.