Set multiple EventListener to element but delete single ones

Viewed 36

I have an element, here in the example - $(window). I would like to put several of the same EventListeners on this element, here "scroll" twice. These two EventListeners each perform different functions, which I cannot / do not want to connect with each other, shown here in a simplified manner. How can I delete individual EventListeners?

Here is the little example I made.

// Logs 1 when scrolling
$(window).on("scroll", () => {
    console.log(1);
});

// Logs 2 when scrolling
$(window).bind("scroll", () => {
    console.log(2);
});

// After 2 seconds stop logging 1
setTimeout(() => {
  $(window).unbind("scroll"); // remove only logging 1
}, 2000);
#test {
  height:10000px;
  width:100vw;
  background:blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test"></div>

2 Answers

You can use event.namespace for this and add multiple namespaces for scroll event like:

$(window).on("scroll.event1", () => {
    console.log(1);
});

$(window).on("scroll.event2", () => {
    console.log(2);
});

and when you want to remove event 1, you can simply call .off on it like:

setTimeout(() => {
  $(window).off("scroll.event1"); // remove only logging 1
}, 2000);

Demo:

$(window).on("scroll.event1", () => {
  console.log(1);
});

$(window).on("scroll.event2", () => {
  console.log(2);
});

// After 2 seconds stop logging 1
setTimeout(() => {
  $(window).off("scroll.event1"); // remove only logging 1
}, 2000);
#test {
  height: 10000px;
  width: 100vw;
  background: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test"></div>

You can add a .namespace to your event. This will still fire the same scroll event, but allows you to reference it with .off (or .unbind in your original code).

Here's your code updated:

// Logs 1 when scrolling
$(window).on("scroll.temp", () => {
  console.log(1);
});

// Logs 2 when scrolling
$(window).on("scroll", () => {
  console.log(2);
});

// After 2 seconds stop logging 1
setTimeout(() => {
  $(window).off("scroll.temp"); // remove only logging 1
}, 2000);
#test {
  height: 10000px;
  width: 100vw;
  background: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test"></div>


More info from: https://api.jquery.com/on/

Event names and namespaces

Any event names can be used for the events argument. jQuery will pass through the browser's standard JavaScript event types, calling the handler function when the browser generates events due to user actions such as click.

Related