JavaScript mobile drag element


Code implementation:

        body {
            background-color: #1cee89;
        div {
            position: absolute;
            left: 0;
            width: 100px;
            height: 100px;
            background-color: #8294ff;
            border-radius: 20px;

        var div = document.querySelector('div');
        Var startx = 0; // get the initial coordinates of fingers
        var startY = 0;
        Var x = 0; // get the original position of the box
        var y = 0;
        //Finger touch
        div.addEventListener('touchstart', function(e) {
            //Get initial finger coordinates
            startX = e.targetTouches[0].pageX;
            startY = e.targetTouches[0].pageY;
            x = this.offsetLeft;
            y = this.offsetTop;
   = '0 0 15px rgba(0, 0, 0, .6)';
        //Fingers away
        div.addEventListener('touchend', function(e) {
   = '';

        //Press and hold the finger to move
        div.addEventListener('touchmove', function(e) {
            //Calculate the movement distance of the finger: subtract the initial coordinate of the finger from the coordinate after the finger moves
            var moveX = e.targetTouches[0].pageX - startX;
            var moveY = e.targetTouches[0].pageY - startY;
            //Move the box the original position of the box + the distance the finger moves
   = x + moveX + 'px';
   = y + moveY + 'px';
            e. Preventdefault(); // the default behavior of preventing screen scrolling

Recommended Today

Explain module, import and export in JavaScript

Author: Tania rascia Crazy technology house Original text:… In the era of the Internet, websites are mainly developed with HTML and CSS. If you load JavaScript into a page, it usually provides effects and interactions in the form of small fragments. Generally, all JavaScript code is written in a file and loaded into a filescriptTag. […]