Width & Height

With SniperJs, it is easy to work with the dimensions of elements and browser window.

SniperJs width() and height() Methods

The width() method sets or returns the width of an element (excludes padding, border and margin).

The height() method sets or returns the height of an element (excludes padding, border and margin).

The following example returns the width and height of a specified <div> element:

$("#container").width();
$("#container").height();
$("button").click(()=>{
   let boxWidth = $("#div1").width(); // gets the width of the selected element 
   let boxHeight = $("#div1").height(); //get height of the selected element
});

Set the Width and Height

$("#container").width('200px'); // set 200px

$("#container").width('100%'); // sets 100%
$("#container").width(100); // sets 100px
$("#container").height(500); //sets 500px
$("button").click(function(e){
   let boxWidth = $("#div1").width(120); // sets 120px width to the selected element 
   let boxHeight = $("#div1").height(500); //sets 500px height to the selected element
});

You can simply chain it like this:

$("button").click(function(e){
   $("#div1").width(120).height(500);
});


Functional Setting of Width and Height

You can use the .width() and .height() methods with a callback function to set these values dynamically. The callback function makes the current value available. Here is an example:

$("button").click(() => {
   $("#div1").width(function(currentValue) {
        return this.height() + currentValue;
    });
});

In this example, clicking the button will update the width of the element by adding its current height to it width.

$("button").click(() => {
   $("#div1").height(function(currentValue) {
        return this.width();
    });
});

In this example, clicking the button will update the height of the element using it width.

Last updated