Position Elements relative to clicks using Javascript

Recently I was playing around on my sandbox personal site with some ideas to dynamically  move and position elements relative to on screen clicks in ways that are compatible with different browsers and different resolutions. The scripts I used to do this were then implemented by a fellow developer on a client’s site to solve a problem with having a customized pop-up div displaying at the correct location when clicking.

Note: Majority of the code was copied from several sources and thrown together and then modified to solve the problem. This is also done without the use of JQuery.

The process can be broken down into several steps.

  1. Find out which browser is being used and find the size of the client’s window.
  2. Find out where on the screen was clicked.
  3. Profit.


Step 1

See which browser is being used and find out the size of the client window. (This can be done in a function or in document ready)

var w = 0, h = 0;
if( typeof( window.innerWidth ) == 'number' ) {
//For non-IE browsers
    w = window.innerWidth;
    h = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//For the latest IE browsers
    w = document.documentElement.clientWidth;
    h = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
//Compatible with older IE browsers
    w = document.body.clientWidth;
    h = document.body.clientHeight;
}

Step 2

Now inside your function you run after the click event
on whichever object determines when/where something has to happen you can add the following:

function foobar(e) {
    var posx = 0;
    var posy = 0;
    if (!e) var e = window.event;
    if (e.pageX || e.pageY)   {
        posx = e.pageX;
        posy = e.pageY;
    }
    else if (e.clientX || e.clientY)   {
        posx = e.clientX + document.body.scrollLeft
        + document.documentElement.scrollLeft;
        posy = e.clientY + document.body.scrollTop
        + document.documentElement.scrollTop;
    }
}

Step 3

Now that you have the click location and the width / height of your display area and with knowledge of your layout you can use basic JQuery functions to animate objects dynamically; show or hide objects dynamically; and a host of other options. The limit is your creativity and current browser standards :P

Leave a Reply