Let's make a cool mouse event bubble animation in just 50 lines of JavaScript!
Tags: javascript, frontend, tutorial, animation
Published: 2023-05-19 12:43:48

Heyy, how are you guys?!

Today I'd like to share an interesting animated background with bubbles and as we move the mouse the bubbles move too!

And we can do it with just **pure JavaScript** and **only 50 lines of code**! Let's do it?!

Take a look at how our animation will look:

{% embed https://stackblitz.com/edit/web-platform-ffydqn?embed=1&file=script.js&hideExplorer=1&hideNavigation=1&theme=dark&view=preview %}
___
## Implementing the HTML Structure:

First, let's implement the basic **HTML** structure, we will have a **main** div and a **banner** with four bubble **divs** in it, so the code will look like below:

```html
 ...
  <body>
    <main>
      <div class="banner">
        <div class="bubble-one"></div>
        <div class="bubble-two"></div>
        <div class="bubble-three"></div>
        <div class="bubble-four"></div>
      </div>
    </main>
  </body>
```
___
## Implementing the CSS Structure:

Now let's implement the CSS structure! We need to create classes for our 4 bubbles and for our banner class! I implemented the bubbles as I drew them in my **Figma** prototype, but feel free to change them and adapt them to your liking. So the code looked like this:

```css
* {
  box-sizing: border-box;
  margin: 0;
}

.banner {
  background-color: #0476df;
  height: 100vh;
  width: 100%;
  overflow: hidden;
  position: relative;
}

.bubble-one {
  position: absolute;
  width: 300px;
  height: 300px;
  left: 0;
  top: 0;
  background: #0dc5d0;
  filter: blur(83px);
}

.bubble-two {
  position: absolute;
  width: 500px;
  height: 500px;
  right: 0;
  top: 0;
  background: #942cb9;
  filter: blur(139px);
}

.bubble-three {
  position: absolute;
  width: 300px;
  height: 300px;
  left: 0;
  bottom: 0;
  background: #040e63;
  filter: blur(114px);
}

.bubble-four {
  position: absolute;
  width: 150px;
  height: 150px;
  left: 70%;
  top: 70%;
  bottom: 0;
  background: #fdee15;
  filter: blur(104px);
}
```

And the result for now is like below:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/siqqljg0we1korecsgla.png)
___

## Implementing the JavaScript Structure:

Below you can see how our JavaScript animation function will look and if you notice we have **only 50 lines** of JavaScript code, cool right?!

Below it we will also look at the code block by block to understand all the pieces!

```javascript
function getElement(elementSelector) {
  return document.querySelector(elementSelector);
}

function bubbleAnimations(event) {
  const bubbleOne = getElement('.bubble-one');
  const bubbleTwo = getElement('.bubble-two');
  const bubbleThree = getElement('.bubble-three');
  const bubbleFour = getElement('.bubble-four');

  let cursorPositionX = event.clientX;
  let cursorPositionY = event.clientY;

  function animateBubble(positionX, positionXType, positionY, positionYType) {
    return `translate(${positionXType}${Math.round(
      positionX / Math.PI
    )}px, ${positionYType}${Math.round(positionY / Math.PI)}px`;
  }

  bubbleOne.style.transform = animateBubble(
    cursorPositionX,
    '',
    cursorPositionY,
    ''
  );
  bubbleTwo.style.transform = animateBubble(
    cursorPositionY,
    '',
    cursorPositionX,
    ''
  );
  bubbleThree.style.transform = animateBubble(
    cursorPositionY,
    '',
    cursorPositionY,
    '-'
  );
  bubbleFour.style.transform = animateBubble(
    cursorPositionX,
    '-',
    cursorPositionY,
    ''
  );
}

document.addEventListener('mousemove', (event) => {
  bubbleAnimations(event);
});
```

Now, let's understand each part of our JavaScrip code and why it is like this!
___

### Understanding the function: getElement() 

```javascript
function getElement(elementSelector) {
  return document.querySelector(elementSelector);
}
```

In this code we have a simple function to return the HTML Element! With that we can improve our development time because we won't write `document.querySelector(elementSelector)` repeatedly, practicing clean code and isolating our code responsibilities!
___

### Understanding the function: bubbleAnimations()

Now, let's understand the core of our animation, the **bubbleAnimations()** function!

#### Get bubbles elements

```javascript
  const bubbleOne = getElement('.bubble-one');
  const bubbleTwo = getElement('.bubble-two');
  const bubbleThree = getElement('.bubble-three');
  const bubbleFour = getElement('.bubble-four');
```

Here we are just creating four const's and passing the class selector and getting the element with the **getElement()** function we created.
___

#### Get the Cursor Position:

```javascript
let cursorPositionX = event.clientX;
let cursorPositionY = event.clientY;
```

Here we are just creating two variables to get the X and Y cursor position using event argument of **bubbleAnimations()** function.
___

#### Understanding the function: animateBubble()

```javascript
function animateBubble(positionX, positionXType, positionY, positionYType) {
    return `translate(${positionXType}${Math.round(
      positionX / Math.PI
    )}px, ${positionYType}${Math.round(positionY / Math.PI)}px`;
  }
```

In this code block we create a function to return the translate property, because with it we will apply the transition effect to our **bubbles** elements!

This function has four parameters:
```
🧩 positionX: The X position of the element.
🧩 positionXType: The position X type, as we can have negative or positive position.
```
```
🧩 positionY: The Y position of the element.
🧩 positionYType: The Y type of the position, as we can have negative or positive position.
```

In this function we have the **Template String**, **Math.round** and **Math.PI** also to do the calculation!

With that we don't need to repeat the code countless times and with that we make our code easier to understand and easier to do maintenance/improvements because we will only touch in one place 🤩🥳
___
#### Applying the animations in our Bubbles:
```javascript
bubbleOne.style.transform = animateBubble(
    cursorPositionX,
    '',
    cursorPositionY,
    ''
  );
  bubbleTwo.style.transform = animateBubble(
    cursorPositionY,
    '',
    cursorPositionX,
    ''
  );
  bubbleThree.style.transform = animateBubble(
    cursorPositionY,
    '',
    cursorPositionY,
    '-'
  );
  bubbleFour.style.transform = animateBubble(
    cursorPositionX,
    '-',
    cursorPositionY,
    ''
  );
```

In this part of the code, we just applied the animation using **style** and changed the **transform** property by calling the **animateBubble** function and with some random arguments to the function!
___
#### Calling the function:
```javascript
document.addEventListener('mousemove', (event) => {
  bubbleAnimations(event);
});
```
This part of the code is important, here we add an **eventListener** in our **document**! And the **event** we need to listen for is **mousemove**, because we only want to apply the animations to the **mousemove** event! So just add it and call the **bubbleAnimations** function passing the **event** parameter!

Anddd finaalllyyy, we have our awesome and simple animation with only 50 lines of code of JavaScript!

{% embed https://stackblitz.com/edit/web-platform-ffydqn?embed=1&file=script.js&hideExplorer=1&hideNavigation=1&theme=dark&view=preview %}
___

That's all guys! With that animation we can turn our websites more nice turning the user experience nice!

Here is the [StackBlitz](https://stackblitz.com/edit/web-platform-ffydqn?file=script.js) project link, feel free to fork and make your changes, improvements and anything you want 😄.

Hope this makes you feel a bit more comfortable with JavaScript animations and their possibilities!

Feel free to reach out to me if you have any questions!

and obviously I hope you enjoyed it 🤟💪🤟💪