How can I get the width (set in the css styles) of a element that is hidden?
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);
How can I get the width (set in the css styles) of a element that is hidden?
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);
Share
Improve this question
edited May 2, 2011 at 10:09
Alexa
asked May 2, 2011 at 9:39
AlexaAlexa
2251 gold badge3 silver badges7 bronze badges
2
-
Did you use
visibility: hidden
ordisplay: none
? – Joachim Sauer Commented May 2, 2011 at 9:41 - I posted the code. It's not exactly like this, but its similar to what I have.. – Alexa Commented May 2, 2011 at 9:51
3 Answers
Reset to default 3This may be impossible, because $(this)
refers to the window
object in this case and not the <a>
element. The this
reference will be properly bound to the newly created element only if called in the context of a function.
There might be a way to inject the element into this
using closures but I can't figure out how - interested to see whether somebody can e 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
-Assuming that you want the width of the .nav element (the element that has been hidden).
since you are using $('<a>')
you are actually creating an anchor tag and in that case $(this) will refer to the anchor element and not the .nav element and so its width is ing out to be 0.
if you wish to get the width of the .nav element u can use
$('.nav').width();
and this will get you the width of the matched elements.
Try this please:
$('a').click(function(){
$(this).appendTo(nav);
alert($(this).width());
$(this).css('left', ($(this).width() / 2));
return false;
})