I am a total newbie to JavaScript and jQuery, and need some help. Also I apologise if it’s easy and Im just not seeing it!
Basically, I’m trying to find the size of an image after it has loaded, so I can use this information to adjust the width of a div.
This is the code currently:
<script type="text/javascript" src="js/jquery.js"></script>
<img id="Img1" src="01.jpg" style="height: 50%; width: 50%;" />
<script>
$(document).ready(function() {
$(Img1).load(function() {
alert($(this).width());
});
});
</script>
Which creates a prompt box with the correct width! But I cant seem to find a way to reuse this information or declare a variable from it!
Please can anyone help me? Any help would be greatly appreciated! Thanks.
Since
Img1is the id ofimgelement use it as id to select it. To store the value of width you can declare a variable and store in it. And then use the variable wherever required.You should learn at various selectors that
jQueryoffers you to use based on your markup structure. Take a look at this link http://api.jquery.com/category/selectors/Note: If you want to use this variable across the page then you should define it in the outer or global scope.