use a javascript variable in inline CSS - javascript

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?

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.

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/

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

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.

I'm using React, and this syntax worked for me:
<div id="theDiv" style={`width: ${aJavascriptVariable} %`}>TESING'</div>

Related

Hiding elements via JavaScript/CSS

Some interesting JavaScript I hadn't seen before:
var html = $( 'html' );
  if( html.className !== '' )
    html.className = '';
I’m not sure how it works, but it seems like that assignment has the effect of changing the CSS display value of every element on the page which has the className selector from block to none.
Is anybody familiar with this behavior? Am I seeing it right?
EDIT:
OK, in response to those who say it's not valid jQuery, you're right. It's a shorthand way of describing the HTML element that was passed in by another function. And I didn't write it, just trying to understand it. It works, I want to know why.
This is actually a jQuery to select the html node and change the value of css class to it.
lets says you want to change the padding of the html document using a click event.
your onclick event would call that function to assign the css class with the desired padding.

jQuery hide(), show() or html()

I have a
<div id="content">
</div>
and three js variables that store different html: content1, content2 and content3.
By user interactions, the content of mentioned above div changes to one of that that stored in js variables.
What is preferable either to directly set div content to what I need by user interaction:
$("#content").html(content2);
or to change div structure to:
<div id="content">
<div id="c1">
// value of content1 variable here
</div>
<div id="c2">
// value of content2 variable here
</div>
<div id="c3">
// value of content3 variable here
</div>
</div>
And doing hide() and show() to that inner blocks, i.e when I want content2 to be shown:
$("#c1").hide();
$("#c2").show();
$("#c3").hide();
?
I'd say hiding & showing divs.
It's less intensive, and if the content inside the javascript variables happens to contain elements that you'll bind to, you won't have to rebind everytime you refresh the content, and if you wanted to have some sort of animation between the different content, multiple divs also allows that.
As a side note, using jQuery it's less code to do something like
$("#c2").show().siblings().hide();
The two aren't really all-that comparable since they do different things. They may well give a similar perception but what's happening isn't the same in terms of markup. In fact, it's not uncommon to see .html('Something').show() chained together.
Passing a string to .html() replaces the content of the selected element, it does nothing to affect the element itself.
Calling .show() or .hide() only affects the element itself - all the descendants remain exactly the same, they just can't be seen because their parent is not being displayed.
By using .html() you are replacing everything inside your element. All references to these descending elements will become undefined and direct (non-delegated) event listeners will also be lost.
.hide() and .show() do exactly what they say. The data inside your element is still preserved, the event handlers still in place, it's all just 'hidden' by way of display: none.
If the content dynamically changes, without page-load, use .html(), if not, .show() and .hide() are more appropriate.
For the ease of use and shorter more cleaner looking code, setting the content through HTML is the right option!
Think of it as what you're trying to do, 1 DIV => Can contain 3 different contents, you can manipulate it through JS.
So, in your first solution, you actually have one div and manipulating it through JS:
$("#content").html(content1);
$("#content").html(content2);
$("#content").html(content3);
Whereas, in the second solution, you are actually using 4 divs for the same functionality! So definitely, if you can do something with 1 div. That's the preferred way.
They both are taking equal lines for JS, but with the second approach, your HTML will contain a lot more code considering your contents are large.
I think that the best solution is to store the different contents into three variables and then assign to the div the choosen one with
$("#content").html(content2);
In this way you have three less nodes on your DOM tree
There isn't that much difference between the two options. One factor that might affect this is the actual size of the content you are changing. If the content is relatively small then it really doesn't matter which way you choose.
Another thing to consider is how available the three versions of the content variable is. If you have to fetch this HTML content each time you load it then it might make sense to pre-populate the content before you display it to your users so as to save the time it takes to load it. Then just show/hide the appropriate content.

how to change the value of <span lang> in javascript?

i have an element in html as shown below.
<tr><td class="HELPTEXT"><span lang="HLPMTXT1" id="HLPMTXT1"></span></td></tr>
i want to change the value of lang according to particular condition.
I tried as given below.but its not working.
<script>
document.getElementById("HLPMTXT1").lang ="HLPMTXT2"
</script>
Could anyone help me for changing the value of lang attribute of span?
You should use setAttribute(name, value) to do that, so your code would look like:
document.getElementById("HLPMTXT1").setAttribute("lang", "HLPMTXT2");
You can also use getAttribute(name) to retrieve the value using JavaScript.
https://developer.mozilla.org/en/DOM/element.setAttribute
https://developer.mozilla.org/en/DOM/element.getAttribute
Edit: It's also possible that your script is not working because you're trying to access the element before it exists in the DOM. Best way to insure that your element exists is by either: a) putting your script tag after the element, b) using the unload event to delay execution of your JS until everything is loaded, or c) use the DOMContentLoaded event. The latter, however, is a bit tricky to get to work cross-browser (without reusing somebody else's code that already addresses those problems) so you might want to read up on it first.
document.getElementById('HLPMTXT1').setAttribute('lang', 'HLPMTXT2');
Not all attributes can be accessed through the object properties

Custom JavaScript as DOM node attribute to perform when it's ready

Can I add a custom JavaScript as some DOM node attribute to perform when it's ready like JavaScript added as "onClick" attribute performed when you click on it?
Suppose i need to process a div element with some funcMyTransform function.
I think it'll be more elegant to write smth like this
<div onReady=funcMyTransform(this)>...</div>
Instead of
<div id="MyElement">...</div>
<script type="text/javascript">
$(document).ready(function(){$("#MyElement").funcMyTransform()});
</script>
Is there such "onReady" attribute or something?
There is no onReady event. Depending on the functionality, you may want to abstract funcMyTransform out to a jQuery plugin. E.g.
jQuery.fn.funcMyTransform = function() {
alert(this.id);
};
jQuery(document).ready(function(){
jQuery("#MyElement").funcMyTransform(); // Alerts => "MyElement"
});
If you want access to the element as soon as its "ready", then placing your script at the bottom the document (before </body>) would probably be a better idea, and is definitely faster (albeit slightly) to initiate than jQuery's pseudo "ready" event.
As others have said, onWhatever attributes are "like so 1999" ;-). The general consensus among the modern Javascript community is that you should avoid using them as much as possible (for maintainability and other reasons).
That being said, there is a way to get something very similar to what you want in a much more maintainable fashion:
<div class="onReadyDoMyTransform">...</div>
<script type="text/javascript">
$(function(){$(".onReadyDoMyTransform").funcMyTransform()});
// $(someFunction) == $(document).ready(someFunction);
</script>
This approach will give you all the benefits of being able to decide what "transforms onReady" in your HTML layer, but without all the failings of an "onReady" attribute. The script part can just go in to a common JS include that you use throughout your site, so you don't have to worry about adding it along with every DIV.onReadyDoMyTransform.
Have you tried the jQuery ready?
$("#MyElement").ready(function(){$(this).funcMyTransform()});
I'm guessing this won't work but worth a shot?
Your suggestion that mixing code with the HTML as ... more elegant is arguable.
<div onReady=funcMyTransform(this)>...</div>
In general this is discouraged as it leads to maintenance problems. If I understood you correctly, on the onReady event being activated you want to call all these functions. One way to do it actually is to use a REL or anything else you might want to use as an expando attribute.
On document ready capture all the elements and read the attribute's value, then eval(). (People will tell you eval() is evil, but is quite harmless here).
$(document).ready(function(){
var v= $('.class_name').attr('rel');
eval(v);
})
It will actually eval() and activate all your javascript within your REL attributes.
I have used er (element-ready) by Stuart Colville before that is somewhat similar to what you are talking about, except for it's not an element attribute.
http://muffinresearch.co.uk/archives/2006/04/12/element-ready/
I have used this in an instance where I was returning some html via an XHR request and I wanted it to execute some javascript, but the dom had to be finished loading before I could execute it. Of course document ready didn't work, since the main document was already loaded.

How to implement unobtrusive javascript with dynamic content generation?

I write a lot of dynamically generated content (developing under PHP) and I use jQuery to add extra flexibility and functionality to my projects.
Thing is that it's rather hard to add JavaScript in an unobtrusive manner. Here's an example:
You have to generate a random number of div elements each with different functionality triggered onClick. I can use the onclick attribute on my div elements to call a JS function with a parameter but that is just a bad solution. Also I could generate some jQuery code along with each div in my PHP for loop, but then again this won't be entirely unobtrusive.
So what's the solution in situations like this?
You need to add something to the divs that defines what type of behaviour they have, then use jQuery to select those divs and add the behaviour. One option is to use the class attribute, although arguably this should be used for presentation rather than behaviour. An alternative would be the rel attribute, but I usually find that you also want to specify different CSS for each behaviour, so class is probably ok in this instance.
So for instance, lets assume you want odd and even behaviour:
<div class="odd">...</div>
<div class="even">...</div>
<div class="odd">...</div>
<div class="even">...</div>
Then in jQuery:
$(document).load(function() {
$('.odd').click(function(el) {
// do stuff
});
$('.even').click(function(el) {
// dostuff
});
});
jQuery has a very powerful selector engine that can find based on any CSS based selector, and also support some XPath and its own selectors. Get to know them! http://docs.jquery.com/Selectors
I would recommend that you use this thing called "Event delegation". This is how it works.
So, if you want to update an area, say a div, and you want to handle events unobtrusively, you attach an event handler to the div itself. Use any framework you prefer to do this. The event attachment can happen at any time, regardless of if you've updated the div or not.
The event handler attached to this div will receive the event object as one of it's arguments. Using this event object, you can then figure which element triggered the event. You could update the div any number of times: events generated by the children of the div will bubble up to the div where you can catch and handle them.
This also turns out to be a huge performance optimization if you are thinking about attaching multiple handlers to many elements inside the div.
I would recommend disregarding the W3C standards and writing out HTML-properties on the elements that need handlers attached to them:
Note: this will not break the rendering of the page!
<ul>
<li handler="doAlertOne"></li>
<li handler="doAlertTwo"></li>
<li handler="doAlertThree"></li>
</ul>
Declare a few functions:
function doAlertOne() { }
function doAlertTwo() { }
function doAlertThree() { }
And then using jQuery like so:
$("ul li").each(function ()
{
switch($(this).attr("handler"))
{
case "doAlertOne":
doAlertOne();
break;
case ... etc.
}
});
Be pragmatic.
It's a bit hard to tell from your question, but perhaps you can use different jQuery selectors to set up different click behaviours? For example, say you have the following:
<div class="section-1">
<div></div>
</div>
<div class="section-2">
<div></div>
</div>
Perhaps you could do the following in jQuery:
$('.section-1 div').onclick(...one set of functionality...);
$('.section-2 div').onclick(...another set of functionality...);
Basically, decide based on context what needs to happen. You could also select all of the divs and test for some parent or child element to determine what functionality they get.
I'd have to know more about the specifics of your situation to give more focused advice, but maybe this will get you started.
I haven't don't really know about JQuery, but I do know that the DOJO toolkit does make highly unobtrusive Javascript possible.
Take a look at the example here: http://dojocampus.org/explorer/#Dojo_Query_Adding%20Events
The demo dynamically adds events to a purely html table based on classes.
Another example is the behaviour features, described here:http://dojocampus.org/content/2008/03/26/cleaning-your-markup-with-dojobehavior/

Categories

Resources