2

I want to do the following:

<div id="theDiv" style="width: aJavascriptVariableOrFunctionCallToGetValue">TESING</div>

I don't want to use, elsewhere in the code,

document.getElementById('theDiv').style.width = someValue;

I actually want that div, when it first appears, to have a width set, inline, by either a JavaScript variable or by way of a call to a JavaScript function.

How can I do this?

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
CFHcoder
  • 429
  • 2
  • 8
  • 25
  • Why do you want to do this? Perhaps you are looking for a templating engine http://handlebarsjs.com/ – Steve Jan 22 '14 at 17:50
  • _"I don't want to use, elsewhere in the code,"_ Why not? – j08691 Jan 22 '14 at 17:51
  • 1
    I am afraid you cannot do that without that JS statement you don't want to use. – Erlik Jan 22 '14 at 17:51
  • 1
    You can generate the html with JavaScript, this way you can use your JS variables when you are making a new element... – Daew Jan 22 '14 at 17:54
  • If you need the style applied immediately, you can embed a script immediately following your HTML markup and then you won't have the flash of unstyled content I'm guessing you want to avoid. – Harvey A. Ramer Jan 22 '14 at 17:56
  • @HarveyA.Ramer -- I'm going to try that. FOUC is indeed what we're trying to avoid. – CFHcoder Jan 22 '14 at 18:11
  • @CFHcoder then I'd recommend that you update your question, as there are ways to avoid FOUC, like dynamic css. – Christophe Jan 22 '14 at 18:39

5 Answers5

3

This is impossible to do the way you see this.

Every time the variable changes, you need to update the style of that particular object:

var theDiv = document.getElementById("theDiv");
document.getElementById('theDiv').style.width = someValue;

I really don't understand what you mean that when it first appears you want it's width to be set to certain width - why do you want to do that inline? Why can't you just set the width in your Javascript? What's preventing you from doing that? Especially if you want to do it just once and don't want to change it dynamically.

If you want to link the width of the div to a variable, look at frameworks like Backbone or EmberJS. You can then define a renderer that changes the width when the variable changes.

MMM
  • 7,221
  • 2
  • 24
  • 42
  • http://stackoverflow.com/questions/588040/window-onload-vs-document-onload and yes – digitalextremist Jan 22 '14 at 17:56
  • It's my experience that FOUC can occur and one way to avoid that is to have the html complete when the page is rendered. When the page loads, I want that div to have the width of the window.innerWidth value. And I cannot use "100vw", ie "100% of the viewport", as in **style="width: 100vw"** because I've found the "vw" notation is not supported consistently. – CFHcoder Jan 22 '14 at 17:59
  • @CFHcoder: This should normally be possible by simply using CSS, but if you really want to do it in Javascript, simply run your code [when the DOM content has loaded](https://developer.mozilla.org/en-US/docs/Web/Reference/Events/DOMContentLoaded) or when everything is ready. – MMM Jan 22 '14 at 18:03
  • If your server is slow -- the onload in the body, which I admit can be used to set that width -- the onload in the body tag, when set to call a javascript function -- on a slow server you can see the div before the onload handling. I want the page to appear **quickly**, I don't want to use **display: none**, then set the width, then set **display: block**. I want the page to appear fast, with zero penalty that can come with a slow server, on the correct rendering of the UI that uses 'onload' handling in a Javascript function to correctly format it. – CFHcoder Jan 22 '14 at 18:04
  • 1
    This is how things work @CFHcoder, you can't skip the loading process, you shouldn't be working with a DOM that's not fully loaded! – MMM Jan 22 '14 at 18:05
1

The only way to get JavaScript to run when an element first appears is with an onload event handler. And onload events only work on a few specific elements, like body, script or img.

Here is how you could make it work in your case, with a img tag:

<div id="theDiv">
TESING
<img style="display:none;" src="tinyImage.jpg" onload="this.parentNode.style.width='100px';"/>
</div>

Honestly, I don't see this as a good practice, and I would recommend to just be patient, and set the width later in a script.

Live demo: http://jsfiddle.net/HKW6b/

Christophe
  • 27,383
  • 28
  • 97
  • 140
0

You cannot do it like that. There are other ways to achieve what you want, though.

  • Server side processing, specially if the technology you use supports templating. You can manipulate the html value before sending it to the client;

  • jQuery may be something to consider. Simply fetch the element and use its API. Example:

$("#theDiv").width(aJavascriptVariableOrFunctionCallToGetValue);

This small piece of code does exactly what you want. It is not written inside the element itself, and it is about equivalent to the sample you provided, but again, it's something to consider should you have to do more complex operations on the DOM later on.

If you want to execute that piece of code only once, and after the page is ready, you can do it like this:

var div = $("#theDiv");
div.ready(function () {
    div.width(aJavascriptVariableOrFunctionCallToGetValue);
});
Geeky Guy
  • 9,229
  • 4
  • 42
  • 62
  • 1
    Why are you suggesting jQuery? – MMM Jan 22 '14 at 17:54
  • 1
    How is it "hell" to set the width of an element without jQuery? What are the cross-browser implications here? – MMM Jan 22 '14 at 17:55
  • Also `ready` is used when the DOM is fully loaded... Not when one div is ready (because you can't assign an event to it if it is not ready!) – MMM Jan 22 '14 at 17:58
  • @MMM you start writing code for things like this without jQuery or Angular, and then you do it again because come-on-it's-just-one-more-little-thing, and so and so... six months later, you regret not having made your work easier from start. Personal experience. – Geeky Guy Jan 22 '14 at 18:00
  • 2
    From personal experience you shouldn't be importing a whole library to do a simple task. – MMM Jan 22 '14 at 18:02
  • @Renan how is `$(elem).css("width", myWidth);` "_easier_" than `document.getEelementById(elem).style.width = myWidth`? – Jace Cotton Jan 22 '14 at 18:03
  • @JaceCotton it's more like `$("#id").width(x)` vs. `document.getEelementById("id").style.width = x`. – Geeky Guy Jan 22 '14 at 18:06
  • 1
    @Renan is it really _that_ big of a difference that you have to include a whole 32kb library? And even though the jQuery version to set a width has less bytes, native JavaScript is faster. Bear in mind the things the script has to go through in order to complete that task. `$` is a function which returns an `fn` prototype which returns an `init` prototype, which then passes through a separate `sizzle` library just to get a DOM node, then it has a property which injects _inline_ CSS onto the DOM. Whereas with pure javascript it's all native. – Jace Cotton Jan 22 '14 at 18:08
  • @JaceCotton if a 32kb download a few more milisseconds overload matter to you, you can keep using pure Javascript. Whether it's better or not to make code more readable is a matter of opinion, but I take the side of simpler, cleaner code. – Geeky Guy Jan 22 '14 at 18:13
0

The solution for this issue allowed me to set the proper width of the div immediately, asymptotically approaching inlined-javascript as possible, as per one of the comments above suggested:

"If you need the style applied immediately, you can embed a script immediately following your HTML markup and then you won't have the flash of unstyled content I'm guessing you want to avoid. – Harvey A. Ramer"

This solved the 'slow server' => FOUC problem. I added a 'script' tag immediately after the div tag to set the div to the window.innerWidth, problem solved.

From what I've seen, this approach is the earliest/soonest/fastest way to use javascript to set a CSS style attribute -- and it avoids having to code up an 'onload' handler.

The problem with 'onload' handlers being used to set UI style attributes on the page is -- the onload Javascript handler function can grow...and grow...and grow over time over the project's lifespan and you eventually are forced to clean out the onload handler. Best approach is to never use an onload handler that sets styles in the first place.

CFHcoder
  • 429
  • 2
  • 8
  • 25
0

I'm using React, and this syntax worked for me:

<div id="theDiv" style={`width: ${aJavascriptVariable} %`}>TESING'</div>