0

I am trying to get mouse position percent in screen. when I get mouse coordinates I want to send ajax request to backend X,Y.

I already have mouse position function but when I am write ajax function inside mousemove event listener it sends too many request to backend . I need send request every X second after mouse move. I tried setInterval function but it not works. when user moving cursor and stop it then after 5 second should send ajax request my code looks like.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{{ csrf_token() }}" />


    <title>Document</title>
<style>
    body {
    margin: 0;
    overflow: hidden;
    width: 100vw;
    height: 100vh;
    background: skyblue;
    font-weight: bold;
    font-family: arial;
    }
</style>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256- 
9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
  crossorigin="anonymous"></script>
<script>

$.ajaxSetup({

        headers: {

            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')

        }

    });
    // Container and displays
    const container = document.querySelector("body");
    let posXDisplay = document.getElementById("posX");
    let posYDisplay = document.getElementById("posY");

    // On mousemove

    container.addEventListener("mousemove", (e)=> {
        // Do math
        xPercent = parseInt(e.pageX / window.innerWidth * 100);
        yPercent = parseInt(e.pageY / window.innerHeight * 100);


        setInterval(function(){
             $.ajax({

                 type:'POST',

                 url:'/getImage',

                 data:{xPercent:xPercent, yPercent:yPercent},

                 success:function(data){

                     let src = data;
                     $('body').css('backgroundImage','url('+src+')');

                 }

             });
            console.log(xPercent ,yPercent )
           }, 5000);

    });

</script>
</body>
</html>
John Doe
  • 85
  • 1
  • 8

0 Answers0