Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery offset() behaving strange

Tags:

jquery

I want to put a translucent screen over a div so I can show an image on top of the screen without the div contents being a distraction. The main div could move around so I read its current width, height, and offset with jQuery and then apply those to the screen. But the screen appears in a different place each time! The core code is

$('#on').click(function () {
    canvasOffset = $('#canvas').offset();
    canvasWidth = $('#canvas').width();
    canvasHeight = $('#canvas').height();
    $('#canvasScreen').width(canvasWidth).height(canvasHeight).offset(canvasOffset).css({'opacity':'0.7', 'display' : 'block'});
    console.log("canvasHeight", canvasHeight, "canvasWidth", canvasWidth, "canvasOffset", canvasOffset);
});

There's a jsfiddle here: http://jsfiddle.net/bdWW3/1/

When you click Screen On the screen is applied. When you click Screen Off the screen is removed. When you click Screen On again the screen is applied, but it appears in a different place, no longer exactly over the canvas div. But console.log shows exactly the same parameters being put into the jQuery offset() call!?

Does anyone see what's going on?

Thanks

like image 435
Steve Avatar asked Feb 16 '23 08:02

Steve


2 Answers

The offset is being applied twice the second time you click on, from top: 110px; left: 8px to top: 220px; left: 16px.

You should reset the offset with .offset({left:0, top: 0}) when you click off.

$('#off').click(function () {
    $('#canvasScreen').offset({left:0, top: 0}).css({
        'display': 'none'
    });
});

See DEMO.

like image 78
Antony Avatar answered Feb 18 '23 22:02

Antony


Ah! Got it!

I was applying .offset() to an element that had no width and no height, i.e., the state left by display:none, and this gives unreliable results. I have to "display:block" the element before applying an offset to it before the offset will behave sanely. Just changing the order of the methods in the chain works:

$('#canvasScreen').width(canvasWidth).height(canvasHeight).css({'opacity':'0.7', 'display' : 'block'}).offset(canvasOffset);

like image 24
Steve Avatar answered Feb 19 '23 00:02

Steve