Preventing page referesh on a click

<div><a href="" class="searchicon"><img src="svg/search-svgrepo-com.svg" alt=""></a></div>

JS code is:

(function (evt) {
  const searchModal = evt.querySelector(".searchicon");
  searchModal.addEventListener("click", modalClick);
  evt.preventDefault();
  function modalClick() {        
      const heyModal  = document.querySelector("body");  
            heyModal.classList.toggle('active');
  }
})(document);

But the page is still refreshing with the click of .searchicon. Certainly, I am faltering somewhere?

I also tried putting this: evt.preventDefault(); inside the function modalClick, but it didn’t worked.

I tried this and did worked:

(function (evt) {
  const searchModal = evt.querySelector(".searchicon");
  searchModal.addEventListener("click", modalClick);
  
  function modalClick(e) {        
    const heyModal  = document.querySelector("body");  
          heyModal.classList.toggle('active');
          e.preventDefault();
  }
})(document);

I am not yet sure the code is of good standards. I will wait for the experts guidance.

1 Like

You have attached the click event listener to an a element.
Maybe you need to add

evt.stopPropagation();
evt.stopImmediatePropagation();

I am still hoping for guidance in case the function evt parameter can be used for preventing default, instead of the modalClick e

The above is an anchor, the normal click behaviour is to change location to the url, which in this case is a svg image, not a location.
but by attaching a click event handler, the event handler runs before the default action.
In the event handler you can prevent the default click action by using:

preventDefault();

As the event handler is attached to the a tag it is not going to propagate but adding

e.stopPropagation();

does no harm but adding it is a good habit to get into.
The:

e.stopImmediatePropagation();

Stops any subsequent event handlers attached to the a element from running.
Not always needed but can be very useful in certain circumstances.
So the only way to prevent the default behaviour is to attack an event handler to the element.
But why not use a button instead of an a tag?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.