Search code examples
javascriptjqueryhtmlcssjquery-effects

Create a wiggle effect for a text


So what I want to happen is that when viewing the Span the text is normal but as you scroll down it starts moving until it looks like such:

Before the effect:
Before the effect

While the effect occurs:
While the effect occurs

The header is represented by spans for each letter. In the initial state, the top pixel value for each is 0. But the idea as mentioned is that that changes alongside the scroll value.

I wanted to keep track of the scroll position through JS and jQuery and then change the pixel value as needed. But that's what I have been having trouble with. Also making it smooth has been another issue.


Solution

  • Something like this will be the core of your JS functionality:

    window.addEventListener('scroll', function(e) {
      var scrl = window.scrollY
    
      // Changing the position of elements that we want to go up
      document.querySelectorAll('.up').forEach(function(el){
        el.style.top = - scrl/30 +'px';
      });
    
      // Changing the position of elements that we want to go down
      document.querySelectorAll('.down').forEach(function(el){
        el.style.top = scrl/30 +'px';
      });
    });
    

    We're basically listening in on the scroll event, checking how much has the user scrolled and then act upon it by offsetting our spans (which i've classed as up & down)

    JSBin Example

    Something you can improve on yourself would be making sure that the letters wont go off the page when the user scrolls a lot.
    You can do this with simple math calculation, taking in consideration the window's total height and using the current scrollY as a multiplier.

    - As RokoC has pointed out there is room for performance improvements.
    Implement some debouncing or other kinds of limiters