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
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With