Tip: Three useful JavaScript functions
Posted on Saturday, August 2nd, 2008There are a certain number of stock JavaScript functions which I tend to use on most projects. Normally I’ll create a function if a task needs to be carried out quite a few times. So, here we have a newElement function, a style function and a toggleVisibility function. It’s pretty obvious what each of them do…
Create new elements
The newElement function is used to create new DOM elements - it does NOT inject these newly created elements into the DOM so you’ll have to do that yourself.
function newElement(elementName,text,attributes) { if(typeof elementName != "string" || typeof attributes != "object") return; var element = document.createElement(elementName); element.appendChild(document.createTextNode(text)); for( var i in attributes ) { element[i] = attributes[i]; } return element; }
It takes three arguments, an elementName (such as, "div", "a","input" etc.), an attributes object which is a little time-saving addition I made, and text (which will be appended within the newly created element.
So, if you wanted to create a new short paragraph with a class of "important", a title of "summary" and some text inside it then you could do this:
var myNewElement = newElement('p','some text inside',{className: 'important', title: 'summary'});
When adding attributes make sure that you use the proper reference. So, if you want to add a class you cannot use class:'important' - you have to use className:'important' instead.
Style your elements
The style function is really useful for adding a large amount of CSS styles to an element. Most of the time you should just add a class and have the corresponding CSS rules defined in your StyleSheet but for when that’s not possible, you can use this:
function style(elementReference,styles) { if(typeof elementReference != "object") return; if (typeof styles == "string") { styles = styles.split(';'); for (var i = 0; i < styles.length; ++i) { elementReference.style[styles[i].split(':')[0]] = styles[i].split(':')[1]; } } else if (typeof styles == "object") { if (styles[0]) { for (var i = 0; i < styles.length/2; ++i) { elementReference.style[styles[i]] = styles[++i]; } } else { for (var i in styles) { elementReference.style[i] = styles[i]; } } } }
This function takes two arguments, an elementReference and the styles object/string. So, there are three ways of using it:
This:
var elem = document.getElementById('elemID'); style(elem,['color','blue','padding','5px']);
Or: (this is my preferred way)
var elem = document.getElementById('elemID'); style(elem,{ color: 'blue', padding: '5px' });
Or:
var elem = document.getElementById('elemID'); style(elem,'color:blue;padding:5px;');
The style function has been especially useful to me in my GreaseMonkey scripts. On most projects I tend to just create a class within CSS and apply it to the element when I need it, - sometimes this won’t be possible, for example, if you don’t have access to the StyleSheet - in such situations this function becomes incredibly useful!
Toggle the visbility of an element
The toggleVisibility function is pretty basic, it just shows or hides elements dependent on their current state. - So if an element is hidden when you initiate the function then it will be shown and vice versa.
Here it is:
function toggleVisibility(elementReference) { var e = elementReference; if(!e || typeof e != "object") return; e.style.display = (e.style.display==='none') ? 'block' : 'none'; }
And this is how you use it:
var elem = document.getElementById('elemID'); elem.onclick = function() { var something = document.getElementById('something'); toggleVisibility(something); // so simple... }
All of the above functionality can be gained from utilising one of the many available JavaScript libraries but if you’re not planning to use a library because you find them unnecessary or bloated then the above functions might be of some use to you.
August 3rd, 2008 at 12:26 am
Your functions look handy, but they will fail in IE.
especially your newElement() one.
The first issue would be the bug with setting the name attribute in IE.
http://webbugtrack.blogspot.com/2007/10/bug-235-createelement-is-broken-in-ie.html
Followed by this one, which would make any attempt to make form fields other than text impossible.
http://webbugtrack.blogspot.com/2007/09/bug-237-type-is-readonly-attribute-in.html
Feel free to browse around. If you need help fixing your functions to work in IE, just give me a shout.
Cheers!
August 3rd, 2008 at 8:30 am
@Max - Thanks for the info… The functions themselves work perfectly (I’ve tested
) - Obviously the extent of the perfection is defined by how well you use them. Not all element attributes can be changed/added easily so you’ll have to take that into account when using the newElement() function.
All functions and shown examples have been tested successfully in Opera, Safari, IE6, IE7, FF3.
August 3rd, 2008 at 2:50 pm
James thanks for the correction, I missed that you didn’t add to the DOM before setting the attributes (as this would break things for sure)
It will still fail in IE8 due to a regression bug:
http://webbugtrack.blogspot.com/2008/04/bug-230-no-elementattributes-array-in.html
But otherwise it should work if you pass in the camelCase attribute names etc.
A few things might make these a bit more useful though.
I would wrap the textNode portion with:
This way you can pass null, if there is no inner text (e.g. all input elements, selects, etc.) Trying to append the text in IE will throw an error.
As for the setting of the styles, I’m not sure I understand the need to iterate over every item…
just set the style attribute in all browsers, or set the style.cssText attribute in IE… or if you want to merge with other styles…