Best html questions in June 2011

Do browsers send "\r\n" or "\n" or does it depend on the browser?

60 votes

This question has bothered me for a million years... whenever I create a website with a textarea that allows multi-line (such as a "Bio" for a user's profile) I always end up writing the following paranoid code:

// C# code sample...
bio = bio.Replace("\r\n", "\n").Replace("\r", "\n");
bio = Regex.Replace(@"\n{2,}", "\n\n");

So, what do browsers send up for a <textarea name="Bio"></textarea> if it has multiple lines?

The HTTP and MIME specs specify that header lines must end with \r\n, but they aren't clear (some would argue that it isn't clear if they are clear) about what to do with the contents of a TEXTAREA. (See, for instance, this thread from an HTML working group about the issue.)

Here's a quote from the HTTP/1.1 spec about message headers:

The line terminator for message-header fields is the sequence CRLF. However, we recommend that applications, when parsing such headers, recognize a single LF as a line terminator and ignore the leading CR.

I think that is a good strategy in general: be strict about what you produce but liberal in what you accept. You should assume that you will receive all sorts of line terminators. (Note that in addition to CRLF and LF, Mac OS-9 used CR alone, and there are still a few of those around. The Unicode standard (section 5.8) specifies a wide range of character sequences that should be recognized as line terminators; there's a list of them here.)

Should css class names like 'floatleft' that directly describe the attached style be avoided?

40 votes

Lots of websites use class names like floatleft, clearfloat, alignright, small, center etc that describe the style that is attached to the class. This seems to make sense so when writing new content you can easily wrap (for example) <div class="clearfloat">...</div> around your element to make it behave the way you want.

My question is, doesn't this style of naming classes go against the idea of separating content from presentation? Putting class="floatleft" on an element is clearly putting presentation information into the HTML document.

Should class names like this that directly describe the attached style be avoided, and if so what alternative is there?


To clarify, this isn't just a question of what to name classes. For example a semantically accurate document might look something like:

<div class="foo">Some info about foo</div>
...
<div class="bar">Info about unrelated topic bar</div>
...
<div class="foobar">Another unrelated topic</div>

Say all these divs need to clear floats, the css would look something like:

div.foo, div.bar, div.foobar {
    clear:both;
}

This starts to get ugly as the number of these clearing elements increases - whereas a single class="clearfloat" would serve the same purpose. Is it recommended to group elements based on the attached styles to avoid repetition in the CSS, even if this means presentational information creeps into the HTML?


Update: Thanks for all the answers. The general consensus seems to be to avoid these class names in favour of semantic names, or at least use them sparingly provided they don't hinder maintenance. I think the important thing is that changes in the layout should not require excessive changes to the markup (although a few people said minor changes are okay if it makes overall maintenance easier). Thanks to those who suggested other methods to keep CSS code smaller as well.

It's great until you re-design, and narrow is highlighted yellow, center converts better left-justified, and the image you called floatleft now belongs on the right.

I'll admit to the sin of using floatleft and clear as CSS class names, but it is much easier to maintain your CSS if you choose names that relate to the semantic meaning of the content, like feedback and heroimage.

Stacking Divs from Bottom to Top

24 votes

when appending divs to a div with a fixed height, the child divs will appear from top to bottom, sticking at the top border.

┌─────────────────────────┐
│ Child Div 1             │
│ Child Div 2             │
│                         │
│                         │
│                         │
└─────────────────────────┘

I'm now trying to display them from bottom to top like this (sticking to the bottom border):

┌─────────────────────────┐
│                         │
│                         │
│                         │
│ Child Div 1             │
│ Child Div 2             │
└─────────────────────────┘
┌─────────────────────────┐
│                         │
│                         │
│ Child Div 1             │
│ Child Div 2             │
│ Child Div 3             │
└─────────────────────────┘
┌───────────────────────┬─┐
│ Child Div 2           │▲│
│ Child Div 3           │ │
│ Child Div 4           │ │
│ Child Div 5           │█│
│ Child Div 6           │▼│
└───────────────────────┴─┘

And so on... I hope you get what I mean.

Is this simply doable with css (something like vertical-align: bottom?) or do I have to hack something together with javascript?

Thank you very much for your help. :)

All the answers miss the scrollbar point of your question. And it's a tough one. If you only need this to work for modern browsers and IE 7+ you can use table positioning, vertical-align:bottom and max-height.

Demo (vertical-align)

.wrapper { display:table-cell; vertical-align:bottom; height:200px;  }
.content { max-height:200px; overflow:auto;  }

html

<div class="wrapper">
  <div class="content">
     <div>row 1</div>
     <div>row 2</div>
     <div>row 3</div>  
  </div>
</div>  

Other than that, I think it's not possible with CSS only. You can make elements stick to the bottom of their container with position:absolute, but it'll take them out of the flow. As a result they won't stretch and make the container to be scrollable.

Demo (position-absolute)

.wrapper { position:relative; height:200px; }
.content { position:absolute; bottom:0; width:100%; }

Pixels vs. Points in HTML

17 votes

When creating an HTML page, should I specify things like margins with pixels or with points?

Is one of them considered to be better practice than the other? Any advantages or disadvantages to either one?

Use px or em

Points (pt): Points are traditionally used in print media (anything that is to be printed on paper, etc.). One point is equal to 1/72 of an inch. Points are much like pixels, in that they are fixed-size units and cannot scale in size.

Generally, 1em = 12pt = 16px = 100%.

[Conclusion]

The winner: percent (%).

  • JohnB note: this is for TEXT. Obviously you asked about "things like margins." (I assume you mean padding also.) For that, I would recommend px or em. Personally, I switch, depending on the particular situation.

MORE ARTICLES

Point values are only for print CSS!

(Comment further down)

Points are for print? Nope.

Points are not for print exclusively. Theoretically, points are for defining an absolute measure. Pixels are not absolute, since depending on your screen and chosen definition (not resolution), the resolution (pixels per inch) can go from a lot (150dpi) or very little (75dpi). Which means your pixels can be a size, or maybe half that size. Which means that text you design to be perfectly legible on your screen may look too big on your client’s screen (“please make the text smaller, ok?”) or too small to be readable on your neighbor’s screen (“hey, the website you told me about the other day? the one you said you had worked on… well i couldn’t read the text very well, it’s so small”).

Points are a solution to this issue. But browsers and operating systems need to manage those. Basically, it means:

browsers have to calculate the display size in pixels using the given value (say, 10pt) and the screen’s real resolution; operating systems have to communicate the real current resolution, and not a default value.

Also:

Is there any way to change the color of text "halfway" through a character on a webpage?

11 votes

One thing I've seen in some Desktop applications is the ability to change the color of text as the background changes -- to effectively have multiple colors on a single character. I've seen this most commonly with progress bars that display the percentage inside the bar. Generally a darker background color will be used as the progress bar color, and as it progresses, the dark color doesn't contrast enough with the dark text, so the text color changes as soon as the bar overlaps with the text. This image should explain what I mean:

Progress Bars

As you can see, the text is black when it's at 0% -- when there is no dark background. When the background image fully progresses to 100%, the text is completely white. But in the middle, as you can see at 50%, the text is half black/half white, and it's actually split on the "0" character in this example.

Is there any way to do this at all on a webpage? CSS, Images, Jquery, otherwise? (Preferably not Flash or a Java applet though -- I'm really wondering whether an HTML-based solution is possible.) Thanks!

I'll get you started:

  1. Create two equally sized "progress bars" (divs). Set their size to the full width they would be if they were at 100%.
  2. Set one bar to black text with a white background and the other to yellow text with a blue background, as per your example above.
  3. Set the yellow/blue bar in a parent div and increase the width of the parent on every percentage increase. Position the parent above the black/white bar.
  4. Also on every increase, update the labels of both progress bars to represent the percentage.

That will simulate the same effect without having to manually paint half a character. It will be difficult in CSS because you will have to position one over the other.

The benefit of doing it this way is that you can easily display half-painted characters. There is already a jQuery progress bar you can use, though.

Vim delete HTML tag, but not content

11 votes

I have in vim

<p>Hello stackoverflow!</p>

And I want to delete p tag in vim to end with:

Hello stackoverflow!

I know dit command to do opposite. But I can't find how to do this.

I'm using Janus.

With the surround.vim plugin, use dst (for delete surrounding tag). Same with ds(, ds" etc.

problem in file upload

11 votes

I have the following markup:

  <select multiple="multiple" id="targetFilesList"  style="width:200px;height:110px;">
   </select>
   <input type="button" value="Get" id="btnGet" />

and following javascript:

    $(function()
    {
        $('#btnGet').click(function()
        {
            var fileupload = $("<input type='file' name='filetoupload' style='visibility:hidden;'/>");
            $('body').append(fileupload);

            fileupload[0].onchange = function()
            {
                $('#targetFilesList').append('<option >' + fileupload.val() + '</option>');
                return false;
            }
            fileupload.click();
        });
    });

Scenario is that i have to upload multiple files and once user has chosen the file to be uploaded i have to show the file name to user.Then,on submitting the form i will upload all the files.For this,on clicking the get button i am adding a fileupload control dynamically and initialise onchange event of the fileupload control just added. The problem in chrome 12 on clicking get button fileupload control does not get opened but in firefox4 and ie8 it is working. Any idea why?

To get it working on Chrome 12, you can just add it into a window timeout of 0, like this:

window.setTimeout(function(){
   fileupload.click();   
},0);

Why exactly it behaves like this, I am not sure. The first time I encountered the problem I tried it with a longer interval, reducing it all the time to see how low you could get it, until I noticed it doesn't even need a delay. The obvious answer would be that it isn't actually ready in DOM by the time you trigger the click (element is there, but is the appropriate events for it?).

example: http://jsfiddle.net/HgEga/

why are end tags somtimes required and sometimes not?

10 votes

very basic question, but i haven't found an answer for it...

why do some html opening/start tags require a closing/end tag?

for example, <script> requires a </script>, while <img> can (in fact, must) be self-closing (<img src="path.jpg" />)?

i would assume it has to do with requiring content between start and end tags, but with the example of <script>, <script src="file.js"></script> doesn't need anything in between...

i ask because i burned a solid two hours trying to figure out why my included script was working in Safari but not in FF or Chrome. it was because i incorrectly self-closed the script tag. bleh.

The reason for the existence of self closing tags is that certain elements naturally will never have content that goes between the tags. For instance, think about the <br / tag. When would something like <br></br> be useful? It's really just a waste of character space and time. This syntax stems from the XML syntax and became part of XHTML.

Determining which tags can/should be self closing is up the HTML parser in the browser. The HTML specification for the version you're using should define the way things are handled, but of course we all know that it never necessarily the case.

Here is a great article about self closing tags in HTML5 (& past versions) for your reference.

http://tiffanybbrown.com/2011/03/23/html5-does-not-allow-self-closing-tags/

Generating sound on the fly with javascript/html5

10 votes

Is it possible to generate a constant sound stream with javascript/html? For example, to generate a perpetual sine wave, I would have a callback function, that would be called whenever the output buffer is about to become empty:

function getSampleAt(timestep)
{
    return Math.sin(timestep);
}

(The idea is to use this to make an interactive synth. I don't know in advance how long a key will be pressed, so I can't use a fixed length buffer)

Using the HTML5 audio element

Cross-browser generative sustained audio using JavaScript and the audio element isn't currently possible, as Steven Wittens notes in a blog post on creating a JavaScript synth:

"...there is no way to queue up chunks of synthesized audio for seamless playback".

Using the Web Audio API

The Web Audio API was designed to facilitate JavaScript audio synthesis. The Mozilla Developer Network has a Web Based Tone Generator that works in Firefox 4+ [demo 1]. Add these two lines to that code and you have a working synth with generative sustained audio upon keypress [demo 2 - works in Firefox 4 only, click the 'Results' area first, then press any key]:

window.onkeydown = start;  
window.onkeyup = stop;

The BBC's page on the Web Audio API is worth reviewing too. Unfortunately, support for the Web Audio API doesn't extend to other browsers yet.

Possible workarounds

To create a cross-browser synth at present, you'll likely have to fall back on prerecorded audio by:

  1. Using long prerecorded ogg/mp3 sample tones, embedding them in separate audio elements and starting and stopping them upon keypress.
  2. Embedding an swf file containing the audio elements and controlling playback via JavaScript. (This appears to be the method that the Google Les Paul Doodle employs.)

iPad Zoom Scale Detection

9 votes

I'm trying to find a way to detect how zoomed in someone is on a web app so that when they click to pull up a menu, the menu stays the same size regardless of the zoom. To do that, I need to be able to scale the size of the menu appropriately relative to the zoom. Is there a way to do this?

First, all UIWebView has as a UIScrollView subview. So, in order to get it you could do the following:

for (UIView * v in [_webView subviews]) {

    if ([v isKindOfClass:[UIScrollView class]]) {
        UIScrollView * s = (UIScrollView*)v;
        // use the scrollview
    }

}

After that you can use the UIScrollView to find out the zoom scale. Unfortunately, the property zoomScale doesn't tell us, in this case, what we want, but we can use the contentSize and the frame of the scrollView, as the following:

CGFloat zoomScale = s.contentSize.width / s.frame.size.width;

After that, I suppose you want to tell your javascript code about this zoomScale. You could use the following code:

[_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"yourJSZoomScaleVar = %f;", zoomScale]];

Hope it helps!

What technology is used at the Google homepage (guitarstrings)

9 votes

What technology is used at the Google homepage (9 June 2011)? They made something like a guitar pickup for the snares. When you move the mouse over it, the snares are being played.enter image description here

I know it is no flash, otherwise the add-on for Firefox would have blocked it.

Thanks.

They use a canvas

<canvas width="474" height="175"></canvas>

and flash

<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="0" height="0" id="guitar11-sound-player" type="application/x-shockwave-flash"><param name="movie" value="/logos/swf/guitar11.swf"><param name="allowScriptAccess" value="always"><object id="guitar11-sound-player-2" type="application/x-shockwave-flash" data="/logos/swf/guitar11.swf" width="0" height="0"><param name="allowScriptAccess" value="always"></object></object>

The flash is for the sound.

Here's the JavaScript:

(function() {
    var g = null,
        h;
    try {
        if (!google.doodle) google.doodle = {};
        var i, m, n, o, r, s, t, u, v, aa, w, ba, ca, da = navigator.userAgent.indexOf("MSIE") >= 0,
            ea = [[3, "#776a62", "#2063ff", 2, [[28, 23], [103, 23]]], [5, "#776a62", "#f61b33", 2, [[28, 38], [103, 38]]], [0, "#776a62", "#ffdd24", 2, [[65, 67], [318, 67]]], [2, "#776a62", "#07d238", 2, [[28, 81], [281, 81]]], [7, "#776a62", "#2063ff", 1, [[28, 96.5], [281, 96.5]]], [9, "#776a62", "#f61b33", 1, [[29, 111.5], [104, 111.5]]], [1, "#776a62", "#07d238", 2, [[358, 66], [433, 66]]], [4, "#776a62", "#2063ff", 2, [[358, 81], [433, 81]]], [6, "#776a62", "#f61b33", 2, [[330, 96], [405, 96]]], [8, "#776a62", "#ffdd24", 1, [[358, 111.5], [434, 111.5]]]],
            fa = 0,
            ga = 0,
            x = 0,
            y = 0,
            z = !0,
            A = [],
            B = g,
            C = g,
            D = function(a) {
                a && a.parentNode && a.parentNode.removeChild(a)
            },
            E = function(a, b, c) {
                if (a) {
                    if (!google.doodle.ba) google.doodle.ba = [];
                    google.doodle.ba.push(arguments);
                    var d = a,
                        e = b,
                        f = c;
                    d.addEventListener ? d.addEventListener(e, f, !1) : d.attachEvent("on" + e, f)
                }
            },
            ... // A lot more [link](http://jsfiddle.net/2R4Cg/)

They also have some CSS:

#hplogo:active,#hplogo:focus {
    outline:none;
}

#hplogo-g {
    background:url(logos/2011/guitar11-hp-sprite.png) no-repeat 0 0;
    height:175px;
    position:relative;
    width:474px;
}

#hplogo-click {
    background:url(logos/2011/guitar11-hp-sprite.png) no-repeat -2000px -2000px;
    cursor:pointer;
    height:130px;
    left:0;
    position:absolute;
    top:0;
    width:474px;
}

#hplogo-lcd {
    height:30px;
    left:70px;
    position:absolute;
    top:129px;
    width:200px;
}

#hplogo-lcd-icon {
    background:url(logos/2011/guitar11-hp-sprite.png) no-repeat -580px -162px;
    cursor:pointer;
    height:0;
    position:absolute;
    width:0;
}

#hplogo-lcd-text {
    background:transparent;
    border:0 none;
    color:#666;
    cursor:text;
    font-family:VT323,arial,sans-serif;
    font-size:14px;
    left:77px;
    position:absolute;
    top:134px;
    text-decoration:none;
    width:182px;
}

#hplogo-lcd-screen {
    background:url(logos/2011/guitar11-hp-sprite.png) no-repeat -2000px -2000px;
    height:20px;
    left:52px;
    position:absolute;
    top:134px;
    width:214px;
}

#hplogo-on {
    background:url(logos/2011/guitar11-hp-sprite.png) no-repeat -809px -39px;
    height:37px;
    left:272px;
    position:absolute;
    top:123px;
    width:62px;
}

#hplogo-led {
    background:url(logos/2011/guitar11-hp-sprite.png) no-repeat -2000px -2000px;
    height:21px;
    left:292px;
    position:absolute;
    top:133px;
    width:21px;
}

.hplogo-str {
    background:url(logos/2011/guitar11-hp-sprite.png) no-repeat -530px -60px;
    height:20px;
    position:absolute;
    width:255px;
}

#hplogot {
    -webkit-box-shadow:5px 5px 10px #ddd;
    -moz-box-shadow:5px 5px 10px #ddd;
    box-shadow:5px 5px 10px #ddd;
    -webkit-transition:opacity .5s ease-out;
    -moz-transition:opacity .5s ease-out;
    -o-transition:opacity .5s ease-out;
    transition:opacity .5s ease-out;
    -webkit-user-select:none;
    -moz-user-select:none;
    user-select:none;
    background-color:#ffffca;
    border:1px solid #b5b5b5;
    cursor:pointer;
    display:none;
    font:normal 9pt arial,sans-serif;
    left:128px;
    opacity:0;
    position:absolute;
    top:16px;
    white-space:nowrap;
    padding:2px 3px;
}

Note

#hplogo-click {
    background:url(logos/2011/guitar11-hp-sprite.png) no-repeat -2000px -2000px;
}

and <div id="hplogo-click" onclick="google.doodle.go();"></div> which contain the actual image of the guitar.

Why do big sites use 'bad practices'?

8 votes

I often see articles, posts and comments something like:

  • globals are bad in javascript
  • script tags should be at bottom of page
  • CSS should be in external files and at the top of page
  • scripts should be in external files, not plain script-tags.
  • etc.

I've looked up the HTML source of some big sites and have noticed that they have a lot of plain javascript and CSS inside HTML markup. JavaScript and HTML are note always obfuscated, and so on.

There are quite a few separate issues here.

  1. What you see when you "view source" is not usually what they develop with. It's usually a compressed / optimised form generated from "source" code.
  2. Claims about what is "best practice" are necessarily generic, and don't apply to all scenarios (especially if you're a big site and need specialised optimisation). These guidelines should be considered individually for each project.
  3. Best practice, or even clean code, doesn't directly translate to return on investment. It may be nice to have consistent naming schemes, but is it worth the time developing and enforcing the scheme across 100s of developers?
  4. Laziness, incompetence, or Friday nights.

Wrap a list to the right

8 votes

If i had a list like the following:

<ul>
  <li>Alex</li>
  <li>James</li>
  <li>Thomas</li>
  <li>Is</li>
  <li>Asking</li>
  <li>Questions</li>
  <li>On</li>
  <li>Stackoverflow</li>
</ul>

The default will be displayed like:

* Alex   
* James
* Thomas
* Is
* Asking
* Questions
* On
* Stackoverflow

What CSS would i use to get it to display like:

* Alex     * Questions
* James    * On
* Thomas   * Stackoverflow
* Is
* Asking

Thanks in advance...

For modern browsers

ul{
    -ms-column-count: 2;
    -o-column-count: 2;
    -moz-column-count: 2;
    -khtml-column-count: 2;
    column-count: 2;
    }

Issue with applying dotted border to cells in table design

7 votes

Here's my fiddle:

http://jsfiddle.net/gFA4p/84/

In this screenshot, the green lines represent where I'm trying to apply dotted lines.

enter image description here

I am able to get the left-right borders to appear as dotted lines, but not the bottom borders.

How can I resolve this?

The issue you're seeing is due to the rules of conflict resolution when it comes to border collapse. Solid takes precedence over dotted:

http://lachy.id.au/dev/css/tests/bordercollapse/bordercollapse.html

I believe you will need to make the conflicting borders dotted as well. So if you went a cell's left border to be dotted, you'll need to make the right border of the cell to its left also dotted (or anything of lower precedence, but dotted make the most sense).

How to keep text opacity 100 when its parent container is having opacity of 50

7 votes

I have a list div which have a opacity set to 50 and inside this div I want to display some text with opacity 100,

Here's what I mean:

<div id="outer">
  <div id="inner">
    Text
  </div>
</div>

The CSS would be:

#outer {
  opacity: 0.5;
}

#inner {
  opacity: 1.0;
}

I tried that, but it doesn't work.

please help

Regards

This tutorial is pure genius

In essence, you're overriding this css "hiccup" by floating a transparency over a div, then presenting the type layer at 100% opacity over that. It just works!

Why use a form tag when you're submitting via ajax?

5 votes

Philosophical question:

Say I've got a web app that requires javascript and a modern browser, so progressive enhancement is not an issue. If my form is being built via javascript, and my data updates are all being done via ajax POSTs & PUTs, is there really any reason to wrap my controls in a form tag? If I'm still going to use the tag, say for semantic or structural reasons, is there any reason to have action and method params that I'm going to ignore? It kind of feels like a hold-over from an earlier era to me.

There is at least one important user-experience feature provided specifically by wrapping inputs inside a form tag:

The enter key will submit the form. In fact, in Mobile Safari, this is how you get the "Go" button to appear on the keyboard.

Without a form wrapping the inputs, there is nothing to submit.

You can of course provide enter-key behavior through a keypress event, but I don't know about if this works for mobile devices. I don't know about you, but I'd rather work with the semantics provided by the browser than have to imitate them with events.

In your case, you would simply provide an onsubmit event handler for the form, which would do your AJAX submit, then return false, canceling the actual submit.

You can simply provide action="" (which means "self"), and method is not required — it defaults to GET.