views:

427

answers:

1

hi guys

i am trying to implement jquery image hover popup but facing a problem when the popup is closer to browser edge it goes beyond its edge i want it to change its direction when it finds that space is not enough to show that popup, i have see this effect in many plugins where popups, tooltips and drop down menus change their direction if they are close to browser window edge

can any one guide me in right direction here is the screen shot for reference http://img512.imageshack.us/img512/4990/browseredge.png

here is the jquery hover code

function imagePreview(){ 
 /* CONFIG */

  xOffset = 10;
  yOffset = 30;

  // these 2 variable determine popup's distance from the cursor
  // you might want to adjust to get the right result

 /* END CONFIG */
 $("a.preview").hover(function(e){
  this.t = this.title;
  this.title = ""; 
  var c = (this.t != "") ? "<br>" + this.t : "";
  var newName = this.name;
  //console.log(this.name);
  newName=newName.replace("/l/","/o/");
  //console.log(newName);
  $("body").append("<p id='preview'><img src='"+ this.name +"' alt='Image preview' style='margin-bottom:5px;'>"+ c +"</p>");
  $("#preview img").error(function () {
   $("#preview img").attr("src" ,newName).css({'width': '400px', 'height': 'auto'});
  });

  $("#preview")
   .css("top",(e.pageY - xOffset) + "px")
   .css("left",(e.pageX + yOffset) + "px")
   .fadeIn("fast");      
    },
 function(){
  this.title = this.t; 
  $("#preview").remove();
    }); 
 $("a.preview").mousemove(function(e){
  $("#preview")
   .css("top",(e.pageY - xOffset) + "px")
   .css("left",(e.pageX + yOffset) + "px");
 });   
};

any help will be appriciated

Thanks

Salman

+2  A: 

Your extract is a bit bloated with other unrelated code/long for me to spend too much time looking at it, but understanding your problem I think this snippet of code I wrote to deal with a mega-drop-down navigation and ensuring it never went off-screen will probably help you.

function resize() {
  var viewportWidth = window.innerWidth ? window.innerWidth : $(window).width();

  if (jQuery.browser.msie) {
    if(parseInt(jQuery.browser.version) == 7) {
      viewportWidth -= 3;
    }
  }

  $('ul#nav .sub').each(function() {
    $(this).css({'display': 'block', 'left': ''});
    var offset = $(this).offset().left + $(this).outerWidth(true) + 10;

    if(offset > viewportWidth) {
      ie6offset = $.browser.msie && $.browser.version.substr(0,1)<7 ? 30 : 0;
      $(this).css({
        'left': -(offset + 10 - viewportWidth) - ie6offset
      });
    }
  });
}

In summary the function calculates the true offset of the right-hand edge of .sub. And then checks that offset against the width of the viewport taking into account browser inconsistencies. In the event that the offset is greater than the width of the viewport, it is necessary to set a negative left value to keep the element on-screen.

Steve
great let me have a look, i just need a direction , this may be it
Salman