MeltingDog
MeltingDog

Reputation: 15458

JQuery/CSS: Append div using mouse coords and position: absolute

OK complicated one - I have created some code to append a div within a wrapper div:

$("#container").click(function(e){
   var parentOffset = $(this).parent().offset(); 
   var relX = e.pageX - parentOffset.left;
   var relY = e.pageY - parentOffset.top;

 $('#container').append('<div class="placeddiv" style="left:' + relX + '; top:' + relY +';"></div>');

This works ok if the placeddiv is set to position: absolute;

However, my container div is intentionally large (10,000px by 10,000px) and thus my wrapper div has overflow:scroll.

The issue is the placeddivs do not stay in the one position relative to the container. They only stay positioned relative to the wrapper.

I have tried using position:relative but then the placeddivs 'stack' on top of each other (ie you cannot add a 2nd placeddiv above the first).

Does anyone know a way around this?

(PS: I have tried to create a Fiddle http://jsfiddle.net/7WQ5Q/20/ but even though I have copied from my local verbatim (just changed names of divs to be more meaningful) it wont work. Never used JSFiddle before so I could be doing something wrong)

Any help is appreciated!

Upvotes: 4

Views: 6224

Answers (1)

Levi
Levi

Reputation: 2113

Couple of things:

  1. there was a JS typo
  2. you need to specify px if you're going to set the position like that.
  3. your container needs to have position: relative
  4. you need to account for the scrolling yourself

See this working fiddle forked from yours (updated with cleaner code): http://jsfiddle.net/wWEqP/5/

$("#container").click(function(e){
    var wrapper = $(this).parent();
    var parentOffset = wrapper.offset(); 
    var relX = e.pageX - parentOffset.left + wrapper.scrollLeft();
    var relY = e.pageY - parentOffset.top + wrapper.scrollTop();

    $(this).append($('<div/>').addClass('placeddiv').css({
        left: relX,
        top: relY
    }));    
});

does that cover everything you were trying to accomplish?

Upvotes: 7

Related Questions