Reputation: 11
I have an embarrassingly simple question: How can I display an image at double its size without hard coding the width and height attributes? Here's what I tried, but I ended up having to just enter 1000 for width and height. Is something wrong with my function? Thanks!
<img onload="double(self.id);" name="bigPic" id="bigPic" src="album1.jpg" height="1000" width="1000"/>
function double(id) {
var img = document.getElementById(id);
var dblWdth = img.width * 2;
var dblHt = img.height * 2;
img.height = dblHt;
img.width = dblWdth;
}
Upvotes: 1
Views: 3235
Reputation: 12576
if you use jquery, you can do it this way:
<img name="bigPic" id="bigPic" src="album1.jpg" />
<script type="text/javascript">
$(document).ready(function () {
$("#bigPic")[0].width *= 2;
$("#bigPic")[0].height *= 2; // may not be necessary, see note
});
</script>
without jquery:
as pointed out by Okonomiyaki3000, double
is not a good name for function name since it's a reserved word for a data type in JavaScript.
<img name="bigPic" id="bigPic" src="album1.jpg" onload='superSize(this);' />
function superSize(me) {
me.width = me.width * 2;
me.height = me.height * 2; //may not be necessary, see note
}
note: looks like if you don't specify the height, height is automatically doubled. and vice-versa for width. but i only tested on IE9 and FF12.
Upvotes: 0
Reputation: 3696
You don't really need javascript for this. You can do it with CSS.
img {
zoom: 2;
-webkit-transform: scale(2);
-moz-transform: scale(2);
-ms-transform: scale(2);
-o-transform: scale(2);
transform: scale(2);
}
This will, of course, double the size of all images on the page. Maybe instead you'd like to make a class and assign it to all images that should be doubled or find some other way of selecting just those images. You could also set it up to double in size on mouseover (hover) or scale up with an animation (in some browsers) purely with css.
Upvotes: 3
Reputation: 160883
Not double(self.id);
but double(this.id);
The demo.
And you could just pass this
, that will be more simple.
function double(img) {
img.height *= 2;
img.width *= 2;
}
Upvotes: 2
Reputation:
you have to use window.load function() to achieve this
window.onload=function() {double("bigPic");
}
Upvotes: 0
Reputation: 993
window.onload = function() {
double("bigPic")
};
That should do the trick. You can use the window onload method to do everything that needs to be done when pages is loaded.
Upvotes: 0