Search code examples
javascriptjspdom-events

Setting div position using coordinates


I'm having a web page (jsp) that included another jsp using

     <%@jsp:include ... %>

When I click on the second part (included page), getting the co-ordinates using:

    window.event.clientX 
    window.event.clientY

and storing into x and y respectively. Now I'm setting a div to visible at that mouse co-ordinates like,

    document.getElementById('division').style.top=x;
    document.getElementById('division').style.left=y;

as expected to display that div at the same spot where the mouse clicked. But the division is coming somewhere else.

What is the reason for that?


Solution

  • The top property is a string. Try document.getElementById('division').style.top=x + 'px';

    I tried the following code and it worked fine for IE and Firefox. The onclick is for IE, the addEventListener is for compliant browsers.

    <div id="clickMe" style="position: absolute; top: 10px;" onclick="myClick();">
        clickMe
    </div>
    <div id="division" style="position: absolute; top: 40px;">
        division
    </div>
    <script type="text/javascript">
        var clickMe = document.getElementById('clickMe');
        clickMe.addEventListener('click', myClick, 'false');
    
        function myClick(e) {
            var evt = e || window.event; //windows.event is for IE
            var x = evt.clientX;
            var y = evt.clientY;            
            document.getElementById('division').style.top = y + 'px';
            document.getElementById('division').style.left = x + 'px';
        }
    </script>