Dan
Dan

Reputation: 363

Jquery variable losing value when element is deleted

I'm grabbing the width of an image and storing it in a variable, then deleting the image. After I delete the image, the variable value reverts to 0. Is there a way to have this value stick or a different way to accomplish it?

Here's some code for the confused:

bgWidth = $('#widthContainer img').width();

     alert(bgWidth); // value equals the image's width
$('widthContainer').empty();
     alert(bgWidth); // value equals now equals 0

Upvotes: 0

Views: 249

Answers (2)

jbabey
jbabey

Reputation: 46647

you're missing var on bgWidth = ..., you're missing a # on $('widthContainer'), and you're missing ; on both the second and fourth lines.

with those changes, this works as expected (in firefox)

http://jsfiddle.net/B6RGJ/

var bgWidth = $('#test #sub').attr('id');

alert(bgWidth); // value equals the image's width
$('#test').empty();
alert(bgWidth); // value equals now equals 0

I am using a div's ID instead of an image's width here, but it should not matter if you are storing it in a variable.

Upvotes: 5

adeneo
adeneo

Reputation: 318182

Maybe if you try it as a variable:

alert(bgWidth);

Upvotes: 0

Related Questions