Search code examples
javascripthtmlmousewheel

Detect the target parent element when perform mouse "onwheel Event"


What this code should do is:

I have a list of element IDs, each of these target elements contains other elements. When I use the mouse wheel and the cursor is on one of the target elements (or some of its child element) some action must be performed.

I wrote this code and it works fine. What worries me is that each time the code has to perform many calculations to complete the task. If anyone has an idea how I can optimize this task I will be happy to share. Тhanks in advance.

Please, Run code snippet on Full page

var flag = true;
var myTarget;
var myRes;
var myI;

// The IDs of the target elements
var array = ['elOne', 'elTwo', 'elThree'];
var newArray = array.reverse();

for (var i = 0; i < array.length; i++) {
    var myEl = document.getElementById(array[i]);
    myEl.parentElement.addEventListener("wheel", event => {
        mouseWeel(event.target);
    });
}

function mouseWeel(cmp) {
    if (cmp !== myTarget) {
        for (var i = 0; i < newArray.length; i++) {
            var res = cmp.closest('#' + newArray[i]);
            if (res) { break; }
        }

        myTarget = cmp;
        myRes = res;
        myI = i;
    }

    cmd = myTarget; res = myRes; i = myI;

    if (flag) {
        var myEl = document.getElementById(newArray[i]);
        myEl.appendChild(document.createTextNode(i));
        flag = false;
    } else {
        flag = true;
    }
}
<div id="elOne" style="width:100%; height:90vh; background:orangered;">
    <div id="elTwo" style="width:50%; height:45%; background:orange; margin: auto;">
        <div style="width:80%; height:50%; background:orange; padding: 10px;">
            <h2>Lorem ipsum</h2>
            <span>Lorem ipsum dolor sit amet consectetur.</span>
        </div>
    </div>

    <div id="elThree" style="width:50%; height:45%; background:blue; margin: auto;">
        <div style="width:80%; height:50%; background:blue; padding: 10px;">
            <h2>Lorem ipsum</h2>
            <span>Lorem ipsum dolor sit amet consectetur</span>
            <div
                style="width: 150px; height: 150px; margin-left: -200px; background:blue; padding: 20px; transform: rotate(-45deg); opacity: 0.5; color: white;">
                I am a child of the blue element
            </div>
        </div>
    </div>
</div>


Solution

  • You'll want to look at a throttle or debounce of some sort.

    https://programmingwithmosh.com/javascript/javascript-throttle-and-debounce-patterns/