Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display a div below an input field of the exact width using jQuery

Tags:

jquery

I currently use the following code to position a div directly below an input text field on focus. The problem is the width of the div varies between browsers. Is there a way to ensure the div that appears is the exact width as my input field?

  // get the field position
  var inputField = $('#inputfield');
  var fieldDiv = $('div.divname');
  var sf_pos    = field.offset();
  var sf_top    = sf_pos.top;
  var sf_left   = sf_pos.left;
  // get the input field size
  var sf_height = inputField.height();
  var sf_width  = inputField.width();

  fieldDiv.css("position","absolute");
  fieldDiv.css("left", sf_left);
  fieldDiv.css("top", sf_top + sf_height + 6);
  fieldDiv.css("width", sf_width);

  $('#inputfield').focus(function() {
    fieldDiv.fadeIn('medium');
  }).blur(function() {
    fieldDiv.fadeOut('medium');
  });
like image 221
Lyon Avatar asked Oct 15 '22 08:10

Lyon


1 Answers

i think this may be related to IE not respecting the box model, and some browsers will also include borders in the widths and others wont.

have you tried using outterWidth() instead of width()?

also You can hack it and add offsets that are browser dependent, for example:

width += ($.support.boxModel ? 0 : 2);
like image 168
mkoryak Avatar answered Oct 18 '22 22:10

mkoryak