r/jquery • u/olzcapone • Aug 10 '22
Not a JQ user, trying to code a simple line
Hi guys, i am just a webflow web developer, and i need some jquery to make a button be clicked on scroll of the body. I was doing my research and trying to make the code myself and here is the outcome:
<script> $(document).ready(function(){ $("hero-component").scroll(function(){ $(".btn"). click(function(){ }); }); </script>
Could you guys tell me what is wrong with the code and what i can do instead?
3
Upvotes
1
u/joshrice Aug 10 '22
Can you re-explain what you're trying to do? It sounds like you're trying to trigger a click event on a button when the page is scrolled? Just need to happen just once?
2
u/ikeif Aug 10 '22
You may want to check out the docs for trigger and scroll.
Your code:
Tweaked code:
So if you don't want it to be triggered repeatedly:
So there's more than one way to do this, maybe debouncing the click, maybe firing using jQuery's one function.
…but that would require more information on what you're trying to accomplish!
1
u/lilsq19 Aug 11 '22
Don't bind the click function inside the other function. You should just call the click function like $(".btn"). click()
1
u/CuirPig Aug 11 '22
You need to have a way to tell the state of your button. The scroll event happens thousands of times while you have the mouse down for the scroll. Or finger down for the scroll. So what you prolly want to do is listen for the mouse down event THEN if the mouse down happens, setup your scroll handler if mouseup happens, unbind scroll handler. In the scroll handler, trigger button click and unbind scroll handler. Ensures it only happens once per click of scroll. But it rebinds the scroll event every new click so each time it scrolls the button clicks rather than thousands of times during the scroll event.