본문 바로가기
푸닥거리

자바스크립트에서 버튼을 브라우저 밖으로 드래그 앤 드롭 동작이 보이면서 새창 띄우는 스크립트

by [김경민]™ ┌(  ̄∇ ̄)┘™ 2023. 8. 19.
728x90

자바스크립트에서 버튼을 브라우저 밖으로 드래그 앤 드롭 동작이 보이면서 새창 띄우는 스크립트

 

728x90

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Drag and Drop outside browser</title>
    <style>
        #draggable {
            width: 100px;
            height: 50px;
            background-color: lightblue;
            cursor: pointer;
            position: relative;
        }
    </style>
</head>
<body>

<button id="draggable">Drag me!</button>

<script>
    let draggable = document.getElementById('draggable');
    let isDragging = false;
    let offsetX, offsetY;

    draggable.addEventListener('mousedown', (e) => {
        isDragging = true;
        offsetX = e.clientX - draggable.getBoundingClientRect().left;
        offsetY = e.clientY - draggable.getBoundingClientRect().top;

        window.addEventListener('mousemove', onMouseMove);
        window.addEventListener('mouseup', onMouseUp);
    });

    function onMouseMove(e) {
        draggable.style.left = (e.clientX - offsetX) + 'px';
        draggable.style.top = (e.clientY - offsetY) + 'px';

        // Check if the element is outside the viewport
        if (e.clientY < 0 || e.clientY > window.innerHeight || e.clientX < 0 || e.clientX > window.innerWidth) {
            openNewWindow();
            onMouseUp();  // Clean up
        }
    }

    function onMouseUp() {
        isDragging = false;
        window.removeEventListener('mousemove', onMouseMove);
        window.removeEventListener('mouseup', onMouseUp);
    }

    function openNewWindow() {
        window.open('https://www.example.com', '_blank');
    }
</script>

</body>
</html>
728x90

댓글