Positioning a pop up element on a browser window

While working in my last CakePHP project i needed a piece of javascript code that should help me in positioning a absolute pop up element near mouse click. I had been using prototype library for javascript stuff so i looked around for something real quick and useful to position element (Some useful Position methods with its Object has already been deprecated in new prototype library), and, what i came up with was tooltip.js, a small plugin for prototype library to show tooltips on mouse over and hide them on mouse out event. This was a simple EventObserver class which handled tooltips quite well. However, i looked for a straight way to position element utilizing prototype.

Finally what i came up with was a strange mix of tooltip.js and core javascript code which i am just putting here for my own reference. I am sorry for perfectionists there!

function getWindowWidth() {
  var innerWidth;
  if (navigator.appVersion.indexOf('MSIE')>0) {
    innerWidth = document.body.clientWidth;
  } else {
    innerWidth = window.innerWidth;
  }
  return innerWidth;	
}

function getWindowHeight(){
  var innerHeight;
  if (navigator.appVersion.indexOf('MSIE')>0) {
    innerHeight = document.body.clientHeight;
  } else {
    innerHeight = window.innerHeight;
  }
  return innerHeight;
}

function PositionIt(elem, event) {
  var options = Object.extend({
    margin: "0px",
    padding: "5px",
    backgroundColor: "#d6d6fc",
    delta_x: 5,
    delta_y: 0,
    zindex: 1000
  });

  var dimensions = Element.getDimensions(elem);
  var element_width = dimensions.width;
  var element_height = dimensions.height;

  Event.stop(event);

  var mouse_x = Event.pointerX(event);
  var mouse_y = Event.pointerY(event);

  if ( (element_width + mouse_x) >= ( getWindowWidth() - options.delta_x) ){
		mouse_x = mouse_x - element_width;
		mouse_x = mouse_x - options.delta_x;
	} else {
		mouse_x = mouse_x + options.delta_x;
	}
	
	if ( (element_height + mouse_y) >= ( getWindowHeight() - options.delta_y) ){ 
		mouse_y = mouse_y - element_height;
		mouse_y = mouse_y - options.delta_y;
	} else {
		mouse_y = mouse_y + options.delta_y;
	} 

       if(mouse_x<0) mouse_x = 0;
       if(mouse_y<0) mouse_y = 0;
	
       Element.setStyle(elem, { position:'absolute',
	 	 top:mouse_y + "px",
	 	 left:mouse_x + "px",
		 zindex:options.zindex,
                 display:""
      });

      Element.show(elem);
}

Although i had been using prototype library i used some shortcut methods like Element.getDimensions(elem), Element.setStyle(), Element.show(elem) and Event.Stop() and i guess these are the only shortcuts which relate to prototype otherwise it is a pure core javascript code to position a pop up element on a browser window.

Leave a Reply