skip to Main Content

https://www.flashfeed.io/app/showcase

I’m trying to make a click of the "video" or "photo" applied filter tag also click the element which has "view all". Similar how the reset button current works.

enter image description here

// reset contenttype on video or photo genre
const appliedFilterTag = document.querySelectorAll('[fs-cmsfilter-element="tag-remove"]');

appliedFilterTag.forEach(element => {
  const innerText = element.innerText.toLowerCase();

  if (innerText === "video" || innerText === "photo") {
    element.addEventListener('click', () => {
      const allFilterElement = document.querySelector('#all-filter');
      allFilterElement.click();
    });
  }
});

This code works, but only when the applied filter element is currently existing in the DOM. I tried to just make an onclick function of the an element with the tag [fs-cmsfilter-element="tag-remove"] so that it logically would only run whenever the tag exists, but it just isnt working. Cant figure it out

2

Answers


  1. Use event delegation. Here’s a minimal reproducable example

    document.addEventListener(`click`, handle);
    
    document.body.insertAdjacentHTML(
      `beforeend`, 
      `<button id="click1">button 1</button>
       <br><button id="click2">button 2</button>`);
    
    function handle(evt) {
      if (evt.target.id === `click1`) {
        console.clear();
        return console.log(`You clicked button 1`);
      }
      
      if (evt.target.id === `click2`) {
        console.clear();
        return console.log(`You clicked button 2`);
      }
      
      // Not existing (yet), but no problem now
      if (evt.target.id === `click3`) {
        console.clear();
        return console.log(`You clicked button 3`);
      }
    }
    button {margin-bottom: 0.2rem;}
    Login or Signup to reply.
  2. function resetContentTypeFilter() {
        const innerText = this.innerText.toLowerCase();
    
        if (innerText === "video" || innerText === "photo") {
            const allFilterElement = document.querySelector('#all-filter');
            allFilterElement.click();
        }
    }
    
    const appliedFilterTag = document.querySelector('[fs-cmsfilter-element="tag-remove"]');
    if (appliedFilterTag) {
        appliedFilterTag.addEventListener('click', resetContentTypeFilter);
    }
    

    The ‘appliedFilterTag’ is selected using querySelector() instead of querySelectorAll() which will returns a single element.

    The if condition checks whether ‘appliedFilterTag’ element exists in DOM, and if it does the event listener is added.

    Now, only when the ‘appliedFilterTag’ is clicked ‘resetContentTypeFilter’ is executed.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search