user2014429
user2014429

Reputation: 2577

positioning div with setInterval function

I have this div which appears under certain elements when they are clicked. I had a problem when the page was zoomed, as this caused the div to lose perspective and a gap appeared between the element and the div. So I tried tho set up a setInterval function which would re-position the div every second which would solve the problem. unfortunately it does not seem to be effective, I can't figure out why, and hope that someone might see where i'm going wrong. I have made a rudimentary mock-up which demonstrates this. If you visit this jsFiddle and click the inputs, then zoom in/out you can see that a gap appears, and the setInterval function is ineffective. Thank you for reading. I'll put the code below, but the jsFiddle really demonstrates better.

N.B in the real version the gaps are much bigger.

var eleTop,
 eleLeft;

 setInterval(function(){
    $('#box').css({
       top: eleTop + "px",
       left: eleLeft + "px",

   });
 }, 100);

 $('body').click(function(e){

   eleTop =  $(e.target).offset().top + 27;
   eleLeft = $(e.target).offset().left;

 $('#box').css({

     top: eleTop + "px",
     left: eleLeft + "px",
  });

      $('#box').show();

});     

html:

<body>
   <input type = "text" />
   <input type = "text" />
   <input type = "text" />

   <div id = "box">box</div>

</body> 

Upvotes: 1

Views: 112

Answers (1)

dfsq
dfsq

Reputation: 193281

Well, I can suggest another approach. Try to use CSS instead of javascript for positioning. It can be really effective. What you can do is to wrap input elements into another div and position #box absolutely relatively to parent wrapper:

CSS

.wrap {
    display: inline-block;
    padding: 0;
    margin: 0;
    position: relative;
}
.wrap #box {
    display: block;
    position: absolute;
    top: 100%;
    left: 0;
    z-index: 1000;
}

HTML

<div class="wrap"><input type="text" value="click"></div>
<div class="wrap"><input type="text" value="one"></div>
<div class="wrap"><input type="text" value="of us"></div>

Javascript is only used to append #box to corresponding wrapper (parent of currently focused input):

var eleTop,
    eleLeft,
    $box = $('#box');

$('input').click(function (e) {
    $(this).parent().append($box);
});

Demo: http://jsfiddle.net/TxGW4/5/

Upvotes: 1

Related Questions