JavaScript and HTML Tricks

简介: Here are some of my favorite JavaScript and HTML tricks. There are a wide variety of options: from storing and using hidden data to making HTML forms and lists look great.
Here are some of my favorite JavaScript and HTML tricks. There are a wide variety of options: from storing and using hidden data to making HTML forms and lists look great. Each topic has a brief introduction showing you how it will improve your Web site. Then I'll go into each technique in detail.
  • Embedding data in hidden HTML elements and retrieving text lines in a platform-independent fashion
  • Randomizing data with JavaScript
  • Using a stylish form fieldset
  • Making clickable descriptions for checkboxes and radio buttons by using labels
  • Using CSS list-style-image to make beautiful bulleted lists

Introduction

The last time we discussed How to Use a JavaScript Query String Parser. Now we will discuss five more valuable JavaScript and HTML techniques and tricks.

Many times I've stored data in hidden HTML elements for scripts. It's a great way to keep prices and product names handy for e-commerce, or for lists of data that will be formatted by a script. To do that, it's necessary to interpret the lines of data in an operating-system independent way. I've even used this technique to store the radio programming information for a weekly radio schedule. Data stored this way can be graceful at degrading for older browsers. As an example, the radio schedule I mentioned was typed as preformatted text visible to older browsers, but transformed into a dynamically navigable Web page by JavaScript.

Another thing that comes up frequently is randomizing data that is used by a JavaScript program. Random links, images, statisics research and mathematical analysis come to mind as immediate applications.

My Web programming has never been the same since I learned how to use fieldsets to make beautiful forms in Web pages. Best of all, there's no bandwidth intensive imagery to use - it's built into the HTML!

While on the topic of forms, usability and efficiency increase in importance when check boxes and radio buttons are provided with clickable descriptions. Many people expect to click the descriptions, anyway, from experience with other programs. It would be sad to disappoint them, especially when HTML provides an excellent and natural way of doing it.

As a Grand Finale, you'll learn about one of the classic tricks of stylesheets. Using deluxe bullets for your lists will make your Web site more professional and appealing.

Getting Data From Text Lines in Hidden HTML Elements

Data for a script program can be embedded efficiently directly into the HTML source code, either in a hidden input field or a hidden HTML element. A script which reads this data has to perform a small number of steps.

  • Hide the data contents of the hidden field in the HTML document
  • Refer to the data using the document object model
  • Normalize the line breaks for cross-platform compatibility
  • Separate the lines into an array using a simple JavaScript function
  • Trim white space and remove empty lines or comments if desired
    1. <form>
    2.   <input type="hidden" id="domains" value="
    3.   0011.us
    4.   123abc.us
    5.   1mans.com
    6.   hesbest.com
    7.   9900.us
    8.   herclothing.info
    9.   findher.info
    10.   allme.us
    11.   dropoff.us
    12.   cyou.us
    13.   o-1.us
    14.   meadowlark.us
    15.   uuuuu.us
    16.   os-i.org
    17.   supergreat.us
    18.   nicewebsite.us
    19.   " />
    20. </form>
    21. <script type="text/javascript">
    22. function getLinesFromHidden(a) {
    23.   var e = document.getElementById(a);
    24.   if (!e)
    25.   return [];
    26.   var s = e.value;
    27.   s = s.replace(//r/n|/r/g, '/n');
    28.   return s.split('/n');
    29. }
    30. function trimWhiteSpace(a) {
    31.   var i;
    32.   for (i=0; i<a.length; i++)
    33.   a[i] = a[i].replace(/^/s+|/s+$/g, '');
    34.   return a;
    35. }
    36. function removeEmpty(a) {
    37.   var b = [], i;
    38.   for (i=0; i<a.length; i++)
    39.   if (a[i])
    40.   b[b.length] = a[i];
    41.   return b;
    42. }
    43. domainList = getLinesFromHidden('domains');
    44. domainList = removeEmpty(trimWhiteSpace(domainList));
    45. domainList.sort();
    46. d = document;
    47. function showList(a) {
    48.   d.write('<blockquote>', a.join('<br />'), '</blockquote>');
    49. }
    50. showList(domainList);
    51. </script>

The result is displayed below:

Result

Later, I'll write an article discussing some spreadsheet and statistics functions which can be applied to data embedded into an HTML document. At the end of every semester I prepare a quality of teaching report which uses these functions to compute statistics and correlations from classroom data. The first step is how to interpret text lines as comma separated values (CSV) or as data fields delimited in other ways.

Randomizing Data with JavaScript

Often I want to show data in random order. Somtimes I just want to pick a few random things out of many. Just as often I want to show all of the information, but in a randomized order, similar to shuffling a deck of cards. To do this we can use the JavaScript sorting algorithm in combination with a customized sorting comparison function that will randomize the sorted order.

The comparison function returns a value greater than zero or less than zero depending on which element should be sorted first. When the sorting algorithm is executed the data will be randomized if the comparison function gives each comparison of elements an equal probability of being greater than zero or less than zero.

  1. <script type="text/javascript">
  2. randomComparison = function(a, b) {
  3.   return Math.random()-.5;
  4. };
  5. domainList.sort(randomComparison);
  6. showList(domainList);
  7. </script>

Result

Some high-speed sorting algorithms are unstable, and might not result in all data being truly randomized. In a sense, one could say that the sorting algorithm divides up the data too fast for the randomizing to occur. A truly random shuffling has the property that each element has the same probability of being assigned to each location, or equivalently, each permutation of objects is equally likely. As far as I know, Safari is the only browser which may have an unstable sorting algorithm, resulting in the domain uuuuu.us being sorted to the last position most of the time, although other domains appear to be randomly placed. Unstable sorting algorithms may be fine, depending on the application.

There are also iterative methods for sorting. Iterative sorting methods are useful because the computational cost of one iteration is O(N) rather than O(n log N). A precise estimate is typically from N/2 to 2N. The data is not completely sorted after one iteration, but that's fine when the data ranking is based on subjective criteria such as clicking popularity or Google PageRank. Usually a good iterative sorting method guarantees that at least the lowest and highest ranked items are sorted to the correct positions.

Using a stylish form fieldset

One of the coolest form elements built into HTML is the fieldset. It relies on the browser to create a look that can't be replicated using ordinary HTML commands. It has the sophistication of images without the development effort, server load or extra client bandwidth.

A fieldset must be contained in a form. If you want to use one elsewhere, just surround it with form tags, provided that you're not interrupting another form, of course. One form can contain as many fieldsets as you wish.

  1. <form>
  2.   <fieldset>
  3.   <legend>Please enter your Yahoo! Login Information</legend>
  4.   <table>
  5.     <tr><th>User name</th>
  6.     <td><input type="text" name="name" /></td></tr>
  7.     <tr><th>Password</th>
  8.     <td><input type="password" name="password" /></td></tr>
  9.     <tr><th>Security</th>
  10.     <td colspan="2"><input type="radio" name="secure" value="home" id="secure_home" />
  11.     <label for="secure_home">Remember my user name and password on this computer</label><br />
  12.     <input type="radio" name="secure" value="group" id="secure_group" checked="checked" />
  13.     <label for="secure_group">Remember my user name only</label><br />
  14.     <input type="radio" name="secure" value="public" id="secure_public" />
  15.     <label for="secure_public">Do not remember my user name or password</label></td></tr>
  16.     <tr><th><input type="submit" value="Login to Yahoo!" /></th></tr>
  17.   </table>
  18.   </fieldset>
  19. </form>

Result

Please enter your Yahoo! Login Information
User name
Password
Security Remember my user name and password on this computer
Remember my user name only
Do not remember my user name or password

Using Labels to Create Checkboxes and Radio Buttons With Clickable Descriptions

You'll notice in the form above that one can click on the descriptions of the security options in order to choose the desired option. To do this, each radio button must be labeled with an HTML ID. The clickable description has an attribute for="HTML ID" which allows the browser to understand that the radio button should be selected when the user clicks the description.

This is a natural thing for people to do at your Web site. It's difficult to navigate a mouse to select a small checkbox or radio button in comparison to simply clicking the description. Clickable descriptions make Web designs more efficient, and the the user experience more satisfying and enjoyable. Yet it's surprising how many HTML developers don't write their forms this way.

Using List-Style-Image to Make Beautiful Bulleted Lists

In HTML, an unordered list (the ul and li elements) is one of the easiest ways to organize information. It looks like this.

  • Meat
  • Potatoes
  • Water

Lists like this are a best friend to anyone who wants to organize their Web page and make the best use of both white space and text. But did you know that through stylesheets there can be much more to a simple bulleted list?

One can spice up their lists by using any bullet of their choice, and a stylesheet which replaces the default black circular bullet with a nice-looking image. This is done by selecting the li elements contained in the unordered lists and specifing a URL corresponding to the list-style-image attribute.

The best thing about list-style-image is that stylesheets already provide this new design tool, making complicated graphic design work unnecessary.

Here's how it works:

  1. <style type="text/css">
  2. ul.orangearrow li {
  3.   list-style-image: url(http://0--0.us/0067_circular_arrow.png);
  4. }
  5. </style>
  6. <ul class="orangearrow">
  7.   <li>meat</li>
  8.   <li>potatoes</li>
  9.   <li>water</li>
  10. </ul>

Result

  • Meat
  • Potatoes
  • Water
目录
相关文章
|
5月前
|
移动开发 前端开发 JavaScript
征信报告修改器,征信报告生成器,制作软件无痕修改软件【js+html+css】
本项目为信用评分模拟器教学工具,采用HTML5实现,仅供学习参考。核心功能通过JavaScript构建,包含虚拟数据生成、权重分配及信用因素分析(如还款记录、信用使用率等)。
|
5月前
|
存储 自然语言处理 前端开发
抖音快手小红书虚拟评论截图生成器,模拟对话制作工具,html+js+css
这是一款纯前端实现的多平台虚拟评论生成器,支持抖音、快手、小红书风格,适用于产品演示与UI设计。采用Vanilla JS与Flexbox布局,利用IndexedDB存储数据,CSS Variables切换主题。
|
5月前
|
前端开发 JavaScript
个人征信电子版无痕修改, 个人信用报告pdf修改,js+html+css即可实现【仅供学习用途】
本代码展示了一个信用知识学习系统的前端实现,包含评分计算、因素分析和建议生成功能。所有数据均为模拟生成
|
4月前
|
开发框架 JavaScript 前端开发
精选HTML、JavaScript、ASP代码片段集锦
这些代码片段代表了HTML, JavaScript和ASP的基本应用,可被集成到更复杂的项目中。它们注重实用性,并且易于理解,旨在帮助开发者快速开始项目构建或进行学习。尽管ASP不如其他服务器端技术(如Node.js, PHP, Ruby等)现代,但它在遗留系统中仍非常普遍,了解基础仍具有价值。
169 14
|
5月前
|
存储 前端开发 安全
病历单生成器在线制作,病历单生成器app,HTML+CSS+JS恶搞工具
本项目为医疗病历模拟生成器,旨在为医学教学和软件开发测试提供数据支持,严格遵守《医疗机构病历管理规定》。
|
5月前
|
前端开发 容器
处方单图片生成器, 处方单在线制作免费,js+css+html恶搞神器
这是一个电子处方模拟生成系统,使用html2canvas库实现图片导出功能。系统生成的处方单包含多重防伪标识,并明确标注为模拟数据,仅供学习
|
5月前
|
前端开发
个人征信PDF无痕修改软件,个人征信模板可编辑,个人征信报告p图神器【js+html+css仅供学习用途】
这是一款信用知识学习系统,旨在帮助用户了解征信基本概念、信用评分计算原理及信用行为影响。系统通过模拟数据生成信用报告,涵盖还款记录
|
5月前
|
前端开发 JavaScript 容器
制作b超单生成器, 假怀孕b超单图片制作, p图医院证明【css+html+js装逼恶搞神器】
本资源提供一个适合用于熟人之间恶搞的工具,效果逼真,仅供学习参考与娱乐。包含前端技术学习要点:语义化布局、响应式设计、Flexbox、图片自适应
|
5月前
|
前端开发
医院检查单子p图软件,在线制作仿真病历,js+css+html装逼神器
本示例展示如何用HTML/CSS创建医疗信息页面,内容仅供学习参考。页面模拟“阳光医院体检中心”场景,提供预约功能验证(如姓名、手机号、日期)。所有数据仅用于演示