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
your variable $imgWidth
is undeclared in your code, and imgWidth
will not have scope outside your function.
try:
var img = new Image();
img.src = $('#imageViewerImg').attr('src');
var imgWidth='';
img.onload = function() {
imgWidth = this.width;
}
if(imgWidth > 700) {
$("#photoHolder").css({"vertical-align":"none","text-align:":"none"});
}
Use the jQuery document ready function like this:
$(document).ready(function(){
});
This is a common "bug" with code that is copied from jsFiddles.
Try it like this:
var img = new Image();
img.onload = function () {
var W2 = this.width;
if(W2 > 700) {
var photoHolder = document.getElementById("photoHolder");
photoHolder.style.verticalAlign = 'none';
photoHolder.style.textAlign = 'none';
}
}
img.src = document.getElementById('imageViewerImg').src;
Also, open the console and check for errors, check that you only have one element with that ID etc.
Use that to be sure that your code will be executed after the html loading.
$(document).ready(function(){
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"});
}
});