user2611052
user2611052

Reputation: 39

Simple JQuery script working on JSFiddle, not on my site

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.

Upvotes: 3

Views: 164

Answers (4)

Mark Schultheiss
Mark Schultheiss

Reputation: 34158

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"});
}

Upvotes: 0

adeneo
adeneo

Reputation: 318182

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.

Upvotes: 1

Karl Anderson
Karl Anderson

Reputation: 34846

Use the jQuery document ready function like this:

$(document).ready(function(){

});

This is a common "bug" with code that is copied from jsFiddles.

Upvotes: 2

Okazari
Okazari

Reputation: 4597

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"});
    }
});

Upvotes: 0

Related Questions