Zeca Novaes
Zeca Novaes

Reputation: 419

Using jQuery function if element width is valid

I'm new to jQuery and I found this code to use in my site:

$(function() {
  elemWidth = parseInt(getComputedStyle(document.querySelector("#checkVw"), null).width, 10);
  halfWidth = parseInt(window.innerWidth / 2, 10);
  alert("Your browser " + ((elemWidth == halfWidth) ? "" : "does not ") + "support VW and VH");
});

The code check if my element have the size that I define in css, returning if users browser support my size unit (viewport).

What I need is load a script if elemWidth value is not the same as halfWidth, but I don't know how to change this alert to a conditioning function.

Thanks!

Upvotes: 1

Views: 36

Answers (3)

KornholioBeavis
KornholioBeavis

Reputation: 2442

var elemWidth =    parseInt(getComputedStyle(document.querySelector("#checkVw"), null).width, 10);
var halfWidth = parseInt(window.innerWidth / 2, 10);
elementWidth !== halfWidth ? alert("Your browser " + ((elemWidth == halfWidth) ? "" : "does not ") + "support VW and VH");

Upvotes: 0

adeneo
adeneo

Reputation: 318182

Pretty straight forward, place the comparison of the two values in a condition, and lot a script if they are not equal.

$(function () {
    var elemWidth = parseInt(getComputedStyle(document.querySelector("#checkVw"), null).width, 10);
    var halfWidth = parseInt(window.innerWidth / 2, 10);

    if ( elemWidth !== halfWidth ) {

        $.getScript('whatever.js');

    }
});

Upvotes: 1

Josh Crozier
Josh Crozier

Reputation: 240888

The expression ((elemWidth == halfWidth) ? "" : "does not " makes use of the conditional ternary operator.

It is short for:

if (elemWidth == halfWidth) {
  // ""
} else {
  // "does not"
}

Therefore if you want to load a script if the elemWidth value is not the same as halfWidth, then you could simply use the $.getScript function or whatever you are using the load the script.

if (elemWidth !== halfWidth) {
  $.getScript('...');
}

Upvotes: 2

Related Questions