Search code examples
jqueryfunctionany

Is there any way for define my own "onSomeFunction" for an element in jquery?


Is there any way for defining my own "onSomeFunction" in jQuery? I have a function to understand that an element is scrolled to view or not. its name is "isScrolledToView()" and returns true or false. Now I want to define something like code below. its just an example. I want to do it for any other functions like this:

$("div.myDiv").on("scrolledToView", function() {
    alert("Scrolled To View")
})

please help me with this.


Solution

  • Not that easy! But yes it's possible. But now, let's look for an easy way: In this case, we can simply use:

    let onScrollIntoView = () => {
        // do some stuff...
    }
    window.addEventListener("scroll", function() {
        const isVisible = true // or false// Chek if that element is in the viewport
        if (isVisible) { onScrollIntoView() }
    })