Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find the left of an element in JS

I am just trying to make a game using JS. The problem is if one image collides with the other image, I want to stop an animation. I tried to stop if both images have the same left but still not working. Here’s my code

        function mrmove() {
            var enem = document.getElementById("2");
            var elem = document.getElementById("1");
            var width = 1;
            var id = setInterval(frame, 100);
            
            function frame() {
            if (width == elem.style.left) {
                clearInterval(id);
            } else {
                width++;
                elem.style.left = width + '%';
                console.log(elem.style.left);
            }
        }
        }
        function msmove() {
            var enem = document.getElementById("2");
            var elem = document.getElementById("1");
            var width = 1;
            var id = setInterval(frame, 100);
            
            function frame() {
            if (width == elem.style.left) {
                clearInterval(id);
            } else {
                width++;
                enem.style.left = 70 - width + '%' ;
                console.log(elem.style.left);
            }
        }
        }

In this an image moves forward while the other moves backward.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You may be looking for getBoundingClientRect

elem.getBoundingClientRect().left

Doc:https://developer.mozilla.org/fr/docs/Web/API/Element/getBoundingClientRect

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading