1

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

function socialExt()
{
    document.getElementById("Left").style.width = ("Left").width+240px;
}

I want it to add 240 pixels every time I click on the button.

  • What should I replace ("Left").width with in order to access its width so I can add 240px to it
  • I am also currently not using JQuery, should I use it?
7
  • Try document.getElementById("Left").style.width += 240;. Commented Dec 23, 2013 at 20:40
  • 1
    And jQuery is pretty damn useful, and generally makes DOM manipulation stuff like this easy. It really depends on your project whether its "worth" it, but on most projects, I'll just drop it in b/c it's become so ubiquitous Commented Dec 23, 2013 at 20:41
  • 1
    Also, FYI, that style of "brace placement" ({ on its own line) is problematic with javaScript in some edge cases. Its preferable to move it to the same line function socialExt() { Commented Dec 23, 2013 at 20:42
  • 2
    @ZachL Because of the px in the value, your 1st suggestions will likely result in NaN. Commented Dec 23, 2013 at 20:43
  • @JonathanLonowski How about document.getElementById("Left").style.width = String(int(document.getElementById("Left").style.width.replace('px', '')) + 240) + 'px'; Commented Dec 23, 2013 at 20:44

7 Answers 7

3

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

function socialExt()
{
    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.

Sign up to request clarification or add additional context in comments.

2 Comments

Don't use parseInt without a radix. This won't work unless an inline style is already setting the width (and if it is set to use something other than pixels, it will give undesired results).
Good point about setting the radix--I've edited my answer. I believe this would actually manually set the width/inline style (although I could be wrong--not sure if it's entirely cross browser), but so long as the string begins with numerals you can parse any trailing dimensions.
2

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

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

8 Comments

That will typically end up giving you something like NaN as a result (since you can't add 240 to undefined). Alternatively, if the inline property is set already, it is likely to give you "240px240", which also isn't a valid value.
@aksu Perhaps edit your post so your code reads document.getElementById("Left").style.width = int(document.getElementById("Left").style.width.replace('px', '')) + 240 to fix the problem?
@ManofSnow — That won't do any good if the value is undefined and if it is set that assumes it is set to a px value and even if it is, then it will try to set it to a number instead of a length which still isn't allowed.
After the latest edit to this answer, it will throw ReferenceError: int is not defined (and have all the problems from my previous comment)
@Quentin Small fix: document.getElementById("Left").style.width = String(int(document.getElementById("Left").style.width.replace('px', '')) + 240) + 'px';
|
1

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");
}

3 Comments

How could I add an if statement to do the action if the width is less than 640px
and am I also confined to using inline css or could I use a separate document?
This would work fine regardless of where the css is. Updating the Answer now for your conditional (<640px)
1

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.

2 Comments

FYI, this can be shortened to $('#Left').width("+=240"); - a neat and undocumented(?) shorthand!
@ZachL - I had to see it to believe it. It's not explicitly stated in the jquery documentation, but it does say if the value is a string, it can be any valid CSS measurement. So I'm guessing it is CSS that allows that.
0

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

1 Comment

Assuming that the existing value is a pixel length already, this will give you a value like "240px240px" which isn't valid.
0

element.style.width return string (the width of element in px). So the good way to solve your problem you need to parse width in integer then add 240 then finally add 'px' to your width like below

function socialExt()
{
    var elem =document.getElementById("Left");
    elem.style.width= parseInt(elem.style.width||0,10) + 240+'px' 
}

you can check the fiddle here

1 Comment

edit : this will take care if width is not provided in style of the element.
-1

Since you haven't stated what the initial status of the element is, it could be any one of the following:

  • No width specified
  • A width specified in pixels (the unit you want to modify it with)
  • A width specified in some other unit

So the first thing you must do is normalise this. You can do this using getComputedStyle, but since you are using jQuery (or have at least tagged it on the question), you can also just let it handle it for you.

var element = jQuery('#Left');
var initial_width = element.width();

This will give you the width in pixels expressed as a Number.

You can then add to this and set the width to the new value.

var desired_width = initial_width + 240;
element.width(desired_width);

Or in one line:

jQuery('#Left').width( jQuery('#Left').width() + 240 );

See a live demo

Or without jQuery:

var element = document.getElementById('Left');
var style = getComputedStyle(element, null);
var initial_width = style.width;
var initial_pixels = parseFloat(initial_width);
element.style.width = initial_pixels + 240 + "px";

See a live demo.

2 Comments

The initial width is 240px. Would that change anything you just told me?
If, and only if, the initial width is set using inline style, then there are slightly simpler ways that you could write the code, but the approaches in this answer will still work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.