Home > Software engineering >  How can I change the position element via jQuery plugin on mousemove?
How can I change the position element via jQuery plugin on mousemove?

Time:11-05

I need to change the position element via jQuery plugin on mousemove. I'm getting the mousemove coordinates in the index.js file and trying to pass it as params to jQuery custom plugin. So the indexjs variables are changed on mousemove, but when those are passed as params to plugin file, they are not being changed dynamically. Also having the error TypeError: ((S.event.special[o.origType] || {}).handle || o.handler).apply is not a function

// Plugin jQuery file
(function ($) {
  $.fn.moveAnimate = function (posX,posY) {
    console.log('inner posX', posX)    // the posX is instantly === 1, not being changed reactively
    return $(this).each(function () {
      var $moveElement = $('.move');
      $moveElement.animate(
        {
          position: "absolute",
          left: `${posX}   "150px"`,
          top: `${posY}   "150px"`
        },
        1000
      );
    });
  };
})(jQuery);


// index.js file
$(function() {
  let globalX = 1
  let globalY = 1

    $("body").on("mousemove", (e) => {
      console.log('inner', globalX)  // changes the globalX
      globalX = e.pageX;
      globalY = e.pageY;
    })

    $("body").on("mousemove", $(".move").moveAnimate(globalX, globalY))
    
});

CodePudding user response:

There's a few issues in your code.

  • left: `${posX} "150px"`, is not a valid mathematical operation. You need to add the integer values, then append px to the end: left: (posX 150) 'px'
  • You only need one body.mousemove event handler.
  • You need to invoke $.fn.moveAnimate() within the event handler, not executing it separately and providing its return value as the event handler.
  • You don't need an each() loop in the moveAnimate() function, as you can apply animate() on a collection.
  • Use the mouseenter event, not mousemove, as the latter will execute for every pixel the mouse moves, which is not what is required in this use case
  • The .move element needs to be set as position: absolute before the animation runs in order for it to work. This can be done in CSS.

With those changes made, the code works fine:

// Plugin jQuery file
(function($) {
  $.fn.moveAnimate = function(posX, posY) {
    return $(this).animate({
      left: (posX   150)   'px',
      top: (posY   150)   'px'
    }, 1000);
  };
})(jQuery);


// index.js file
$(function() {
  $("body").on("mouseenter", e => {
    globalX = e.pageX;
    globalY = e.pageY;
    $(".move").moveAnimate(globalX, globalY);
  });
});
.move {
  position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div id="app">
  <h1 >hello</h1>
  <h1 >move</h1>
</div>

  • Related