stress_tn
stress_tn

Reputation: 174

If element width more than 80%

Tell me please how can I made function right

var $photoblock = $(".element img");
if ($photoblock).width() > 80%){
$photoblock.css({width: 80%, max-width: 'none'});
} else {
$photoblock.css({width: auto, max-width: 100%});
});

How would be right?

Upvotes: 2

Views: 4247

Answers (3)

Pranav C Balan
Pranav C Balan

Reputation: 115222

Try something like this

var $photoblock = $(".element img");
var per = $photoblock.parent().width() * 0.8;
if ($photoblock.width() > per) {
    $photoblock.css({
        width: '80%',
        'max-width': 'none'
    });
} else {
    $photoblock.css({
        width: 'auto',
        'max-width': '100%'
    });
}

$photoblock.width() will return the width in pixel not in percentage. Hence you need to find out the 80% of it's parent and then need to compare it.

Upvotes: 3

Abhitalks
Abhitalks

Reputation: 28387

You need to get the css width (if specified in percentage), then parseInt it to get the value which you can use in calculation or comparision:

if (parseInt($photoblock.css('width')) > 80){..

Otherwise, compare it with the parents width (as suggested by other posters):

if ($photoblock).width() > $parent.width() * .8) { ...

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388326

The .width() does not give the width in %, so compare it against the width of the parent, also there are few other syntax issues

var $photoblock = $(".element img"),
    $parent = $photoblock.parent();
if ($photoblock).width() > $parent.width() * .8) {
    $photoblock.css({
        width: '80%',
        'max-width': 'none'
    });
} else {
    $photoblock.css({
        width: 'auto',
        'max-width': '100%'
    });
});

Upvotes: 1

Related Questions