JQuery - $ (this) .width () does not work if the element is hidden!

How can I get the width (given in css styles) of a hidden element?

CSS

a{
  position: absolute;
  width: 40px;
  height: 40px;
  background: pink;
}

JS:

var nav = $('.nav');
nav.hide();

nav.hover(function(){
  nav.stop().animate({opacity: 1}, 300);
}, function(){
  nav.stop().animate({opacity: 0}, 500);
});

$('<a>', {
css: { left: 940 / 2 - ($(this).width() / 2), // <-- here it seems to be 0
click: function(){
    alert($(this).width()); // here it works
    return false;
  }
}).appendTo(nav);
+3
source share
3 answers

This may not be possible because it $(this)refers to the object windowin this case, and not to the element <a>. The link thiswill be properly linked to the newly created element only if called in the context of the function.

There may be a way to insert an element in thisusing closures, but I can't figure out how interesting it is, can anyone come up with a solution.

Until then, this alternative is less elegant, but will always work:

mylink = $('<a>', {
    id: 'test',
   click: function(){
   alert($(this).width()); // here it works
   return false;
 }
}).appendTo($("body")).html("Test");;

mylink.css({ left: mylink.width() / 2});

Jsfiddle

+3
source

- , .nav(, ).

$('<a>'), , $(this) , .nav, 0.

.nav,

$('.nav').width();, .

+1

Try the following:

$('a').click(function(){
    $(this).appendTo(nav);
    alert($(this).width());
    $(this).css('left', ($(this).width() / 2));
    return false;
})
+1
source

All Articles