Veljko Stefanovic
Veljko Stefanovic

Reputation: 511

Determine X coordinate of a mouse click

I'm making custom controls for html5 video. My problem is occurring when I click on the seek bar. The x coordinates are far off. As I understand, I need to account for all the margins and padding down to root element, i.e. myElement<parentOfMyElement<parenOfparentOfMyElement ... and so on. Every one of them has its own styling with padding and margins and whatnot. How to achieve that without going through entire dom tree backwards?

zero

I tried:

       if(e.target.id==="progress"){

            parent = e.target;
            let x = e.pageX - parent.offsetLeft;
            console.log(x);

        }

        if(e.target.parentNode.id==="progress"){

            parent = e.target.parentNode;
            let x = e.pageX - parent.offsetLeft;
            console.log(x);

        }

and other variations. I basically need that when I click on the parent element, get x coord in that element, starting with zero when I click the far left, where the arrow on the image points.

PS: If it's fixed value that's being added up to x it wouldn't be a problem, but since resolution gets changed(resize, or in mobile rotate), x coord isn't fixed at any given time even when clicking at exact same spot due to previously mentioned.

Edit as per request:

            <div id="progress" onClick={this.trackProgress} className="progress text-center">
                <div id="progress-bar-num" className="progress-bar-num">{Math.round(this.state.width.toFixed(2))+"%"}</div>
                <div id="progress-bar" onClick={this.trackProgress} className="progress-bar bg-success" style={{width: Math.round(this.state.width.toFixed(2))+"%"}}></div>
            </div>

Don't let my markup confuse you, it is done in React. Effect would be the same if it's done in vanilla js.

Upvotes: 0

Views: 177

Answers (1)

randomusername
randomusername

Reputation: 8087

Your problem is that you're handling the event in a parent of the status bar element, so .offsetX is relative to the x position of parent and not the status bar.

Put the event handler on the status bar element itself and the .offsetX property of the event will work as you expect.

Upvotes: 1

Related Questions