mike98
mike98

Reputation: 61

Javascript mousemove event

I have this snippet. I have the div bar on which I act with a listener for the mousemove event. Depending on the coordinates of the mouse, the hello elements move on the x-axis.

How can I, when the mouse is no longer on the bar, that is, outside, the hello elements in the bar, return to the initial position? For example, while the mouse is over the bar, the hello elements move to the right, and when the mouse is no longer on the bar, they return to their original position.

const bar = document.querySelector('.bar');
const layer = document.querySelectorAll('.layer');

const eff = function(mouse) {
  layer.forEach(layer => {
    const x = (window.innerWidth - mouse.pageX) / 10;
    const y = (window.innerHeight - mouse.pageY) / 10;
    layer.style.transform = `translateX(${x}px)translateY(${y}px)`;
  })
};

bar.addEventListener('mousemove', eff);
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.bar {
  height: 20vh;
  background: black;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-around;
}

#red {
  color: red;
}

#blue {
  color: blue;
}
<div class="bar">
  <div class="hello">
    <h2 id='red' class='layer'>Hello</h2>
    <h2 id='blue' class='layer'>Hello</h2>
  </div>
</div>

Upvotes: 2

Views: 1351

Answers (1)

DBS
DBS

Reputation: 9994

You can add another listener for the mouseleave event and then simply reset the translation to 0px for each layer.

const bar = document.querySelector('.bar');
const layer = document.querySelectorAll('.layer');

const eff = function(mouse) {
  layer.forEach(layer => {
    const x = (window.innerWidth - mouse.pageX) / 10;
    const y = (window.innerHeight - mouse.pageY) / 10;
    layer.style.transform = `translateX(${x}px)translateY(${y}px)`;
  })
};

const reset = function(mouse) {
  layer.forEach(layer => {
    layer.style.transform = `translateX(0px)translateY(0px)`;
  })
};

bar.addEventListener('mousemove', eff);
bar.addEventListener('mouseleave', reset);
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.bar {
  height: 20vh;
  background: black;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-around;
}

#red {
  color: red;
}

#blue {
  color: blue;
}
<div class="bar">
  <div class="hello">
    <h2 id='red' class='layer'>Hello</h2>
    <h2 id='blue' class='layer'>Hello</h2>
  </div>
</div>

Upvotes: 3

Related Questions