Is it possible to find the element which was listening for the event which triggered the current function?
In the code below, event.target
is returning the lowest child node of #xScrollPane
and event.currentTarget
and event.fromElement
are both null. Is there some other way to retrieve a DOM reference to #xScrollPane
without hard coding it?
//convert vertical scroll wheel to horizontal scroll wheel:
function scrollWheelX(event) {
if (event.deltaY == 0) return
event.target.scroll(event.target.scrollLeft + event.deltaY * 5, event.target.scrollTop)
event.preventDefault()
}
document.getElementById('xScrollPane').addEventListener('wheel', scrollWheelX)
Edit: Inside the event handler, the this
object refers to the element the event handler was added to.
In cases where this
doesn't refer to the desired element or object, you can bind the element into the this
object. Note that if you need to use removeEventListener
, you have to pass the bound function to it instead of just the original function.
Example of binding even though in this case it wasn't necessary:
function scrollWheelX(event) {
if(event.deltaY == 0) {
return;
}
this.scroll(this.scrollLeft + event.deltaY * 5, this.scrollTop);
event.preventDefault();
}
const scrollingElement = document.getElementById("scrollElement");
scrollingElement.addEventListener("wheel", scrollWheelX.bind(scrollingElement));
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加