Skip to content Skip to sidebar Skip to footer

Using Javascript To Add Width To A Html Element

I am trying to work with altering a div tag's position and size with a JavaScript function and am confused about how to reference the current width of the div. This is my function

Solution 1:

Assuming you consistently have a dimension at the end of your string, parseInt() will do the job for you.

functionsocialExt()
{
    var el = document.getElementById("Left");
    el.style.width = (parseInt(el.style.width, 10) + 240) + 'px';
}

Above we parse the value with a trailing px into an integer (you could also use floats), add 240 to it, and then coerce the number to a string as we append 'px' to it.

Solution 2:

No jquery needed for this. Little modification and it should work:

functionsocialExt() {
    var el = document.getElementById("Left");
    var width = parseInt(el.style.width);
    el.style.width = (width + 240) + "px"
}

Solution 3:

Quick and dirty jQuery version:

$('#Left').width("+=240");

Edit for use case in comments

if ($('#Left').width() < 640) {
    $('#Left').width("+=240");
}

Please check out the documentation for more information and examples.

Note that in my example above, it would be a bit more performant if you extracted $('#Left') out into a variable. This is more efficient b/c you only have to query the DOM once. This probably isn't something you need to be worrying about, but its good to know. Revised example below:

var el = $('#Left');
if (el.width() < 640) {
    el.width("+=240");
}

Solution 4:

With JQuery you can use:

var$element = $('#Left');
$element.width($element.width() + 240);

Demo on jsfiddle

The JQuery .width() function returns an integer which represents the element's width in pixels. It also appears to work regardless of whether or not the width is explicitly set on the element. It also doesn't matter if the original width was specified in units other than pixels (for example, "20em").

This is one nice thing about using a library like JQuery, but it probably isn't enough of a reason to use it in this case. If, however, you are going to be adding a lot more JavaScript to your pages, you should consider using it.

Solution 5:

There can be these answers for this question.

First method would be the usage of JS. You are doing it a bit wrong. Since in the first place you are using the document.get... method to get the element so you will have to use the same thing to get the element again.

document.getElementById("Left").style.width = 
                  (parseInt(document.getElementById("Left").width) + 240) + "px";

You can try jQuery:

http://jsfiddle.net/afzaal_ahmad_zeeshan/Tr223/1/

$('#div').width($('#div').width() + 240 + 'px'); // add 240 to the width

Post a Comment for "Using Javascript To Add Width To A Html Element"