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?
Code Maverick
  • 19,231
  • 10
  • 57
  • 111
user3130697
  • 37
  • 1
  • 5
  • Try `document.getElementById("Left").style.width += 240;`. – Zach Lysobey Dec 23 '13 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 – Zach Lysobey Dec 23 '13 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() {` – Zach Lysobey Dec 23 '13 at 20:42
  • 2
    @ZachL Because of the `px` in the value, your 1st suggestions will likely result in `NaN`. – Jonathan Lonowski Dec 23 '13 at 20:43
  • @JonathanLonowski How about `document.getElementById("Left").style.width = String(int(document.getElementById("Left").style.width.replace('px', '')) + 240) + 'px';` – Cilan Dec 23 '13 at 20:44
  • `ReferenceError: int is not defined` – Quentin Dec 23 '13 at 20:45
  • @Quentin you're right, edited my comment. – Cilan Dec 23 '13 at 20:48

7 Answers7

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.

Way Spurr-Chen
  • 395
  • 1
  • 9
  • 2
    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). – Quentin Dec 23 '13 at 20:49
  • 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. – Way Spurr-Chen Dec 23 '13 at 20:51
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"
}
aksu
  • 5,035
  • 5
  • 21
  • 38
  • 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. – Quentin Dec 23 '13 at 20:43
  • @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? – Cilan Dec 23 '13 at 20:45
  • @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. – Quentin Dec 23 '13 at 20:46
  • 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 Dec 23 '13 at 20:47
  • @Quentin Small fix: `document.getElementById("Left").style.width = String(int(document.getElementById("Left").style.width.replace('px', '')) + 240) + 'px';` – Cilan Dec 23 '13 at 20:47
  • @ManofSnow — `ReferenceError: int is not defined`, plus all the assumptions previously mentioned that the value is already defined using inline style and pixels. – Quentin Dec 23 '13 at 20:48
  • @ManofSnow FYI, parseInt() is faster and shorter than replace() in this case: http://jsperf.com/parseint-vs-replace – John Kurlak Dec 23 '13 at 20:48
  • Tossed you an upvote b/c this no longer deserved `-1`, but hope you don't mind a quick critique of this function. You probably should extract `document.getElementById("Left")` into its own variable (to keep it DRY and improve performance). Also, its generally accepted that in JavaScript you should always put your opening braces (`{`) on the same line, rather than a new one, because there are a few cases where JS's automatic semi-colon insertion will bite you in the ass. That said, [it's not the biggest deal, and there is definitely some disagreement](http://stackoverflow.com/a/3218860/363701) – Zach Lysobey Dec 26 '13 at 15:29
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.

John S
  • 20,117
  • 7
  • 39
  • 52
  • FYI, this can be shortened to `$('#Left').width("+=240");` - a neat and undocumented(?) shorthand! – Zach Lysobey Dec 23 '13 at 22:08
  • @ZachL - I had to [**see it**](http://jsfiddle.net/uFG8W/1/) to believe it. It's not explicitly stated in the [jquery documentation](http://api.jquery.com/width/), 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. – John S Dec 23 '13 at 22:49
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");
}
Zach Lysobey
  • 12,910
  • 19
  • 85
  • 140
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
Afzaal Ahmad Zeeshan
  • 14,868
  • 10
  • 50
  • 94
  • Assuming that the existing value is a pixel length already, this will give you a value like `"240px240px"` which isn't valid. – Quentin Dec 23 '13 at 20:49
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

Ranjit Singh
  • 3,597
  • 1
  • 18
  • 35
-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.

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
  • The initial width is 240px. Would that change anything you just told me? – user3130697 Dec 24 '13 at 03:18
  • 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. – Quentin Dec 24 '13 at 08:43