Home > Mobile >  Jquery Move block on mouse move
Jquery Move block on mouse move

Time:12-05

I need script which would change translateX position depends on mouse position inside of this block. https://www.peaktwo.com/work/ Here's how it looks on a live website, can't achieve this effect. Can somebody help to do that on jQuery?

$('.work__main').on("mousemove" ,function(e){
            let center = $(window).width()/2;
            if ((center - event.pageX) > 0 ) {
                $('.work__main').css("transform" , "translateX(-"  event.pageX/10  "px)")
            } else {
                $('.work__main').css("transform" , "translateX(-"  event.pageX/10  "px)")
            }
    });

Here's my code - but when I'm trying to build it like that - when I put my mouse on a center it jumps from one side to another

CodePudding user response:

To fix the issue where the element jumps from one side to another when the mouse is in the center of the screen, you can add an additional check to make sure that the translateX value doesn't exceed a certain threshold.

Here is an example of how you could do that:

$('.work__main').on("mousemove" ,function(e){
  let center = $(window).width()/2;
  let translateX = -event.pageX / 10; // Calculate the translateX value based on the mouse position

  // Limit the translateX value so that it doesn't exceed a certain threshold
  if (translateX > 50) {
    translateX = 50;
  } else if (translateX < -50) {
    translateX = -50;
  }

  // Apply the translateX value to the element
  $('.work__main').css("transform" , "translateX("   translateX   "px)")
});

This will make sure that the element doesn't jump from one side to the other when the mouse is in the center of the screen. You can adjust the threshold value (50 in this example) to your liking.

  • Related