Galanthus
Galanthus

Reputation: 2290

How to stop click event on resize & load if screen width is greater than?

I am facing this problem over and over again and just don't know how to solve this. I have a click event that I would like to fire only if the screen width is less than **576px* and if a page is loaded to make this event fire.

But when I resize the browser larger than 576px the click event still works.

Can someone please help me out how can I solve this common issue that I am facing?

Thanks in advance.

My code:

const onSearchMobile = () => {
    let screenWidth = window.innerWidth;
    let searchIcon = document.querySelector('.main-header__search--icon');
    if (screenWidth <= 576) {
        console.log('Yes lower then 576');
        searchIcon.addEventListener('click', () => {
            console.log('clicked!');
        });
    }
};

window.addEventListener('resize', onSearchMobile, false);
window.addEventListener('load', onSearchMobile);

Upvotes: 0

Views: 263

Answers (2)

User863
User863

Reputation: 20039

Just check the width inside event

const onSearchMobile = () => {
  let screenWidth = window.innerWidth;
  let searchIcon = document.querySelector('.main-header__search--icon');
  searchIcon.addEventListener('click', () => {
    if (screenWidth <= 576) {
      console.log('clicked!');
    }
  });
};

window.addEventListener('resize', onSearchMobile, false);
window.addEventListener('load', onSearchMobile);

Using MediaQueryList.onchange

let searchIcon = document.querySelector('.main-header__search--icon')
let clickListener = () => console.log('clicked!')
let mql = window.matchMedia('(max-width: 576px)')

mql.addEventListener("change", (e) => {
  if (e.matches) {
    searchIcon.addEventListener('click', clickListener)
  } else {
    searchIcon.removeEventListener('click', clickListener)
  }
})

Upvotes: 2

S. Nadezhnyy
S. Nadezhnyy

Reputation: 582

You can remove eventListener:

    const onSearchMobile = () => {
    let screenWidth = window.innerWidth;
    let searchIcon = document.querySelector('.main-header__search--icon');
    if (screenWidth <= 576) {
        console.log('Yes lower then 576');
        searchIcon.addEventListener('click', () => {
            console.log('clicked!');
        });
    }
    else {
        searchIcon.removeEventListener('click');
    }
};

window.addEventListener('resize', onSearchMobile, false);
window.addEventListener('load', onSearchMobile);

Upvotes: 1

Related Questions