Site hosted by Angelfire.com: Build your free website today!
 
MyersDaily Directories
Message Board | Lycos | JavaScripts.com
Your Pages | What's Up | Contents | Bottom of Page
[Home][Archive]

Copy-and-Paste XHTML JavaScript Functions



// Script starts here.

function fixcase(a1) { return ('' + a1).toLowerCase(); }

function encode(a1) {
a1 = ('' + a1).replace(/&/g,'&');
a1 = a1.replace(/</g,'&lt;');
a1 = a1.replace(/>/g,'&gt;');
return a1.replace(/"/g,'&quot;');
}

function stack(a1,a2) {
for (var k in a2) { if (!a1[k]) a1[k] = a2[k]; }
return a1;
}

function tag(a1,a2,a3) {
a1 = '<' + fixcase(a1);
for (var k in a2) a1 += ' ' + ((a2[k] != null && k + '="' + encode(a2[k]) + '"') || k);
return a1 + ((!a3) ? ' /' : '') + '>';
}

function newtag(a1,a2,a3) {
return function(A1) { return tag(a1,(a2 && stack(a2,A1)) || A1,a3); }
}

function tagpair(a1,a2,a3) {
return tag(a1,a3,true) + (a2 || '') + '</' + fixcase(a1) + '>';
}

function newtagpair(a1,a2) {
return function(A1,A2) { return tagpair(a1,A1,a2 && (A2 && stack(a2,A2)) || a2); }
}

var html = { encode:encode,tag:tag,newtag:newtag,tagpair:tagpair,newtagpair:newtagpair };


/*                     Explanation of XHTML Script and Functions


  In tune with the extensible future of HTML development, I managed to get myself thinking
about making some extensible JavaScript routines, and created these cool functions which
create correctly the sort of strict syntax HTML tags needed for XHTML. The pure efficiency
of this script is mind-boggling -- only 896 characters/bytes used to create such power.
The writing of the explanation is more time-consuming and uses more space than the entire
script itself!

  Recently, soon after I developed these functions, I decided to communicate to others these
functions' amazing capability to manipulate HTML tags according to the newly formed XHTML
specifications. The sheer practical capability of these functions demonstrates a crucial
part of good programming. You will probably never tap the full extent the functions'
capabilities due to interface bottlenecks and raw time limitations. However, I believe a
partial explanation of these tremendous tools is in order.


  The list of new XHTML functions is here:

1. encode
2. tag
3. tagpair
4. newtag
5. newtagpair


  A stand-alone stack() function is used to merge two objects together into one.

e.g. stack( { color:'blue', 'class':'main' }, { color:'red', 'class':null } )

returns

{ color:'red', 'class':'main' }


  You notice that any defined properties within the second argument override the same
properties defined within the first argument. Also note the quotes used around class in
order to prevent a clash with a predefined JavaScript keyword.


  Also a simple fixcase() function is used to convert tag names to lowercase letters.

e.g.  fixcase('HTML') equals html


  All the five XHTML functions are accessible in two ways. Directly, through a procedural
interface, or by using an alternative object-oriented method.

The direct format is used as follows

function_name(arguments...)

while the object protocol is used in combination with the html object.

html.function_name(arguments...)


  The examples shown below are all valid JavaScript illustrations showing examples of
correct function use. This script works either in Netscape or Microsoft Internet Explorer
versions 4 or better on all platforms. This script supports over 93.7% of Internet users.


  We will start with an explanation of the encode() function. A simple function, it does
nothing other than the important conversion of characters with HTML meaning i.e. (&,<,>,")
into their safe entity equivalents to avoid possible clashes with the output HTML tags.

html.encode('<tag & hello means "danger" says I.>')

equals

&lt;tag &amp; hello means &quot;danger&quot; says I.&gt;



  The tag() and tagpair() functions produce XHTML tags. The attributes given to the tags
are entered using object-literal syntax.

e.g. { attribute:value, attribute2:value2, etc... }

  Any attributes specified have their values encoded automatically to prevent clashes with
the HTML around them. To specify a bareword tag attribute use a null value for this field.

e.g. { nowrap:null }

Then the nowrap attribute (or another attribute) will not be specified as

nowrap="something"

but instead as a bareword.

  Also, according to the new XHTML standards, the tag name as well as all attribute names
should be in lower case e.g. onmouseover rather than onMouseOver. However, to ensure total
compatibility, attribute names are not automatically converted to lower case although the
tag names themselves are. A single unmated tag now should contain a trailing space and
forward slash i.e. " /" to specify that it is an unpaired tag.

  It is important to understand that these functions have a return value rather than
creating output by a document.write() or document.writeln() method. In other words, these
functions' result is a new value -- just as the new Date() function returns a date object
containing information on the current date. For most purposes these functions would be used
to create HTML dynamically within HTML pages. An example is give below.


document.write
(
html.tagpair('h1','Welcome to my Webpage!')
);

i.e. <h1>Welcome to my Webpage!</h1>



  The tag() function is the multi-purpose single tag constructor function. It uses a
minimum of one, and at most three arguments. The first argument specifies the tag name
e.g. 'html' for a beginning HTML tag <html>. The second defines which attributes and
properties are contained within the tag, and is sent to the function as an object.

e.g. { color:'#ccccff', face:'Verdana', 'id':'p31' }

  Note again that any attribute names which have meaning in JavaScript, numeric floats,
or names containing characters illegal in a variable name (e.g. id, 24, or *) need to be
quoted in an object literal just as the id attribute was in the above example.

  Finally, the last argument, when set to true, tells the function to return its tag as
an unpaired beginning tag element. Remember to always include a matching ending tag
sometime after any XHTML tag not explicitly specified as a stand-alone tag.


Examples:


html.tag('p')

constructs

<p />


html.tag('input', { type:'hidden', name:'cart-id', value:'< #"j6afh95q0" >' } )

constructs

<input type="hidden" name="cart-id" value="&lt; #&quot;j6afh95q0&quot; &gt;" />


html.tag('FORM',

        {
          method:'post',
          action:'/cgi-bin/dir/script.cgi',
          onsubmit:'return checkForm(this);'
        },
          true
        )

constructs

<form method="post" action="/cgi-bin/dir/script.cgi" onsubmit="return checkForm(this);">



  The tagpair() function is the multi-purpose tag pair constructor function. It uses a
minimum of one argument, and at most three. The first argument specifies the tag name.
The second defines the content in between the beginning and ending tags. The third
argument specifies the attributes contained within the starting tag. This is also sent
to the function as an object just as in the tag() function.


Examples:


html.tagpair('p')

constructs

<p></p>


html.tagpair('blockquote','Hi There.')

constructs

<blockquote>Hi There.</blockquote>


html.tagpair(
            'td',
             encode('"Hello, Mr." said Bill.'),
          { 'class':'redfont', align:'center', nowrap:null }
            )

 constructs

<td class="redfont" align="center" nowrap>&quot;Hello, Mr.&quot; said Bill.</td>

  Note the use of encode() to encode the table data cell's content.



  What really gets cool, however, are the newtag() and newtagpair() functions. These let
you create new tag functions with predefined attributes, etc. to use later on. With only
the tag() and tagpair() functions you could create some really cool stuff, and even use
their output more than once by saving it in a variable and using the variable several
times. Now, with the newtag() and newtagpair() functions, this process is taken worlds
further. These functions return an entirely new function with all the given tag attributes
predefined. The returned functions also take new arguments for more flexibililty, and this
allows simplified creation of complicated HTML tags.

  Note that a function created with predefined attributes has special behavior. You will be
able to add and change tag attributes, but not delete them. In other words, the attributes
are "sticky" i.e. they apply themselves automatically in the future.

  The newtag() function uses three arguments. The first is to set the desired tag type,
the second is to set attributes, and the third, if set to true, tells the new function to
return its tags as unpaired beginning tag elements. The second and third arguments are
optional.

  The function returned by newtag() has one optional argument specifying new attributes.
Note that new attributes will overwrite old ones of the same name unless the new attribute
has a useless value. The tag type cannot be changed.

  The newtagpair() function uses two arguments. The first is to set the desired tag type,
and the second to set tag attributes. The second argument is optional.

  The function returned by newtagpair() has two optional arguments. The first argument
specifies content to be inserted between the returned tag pair, and the second is used to
specify additional tag attributes. Otherwise, it is similar to the newtag() function.


Examples:


E.1 Creating the variable textbox() as a new function able to output HTML as shown.

var textbox = html.newtag('input',{ type:'text', 'class':'textbox' })


textbox()

constructs

<input type="text" class="textbox" />


textbox( { name:'first_name',value:'Tom' } )

constructs

<input type="text" class="textbox" name="first_name" value="Tom" />


E.2 Creating the variable bluefont() as a new function able to output HTML as shown.

var bluefont = html.newtagpair('font',{ 'class':'soft', color:'#ccccff' });


bluefont()

constructs

<font class="soft" color="#ccccff"></font>


bluefont('Blue Tulips')

constructs

<font class="soft" color="#ccccff">Blue Tulips</font>


bluefont( 'Blue Roses', { size:'+1'} )

constructs

<font class="soft" color="#ccccff" size="+1">Blue Roses</font>


bluefont('Gasoline for Sale')

constructs

<font class="soft" color="#ccccff" size="+1">Gasoline for Sale</font>


html.tagpair('td',
              bluefont( 'Blue Violets', { size:4 } ),
             { colspan:2 }
            )

constructs

<td colspan="2"><font class="soft" color="#ccccff" size="4">Blue Violets</font></td>

*/



/*

  Additional notes

June 3, 2000

  Due to a strange problem caused by the sticky local variables in block-lexical
functions, the need for a new stack() function was realized. The reason for this is
because any non-default attributes used by a function created by the newtag() or
newtagpair() methods become overriding defaults. This behavior is incorrect according to
the function specifications, although the the original stack() function does behave
properly (as described) in combining objects when used alone.

  Either one of the functions below solves this problem at the expense of letting the
original defaults be overridden. They are both more limited in purpose -- designed to be
used by the newtag() or newtagpair() functions. The second function also lets properties
be deleted by setting them to the number 0. The === operator has no type conversion so to
have a value of '0', set the value to a string to avoid deleting the property.

  Both functions utilize the aberrant "sticky attribute" behavior, rather than being
impeded by it.

function stack(a1,a2) {
for (var k in a2) { if (a2[k] || a2[k] == '') a1[k] = a2[k]; }
return a1;
}

function stack(a1,a2) {
var o1 = a1;
for (var k in a2) {
if (a2[k]) o1[k] = a2[k];
if (a2[k] === 0) delete(o1[k]);
}
return o1;
}

*/ /* Questions or Comments? Email them to the author: "Joseph K. Myers" <e_mayilme@hotmail.com>. Include all pertinent information. A response is not guaranteed. Free use for any non-restricted type website is granted. Do not remove this comment section. Script Author: Joseph K. Myers <e_mayilme@hotmail.com> Script Source: MyersDaily <https://www.angelfire.com/yt/jmyers/> # |- Script Specifications -| # # language: javascript1.2 Version: 1.1.0 Release Date: May 13, 2000 */ // End of script.
 
Enter keywords...  
Amazon.com logo Featured! | Send to a friend!
Home | Top | Feedback | Site Index | Best Photo
“MyersDaily” created by Joseph K. Myers 1999-2000. Free hosting by Angelfire!!
Note: This site's URL is: https://www.angelfire.com/yt/jmyers   Site Updated On: October 6, 2000
Terms-of-Service