JavaScript: Toggle 'fadeEffect' Class Based on Active State

Using JavaScript, how can I toggle ‘fadeEffect’ on an image within an element with id ‘item1’ when it gains or loses ‘active’? Code samples follow:

<div id="item1" class="container">
  <img id="imgMain" src="sample.png" alt="sample image">
</div>
document.addEventListener('DOMContentLoaded', function(){
  const sectionElem = document.getElementById('item1');
  const imgElem = document.getElementById('imgMain');
  if(sectionElem.classList.contains('active')){
    imgElem.classList.add('fadeEffect');
  } else {
    imgElem.classList.remove('fadeEffect');
  }
});

I implemented a similar solution in a project that involved dynamic UI changes. I found it beneficial to abstract the state-checking logic into a self-contained function so that any time the active state changed, the fadeEffect toggled accordingly. This approach removed the need to rely solely on the DOMContentLoaded event and allowed the state to be managed more seamlessly during user interactions. This method proved especially effective when multiple components required similar behavior, making the device response consistent and the code easier to manage over time.

I have been in similar situations where controlling visual effects based on state was crucial for user interaction. In my experience, simplifying the logic by creating a dedicated function for toggling the class has helped a lot. I went through a phase where I attached event listeners for various triggers, not just on DOMContentLoaded. This approach allowed me to control changes more dynamically, reducing device-specific issues. In one case, separating the effects management from other DOM manipulations improved the maintainability, making it easier to add new interactive elements later on.