Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery help with if statement

I'm trying to scale images that have a width greater than 100. I'm using the code below, but it scales images that are even below 100px... What am I doing wrong?

if($(".image-attach-body")) {
    if($(".image-attach-body a")) {
    $(".image-attach-body a").each(function() {
                var width = $("span span img").width();

                if(width > 100) {
                    $("span span img").cjObjectScaler({
                            destObj: $(".image-attach-body"),
                                method: "fit",
                });
                }
    }); 
    }
}
like image 742
phpN00b Avatar asked Dec 14 '25 12:12

phpN00b


2 Answers

If all of your images were under 100, your code would work. Here is the problematic line of code...

$("span span img").cjObjectScaler

This selector is inside of your each loop. So if just one image is greater than 100, you invoke this function to all of them. The function call applies to every element that matches the selector (that's just how jQuery works).

I don't know what your markup looks like, so I can't tell you what to change the code to. Inside your each loop, you will likely need to utilize this somewhere in your selector so that it is more specific and relevant to the given context.

I would guess it needs to be changed to this...

$("span span img", this).cjObjectScaler

EDIT: You'll also need to change the line of code to do this where you get the width of the image, because that will always only return the width of the first image it finds. I'd recommend storing it in a local variable so you don't have to re-query for it later when you apply the "scaler"

like image 165
Josh Stodola Avatar answered Dec 16 '25 05:12

Josh Stodola


The main problem, is you are not scoping the search, so your final $('span span img') is finding all the img in the page. Here is a function that fixes a few other problems as well. Please ask if it doesn't make sense:

if( $(".image-attach-body").length ) {
    $(".image-attach-body a").each(function() {
        var $img = $("span span img", this),
            width = $img.width();

        if(width > 100) {
            $img.cjObjectScaler({
                destObj: $img.closest(".image-attach-body"),
                method: "fit",
            });
        }
    }); 
}

Note: Your first if statement would have always returned true because it returns an empty jQuery object if nothing is found, not null like you might expect. So changing it to .length verifies if found at least 1. The second if statement (which I removed) was unnecessary because the each loop would have run 0 times if no objects matched, so the test was wasted... and had the same problem as the first, in that it would always run.

like image 27
Doug Neiner Avatar answered Dec 16 '25 03:12

Doug Neiner