JavaScript - setPointerCapture() method

revision:


Category : element

The setPointerCapture() method of the Element interface is used to designate a specific element as the capture target of future pointer events. Subsequent events for the pointer will be targeted at the capture element until capture is released (via Element.releasePointerCapture() or the pointerup event is fired).

Syntax :

        element.setPointerCapture(pointerId)
    

Parameters:

pointerId : the pointerId of a PointerEvent object.

Examples:

           
        

Practical examples

example: slider example
SLIDE ME
code:
                    <div>
                        <div class="set-1"id="slider">SLIDE ME</div>
                    </div>
                    <style>
                        div .set-1{width: 10vw; height: 3vw; display: flex; align-items: center; justify-content: center; background: #fbe;}
                    </style>
                    <script>
                        function beginSliding(e) {
                            slider.onpointermove = slide;
                            slider.setPointerCapture(e.pointerId);
                        }
                        function stopSliding(e) {
                            slider.onpointermove = null;
                            slider.releasePointerCapture(e.pointerId);
                        }
                        function slide(e) {
                            slider.style.transform = `translate(${e.clientX - 70}px)`;
                        }
                        const slider = document.getElementById("slider");
                        slider.onpointerdown = beginSliding;
                        slider.onpointerup = stopSliding;
                    </script>
                

example: the element.setPointerCapture() method allows events for a particular pointer event to be re-targeted.

code:
                    <div>
                        <button onpointerdown="pointDown(event)" onpointerup="pointerUp(event);">Press Me</button>
                        <p id="point"></p>
                    </div>
                    <script>
                        var x = document.getElementById("point");
                        var elem = document.getElementsByTagName("button")[0];
            
                        function pointDown(e){
                            elem.setPointerCapture(e.pointerId);
                            check(e);
                        }
                        function pointerUp(e){
                            elem.releasePointerCapture(e.pointerId);
                            check(e);
                        }
                        function check(e){ 
                            if(elem.hasPointerCapture(e.pointerId))
                            x.innerHTML = "Your mouse pointer is captured";
                        else
                            x.innerHTML = "Your mouse pointer is released";
                        }
                    </script>