I'm trying to get the original width of an image with JQuery and make some adjustments in the CSS with a condition if an image is wider than 700px.
I used this code to get the width of an image:
var img = new Image();
img.src = $('#imageViewerImg').attr('src');
img.onload = function () {
var W2 = this.width;
alert(''+ W2);
}
Fiddle
You can see that an alert box shows the width of the image, in this case 1024. When I copy paste this code, it doesn't work on my website. It simply won't display the alert box. I have JQuery included properly, as other JQuery codes work, it's just this simple piece of JQuery that doesn't do what it's supposed to do.
At the end, this is the code I need for the functionality I'm trying to create:
var img = new Image();
img.src = $('#imageViewerImg').attr('src');
img.onload = function() {
var imgWidth = this.width;
}
if($imgWidth > 700) {
$("#photoHolder").css({"vertical-align":"none","text-align:":"none"});
}
Why does the alert box show up on JSfiddle but not on my own PC?
Also with the document.ready function, it still won't work. The JQuery is simply not being executed.
$imgWidthis undeclared in your code. andimgWidthis useless in this context.