JSFiddle - React, Tailwind, and code Playground
by rodrigorf
HTML
<div id="caixa" class="grafico"></div>
<br>
Loader: <span id="posLoader"></span><br>
Caixa: <span id="posCaixa"></span> , largura:200px, centro: left 104px
<br>
<a id="btn" href="#"> Posicionar </a>
<br><br>
<div id="loaderAjax">
<img alt="loader ajax" src="http://www.cpdwise.com/images/lightbox-ico-loading.gif" />
</div>
CSS
.grafico { border:1px dashed red; width:200px; height:200px; position:relative; }
JavaScript
atualizar();
$('#btn').click(function() {
$('#loaderAjax').positionOn($('#caixa'), 'center');
atualizar();
});
//FUNCOES
function atualizar()
{
var positionLoader = $('#loaderAjax').position();
var positionCaixa = $('#caixa').position();
$( "#posLoader" ).text( "left: " + positionLoader.left + ", top: " + positionLoader.top );
$( "#posCaixa" ).text( "left: " + positionCaixa.left + ", top: " + positionCaixa.top );
}
$.fn.positionOn = function(element, align) {
return this.each(function() {
var target = $(this);
var position = element.position();
console.log('position:',position);
var x = position.left;
var y = position.top;
if(align == 'right') {
x -= (target.outerWidth() - element.outerWidth());
} else if(align == 'center') {
console.log('target.outerWidth:',target.outerWidth());
console.log('target.outerWidth:',element.outerWidth());
x -= target.outerWidth() / 2 - element.outerWidth() / 2;
}
target.css({
position: 'absolute',
zIndex: 5000,
top: y,
left: x
});
});
};