I'm trying to get the height, width, and placement of a section of HTML code, so that I can create a <div>
with position: absolute
to overlay the HTML in question. Sometimes this HTML is a single element, other times it's a bunch of elements.
I've tried to wrap the HTML code in question in a <span>
and then use $('#spanToMeasure').height()
and .width()
and .offset()
, but I'm getting inconsistent results. Sometimes the height and/or width returns as 0, when it really isn't, and sometimes the placement is off.
I've also tried using $(window).load()
instead of $(document).ready()
, but the results appear the same.
Is my method not working due to CSS that's changing the dimensions/placement? Or is something else going on? Any help is appreciated!
Here's my full code:
$(document).ready(function() {
// Create a container to hold all of the overlays.
var $overlayContainer = $('<div id="easy_edit_overlays">').appendTo('body');
// Find all of the sections of code to create overlays for.
$('span.easy_edit').each(function() {
var $this = $(this);
$this.removeClass('easy_edit');
var height = $this.height();
var width = $this.width();
var offset = $this.offset();
// Create overlay.
var $editOverlay = $('<div>').addClass('easy_edit_overlay')
.height(height)
.width(width)
.css('background-color', 'red')
.css('opacity', '0.5')
.css('top', offset.top)
.css('left', offset.left)
.css('position', 'absolute');
// Create link to include within overlay.
var $editLink = $('<a>').attr('href', $this.attr('class'))
.attr('target', '_blank')
.css('display', 'block')
.css('height', height)
.css('color', 'red')
.text('Edit');
$editLink.appendTo($editOverlay);
$editOverlay.appendTo($overlayContainer);
// Remove the <span> tag and replace with its children.
$this.replaceWith($this.html());
});
});