Best html questions in March 2011

Why don't I just build the whole web app in Javascript and Javascript HTML Templates?

12 votes

I'm getting to the point on an app where I need to start caching things, and it got me thinking...

  1. In some parts of the app, I render table rows (jqGrid, slickgrid, etc.) or fancy div rows (like in the New Twitter) by grabbing pure JSON and running it through something like Mustache, jquery.tmpl, etc.
  2. In other parts of the app, I just render the info in pure HTML (server-side HAML templates), and if there's searching/paginating, I just go to a new URL and load a new HTML page.

Now the problem is in caching and maintainability.

On one hand I'm thinking, if everything was built using Javascript HTML Templates, then my app would serve just an HTML layout/shell, and a bunch of JSON. If you look at the Facebook and Twitter HTML source, that's basically what they're doing (95% json/javascript, 5% html). This would make it so my app only needed to cache JSON (pages, actions, and/or records). Which means you'd hit the cache no matter if you were some remote api developer accessing a JSON api, or the strait web app. That is, I don't need 2 caches, one for the JSON, one for the HTML. That seems like it'd cut my cache store down in half, and streamline things a little bit.

On the other hand, I'm thinking, from what I've seen/experienced, generating static HTML server-side, and caching that, seems to be much better performance wise cross-browser; you get the graphics instantly and don't have to wait that split-second for javascript to render it. StackOverflow seems to do everything in plain HTML, so does Google, and you can tell... everything appears at once. Notice how though on twitter.com, the page is blank for .5-1 seconds, and the page chunks in: the javascript has to render the json. The downside with this is that, for anything dynamic (like endless scrolling, or grids), I'd have to create javascript templates anyway... so now I have server-side HAML templates, client-side javascript templates, and a lot more to cache.

My question is, is there any consensus on how to approach this? What are the benefits and drawbacks from your experience of mixing the two versus going 100% with one over the other?

Update:

Some reasons that factor into why I haven't yet made the decision to go with 100% javascript templating are:

  • Performance. Haven't formally tested, but from what I've seen, raw html renders faster and more fluidly than javascript-generated html cross-browser. Plus, I'm not sure how mobile devices handle dynamic html performance-wise.
  • Testing. I have a lot of integration tests that work well with static HTML, so switching to javascript-only would require 1) more focused pure-javascript testing (jasmine), and 2) integrating javascript into capybara integration tests. This is just a matter of time and work, but it's probably significant.
  • Maintenance. Getting rid of HAML. I love HAML, it's so easy to write, it prints pretty HTML... It makes code clean, it makes maintenance easy. Going with javascript, there's nothing as concise.
  • SEO. I know google handles the ajax /#!/path, but haven't grasped how this will affect other search engines and how older browsers handle it. Seems like it'd require a significant setup.

Persistant private data storage.

You need a server to store data with various levels of public/private access. You also need a server for secure closed source information. You need a server to do heavy lifting that you don't want to do on the client. Complex data querying is best left upto your database engine. Indexing and searching is not yet optimised for javascript.

Also you have the issues of older browsers being far slower. If your not running FF4/Chrome or IE9 then there is a big difference between data manipulation and page construction on the client and the server.

I myself am going to be trying to build a web application made entirely using a MVC framework and template's but still using the server to connect to secure and optimised database.

But in general the application can indeed be build entirely in javascript and using templates. The various constructs and javascript engines have advanced enough to do this. There are enough popular frameworks out there to do this. The Pure javascript web applications are no longer experiments and prototypes.

Oh, and if were recommending frameworks for this, then take a look at backbone.js.


Security


Let's not forget that we do not trust the client. We need serverside validation. JavaScript is interpreted, dynamic and can be manipulated at run time. We never trust client input.

How to disable resizable property of TextArea?

11 votes

I want to disable the resizable property of a TextArea.

Currently, I can resize a TextArea by clicking on the bottom right corner of the TextArea and dragging the mouse. Is it possible to disable this? Thanks in advance.

Use the following CSS rule to disable this behavior for all TextArea elements:

textarea {
    resize: none;
}

If you want to disable it for some (but not all) TextArea elements, you have a couple of options (thanks to this page).

To disable a specific TextArea with the name attribute set to foo (i.e., <TextArea name="foo"></TextArea>):

textarea[name=foo] {
    resize: none;
}

Or, using an ID (i.e., <TextArea id="foo"></TextArea>):

#foo {
    resize: none;
}

Note that this is only relevant for WebKit-based browsers (i.e., Safari and Chrome), which add the resize handle to TextArea controls.

Standard way to detect mobile mail client?

11 votes

This question is similar to "Standard way to detect mobile browsers in a web application based on the http request" except for mail clients. For instance, if an email message is opened on the built-in iPhone mail client it will display a version of the message specially formatted for the iPhone. If opened on an tablet or desktop it will display as the complete, full-size version of the email. This is similar in principle to web sites that have mobile-friendly versions of the site that load automatically by detecting the user-agent - but for email clients.

So - is it possible to detect the mail client being used to open an email and format the message accordingly? Perhaps a way to detect the screen resolution?

You can try to apply @media css queries that target specific browsers like mobile devices. There is a good introduction on the campaignmonitor help website but be aware, it probably is only supported in a hand full of browsers and devices, iOS being on of them luckily :)

Basically you are defining css styles that target specific screen widths so that you can optimize your email for limited screen space.

@media only screen and (max-device-width: 480px) { ... }

When talking really detection and displaying a totally different email, that's really impossible since you are talking about javascript there and that's not done in emails and probably won't even work in 99% of all email clients. But you can go a loooong way with @media queries.

How to remove HTML tags from user content?

11 votes

NOTE: I asked this question already and it migrated to meta. This is not a specific question about stack overflow so much as it's a question about a behavior I would like to include in my own project. i.e. This IS a programming question. It just so happens that SO performs the exact function I'm looking for. This question is not about Stack Overflow, it is about a programming behavior and I would like programming references. Thank you :)


Alright, let's try this again.

I thought the above note was enough, but apparently not so here is a tl;dr:

How do you remove tags from user-submitted content? A site that just so happens to contain this behavior is a very obscure site you may not have heard of called "Stack Overflow". Below is a description of the desired behavior as well as samples of the end results.


I am curious how SO goes about removing HTML tags from posts. I just started using their MarkdownSharp project. By default MarkdownSharp encodes any HTML within code blocks like this:

<span style="color: red;">I am HTML</span>

But if I do the same thing outside of a code block it simply doesn't show up at all:

I am HTML <- tags are removed.

But they have whitelisted certain tags for basic markup, like the header tags:

<h1>test</h1>

test

I can also type HTML entities like &gt; doesn't get re-encoded, it will actually show up as a >

I'm sure the tags that get removed are being removed BEFORE the content is passed to markdown, as markdown generated HTML tags would likely be removed if this tag removal code was run after markdown handled it.

Does anyone know how SO accomplishes this, and if it is code that is available to use? Alternatives are acceptable also. I'm hoping to find something in C# as my project is C# ASP.NET MVC 3.

Thanks in advance!

As I said on Meta: Stack Overflow uses the HtmlSanatizer written by Jeff Atwood.

Background of body element

10 votes

When you style the background of the body element, why does the styling affect the entire screen and not just the body element itself? Let's say i create the following rule:

body {width: 700px; border: 1px dotted red; background-color: blue;}

I find that the border shows up as 700px wide as i would expect, but the background color occupies the entire browser viewport. Why?

Quote from http://www.w3.org/TR/CSS21/colors.html

The background of the root element becomes the background of the canvas and covers the entire canvas, anchored (for 'background-position') at the same point as it would be if it was painted only for the root element itself. The root element does not paint this background again.

The body element is the root-element, and thus, as required by the CSS rules it loses its background style and the background style is applied to the containing canvas (the webpage area in the browser), therefor the entire screen is blue. The other properties stay with the element (e.g. the border).

my lovely dream : slanted text areas in div

10 votes

I was wondering if any of you knew if it was possible to make anything looking like this? I know about http://www.infimum.dk/HTML/slantinfo.html but I can't put any text in the slanted areas.

Here's an image of what I'm trying to do:

enter image description here

Did it with a bit of javascript: http://jsfiddle.net/billymoon/AvmE8/

But that is just for convenience, you can do the same with HTML.

Will not apply to all circumstances, and will need a little tweaking, but can be made to work for things you know the approximate length of - or know the upper bound of.

html:

<div id='left'>whatever text</div><div id='right'>random text</div>

css:

#left, #right{
    text-align: justify;
    position: absolute;
    width:60%;
    right:0;
}
#right{
    right:auto;
    left:0;
}

js:

for (i = 1; i < 40; i++) {
    $('<div />').css({
        border: '1px solid silver',
        height: 10,
        width: (5 * i),
        float: 'left',
        clear: 'left'
    }).prependTo($('#left'))
    $('<div />').css({
        border: '1px solid gold',
        height: 10,
        width: (200 - (5 * i)),
        float: 'right',
        clear: 'right'
    }).prependTo($('#right'))
}

Ajax Security (i hope)

9 votes

Hi guys, I'm building a browser game and im using a heavy amount of ajax instead of page refreshs. I'm using php and javascript. After alot of work i noticed that ajax isnt exactly secure. The threats im worried about is say someone wants to look up someones information on my SQL server they'd just need to key in right information to my .php file associated with my ajax calls. I was using GET style ajax calls which was a bad idea. Anyways after alot of research i have the following security measures in place. I switched to POST (which isnt really any more secure but its a minor deterent). I have a referred in place as well which again can be faked but again its another deterrent.

The final measure i have in place and is the focus of this question, when my website is loaded i have a 80 char hex key generated and saved in the session, and when im sending the ajax call i am also sending the challenge key in the form of

challenge= <?php $_SESSION["challenge"]; ?>

now when the ajax php file reads this it checks to see if the sent challenge matchs the session challenge. Now this by itself wouldnt do much because you can simply open up firebug and see what challenge is being sent easily. So what I'm having it do is once that challenge is used it generates a new one in the session.

So my question is how secure is this from where im standing it looks one could only see what the challenge key was after it was sent and then it renews and they couldnt see it again until it is sent, making it not possible to send a faked request from another source. So does anyone see any loop hole to this security method or have any addition thoughts or ideas.

See the answer by 'meagar'.

I'd like to mention:

By passing around an identifier in Session, you're doing what the Session is already doing. There's usually a cookie with a unique identifier similar to the one you're generating, which is telling your application, essentially, who that person is. This is how PHP sessions work, in general.

What you would need to do, in this case, is check that for a given request - POST or GET - that the particular user (whose unique user ID, or similar, is stored in the Session) has permission to add/change/delete/whatever with that particular request.

So for a "search" request, you would only return results that User X has permission to view. That way, you don't worry about what they send - if the user doesn't have permission to do something, the system knows not to let them do it.

Hence "you should be authenticating all requests".

Someone feel free to add to this.

Images in CSS or HTML as data/base64

8 votes

To reduce the number requests on the server i have embended some images as BASE64 directly into the css. (Its automated in the build process)

like this:

background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAFWHRTb2Z0d2FyZQBBZG etc...);

Is this a good practice? Are there some reasons to avoid this? Are there some major browser that dont have data url support?

Bonus question: Does it make sense to do this for the CSS & JS also?

Is this a good practice? Are there some reasons to avoid this?

It's a good practice usually only for very small CSS images that are going to be used together (like CSS sprites) when IE compatibility doesn't matter, and saving the request is more important than cacheability.

It has a number of notable downsides:

  • Doesn't work at all in IE6 and 7.

  • Works for resources only up to 32k in size in IE8.

  • It saves a request, but bloats the HTML page instead! And makes images uncacheable. They get loaded every time the containing page or style sheet get loaded.

  • Base64 encoding bloats image sizes by 33%.

  • If served in a gzipped resource, data: images are almost certainly going to be a terrible strain on the server's resources! Images are traditionally very CPU intensive to compress, with very little reduction in size.

How do you pinpoint a word or a selection in the entire document?

7 votes

Hi

I am trying to highlight a part of the text on my website. This highlighted text will be saved for the specific user in a database and when the document is opened again it will show the previously highlighted text. I assumed I would be using javascript to highlight the text but I cannot seem to find a way to pinpoint where the word is that I am highlighting.

function getSelText()
{
    var txt = '';
     if (window.getSelection)
    {
        txt = window.getSelection();
             }
    else if (document.getSelection)
    {
        txt = document.getSelection();
            }
    else if (document.selection)
    {
        txt = document.selection.createRange().text;
            }
    else return "";
    return txt;
}

I am using that to get the selection but I cannot figure out where the selection is in the text. The biggest annoyance is when I have duplicates within the line or text so if I were to use search then I would find the first instance and not the one I was looking for.

So the question is : How do you pinpoint a word or a selection in the entire document?

You can use my Rangy library and its selection serialization module for this. Rangy's core provides a consistent Selection and Range API for all browsers and the serializer module builds on this by converting each selection boundary into a path through the document. See the linked documentation for more details.

Firefox 3 vs Firefox 4 development difference?

7 votes

I was thinking of updating to Firefox 4 (currently running Firefox 3.6.15 -- hold on not a software question specifically!) and had some concerns when it comes to web development.

My only concern is if there are any compatibility issues (CSS / HTML) or quirks between the two. I would hate to see something like a 3px spacing while using Firefox 4 on one website vs 0px using Firefox 3 (almost like an IE6 vs IE7 vs IE8 fiasco, if you get my drift).

Ultimately I am just checking if Firefox 4 is business as usual with the display of a website / web app with an updated 'engine' (which is what I expect).

Thoughts? Has anyone compare at this level? And I'm not just talking things like on the CSS Reset level, altho I am thinking along those lines of compatibility.

Hopefully I am making my concern somewhat clear. I couldn't seem to find any comparisons other than enhancement list to FF4 (over FF3), I don't mean to make this a software question but rather, should I be aware of any output changes that I am missing by upgrading. I don't want to miss critical differences when it comes to development and browser compatibility for the customer.

Thanks.

Even IE6 / IE7 / IE8 vs other browsers isn't as big a fiasco as you make out; the bugs in old IE versions with weird spacing differences were mainly caused by web sites forcing the browser into Quirks mode (which lives up to its name) rather than standards mode. If you're in standards mode, the browsers all pretty much live up to the same rules, albeit with fewer features in older versions (much fewer features in the case of IE6).

With that in mind, the upgrade from FF3.6 to FF4.0 shouldn't present you with any issues for existing sites written with FF3.6 in mind (and standards mode in general).

The only major caveat that I'm aware of with FF4 is that they've removed the -moz-binding CSS feature. This is (or rather, was) a Firefox-specific (ie non-standard) CSS feature which allowed you to bind an XUL template to an HTML element using CSS. XUL is the XML UI definition language which the Firefox user interface is written in (as well as other apps from Mozilla). They've removed the ability to reference it directly from a web page due to security considerations.

This one issue shouldn't generally concern anyone -- if you'd been sticking to standards anyway, you'd never have used it.

However, there is one way in which it has been used quite widely: as a browser hack to get Firefox to support an ellipsis. All other browsers support CSS text-overflow:ellipsis;, but Firefox does not. Even FF4 won't support it. Someone managed to hack a way to do it using -moz-binding, and many sites have been using it since then. This hack will cease to work in FF4.

See my question on this topic here: text-overflow:ellipsis in Firefox 4?

But other than that one thing, pretty much everything else new in Firefox 4 - certainly from the perspective of the rendering engine -- is an incremental upgrade from FF3.6, so existing sites should continue to work unchanged.

Do you need text/javascript specified in your <script> tags?

7 votes

I read somewhere that you no longer need things like type="text/javascript" and the weird CDATA and <!-- things in your script tags. So, instead of:

<script type="text/javascript">
//<![CDATA[
<!--

    //your script here

-->
//]]>
</script>

You would just do:

<script>
    //your script here
</script>

I can't remember where I read this though. It was from a Google or Yahoo engineer I think, and they specifically mentioned which browsers required these archaic constructs and why. Anyone know what blog post/article this was talked about, or have a good resource talking about this?

See Crockford's write-up on the <script> tag, most notably:

Do not use the hack with scripts. It was intended to prevent scripts from showing up as text on the first generation browsers Netscape 1 and Mosaic. It has not been necessary for many years. is supposed to signal an HTML comment. Comments should be ignored, not compiled and executed. Also, HTML comments are not to include --, so a script that decrements has an HTML error.

...

type="text/javascript"

This attribute is optional. Since Netscape 2, the default programming language in all browsers has been JavaScript. In XHTML, this attribute is required and unnecessary. In HTML, it is better to leave it out. The browser knows what to do.

GUI alternative to <select> when you have a lot of options

7 votes

A <select> might be good for choosing between 3-15 simple items, but how do you deal with 15-100+?

The simplest option would be to just have a plain <select> with a lot of <option>s, but it's not very user friendly. There's a lot of scrolling and it might be hard to find the option you are looking for. The benefit is that you can (maybe with scrolling) see all the options you have.

A more advanced option would be to have a text field with autocomplete. A user types in a letter or two, and search results come back which you choose from. It makes it easier to find the option you are looking for - if you know what you are looking for. The drawback is that the user can't see all the options.

An even more advanced option would be to build a "search, list and choose" widget which defaults to show X items, but allows you to search. An advantage of this approach is that I can allow search on multiple attributes and not just the name of the item which is to be selected.

  1. What solutions have you deployed in these situations?
  2. Is there a jQuery plugin I should know about?

  1. The solution that I like to use is provide the user a select list with all the options (should they want to look through it), but provide an autocomplete feature which searches through the list as they type into it. Sort of a hybrid of your first and second options.
  2. As for plug-ins, there are a number out there (as well as documentation which will lead you to more) that can help you here:

Suppress Safari’s “You have entered text…” warning?

7 votes

Are you sure you want to close this tab? You have entered text on “Stack Overflow”. If you close the tab, your changes will be lost. Do you want to close the tab anyway?

Safari helpfully (?) prompts before closing a tab or window when text has been entered into an input.

There are some cases where, as a web developer, this isn’t desirable — for example, when the input is a live search where the user has probably already gotten the results he’s looking for when the window is closed, even though there’s still text in the field.

How can I let Safari know that text in a particular input doesn’t need its protection?

I think I've got a solution to this problem, though it's unquestionably a hack (i.e. if Safari changes how this feature is implemented, it could stop working). Shown here with a touch of jQuery:

$('.unimportant').live('blur', function(){
    var olddisplay = this.style.display;
    this.style.display = 'none';
    this.clientLeft; // layout
    this.style.display = olddisplay;
});

Demo (try typing in the "unimportant" field, click somewhere else on the page, then close the window).

In short:

  1. Hide the input
  2. Trigger layout
  3. Show the input

You can also change the value of the input, trigger layout, and change it back.

The one limitation here is that cleaning the input has to be done explicitly. In this case, it will be dirty until blur. This works well in my situation, and probably in many others, since the input will be protected from an accidental window close until something else on the page is manipulated (e.g. a link is clicked). You could choose to run this on keyup if you're willing to live with a flicker of the insertion point every time a key is pressed.

I'm open to cleaner solutions.

Is there an advantage to dynamically loading/unloading javascript and css stylesheets?

6 votes

Background:

I'm putting together a site that will use ajax as a primary method of changing the content. That way the main frame and images will not have to be constantly reloaded with every page change. The main frame has its own site.css stylesheet.

Question 1:

Is it worthwhile to put all the stylesheet information into a single stylesheet? I think that this would make the website less modular. Everytime a new page or content is added/removed the css would have to be updated (given the content requires different style information).

Question 1.1:

Same question but with javascript.

Question 2:

If it is worthwhile (as I think it is) to have multiple stylesheets, is it beneficial to unload a stylesheet when its not in use. For example, I load the profile.php page so I dynamically load the profile.css. The user then changes to the settings.php page, I unload the profile.css and load the settings.css. Is this constant loading/unloading going to tank performance or even save on website size?

Question 2.1

Same question as above but applied to javascript functions.

Once your javascript or css file is downloaded to the machine, it is cached by their browser. So, you don't incur the additional cost of another HTTP request. Lazy loading the scripts and stylesheets could make sense, but there is no sense in unloading these web assets once they have already been sent to the client.

It is good to use some sort of mechanism to compile your scripts and stylesheets to minimize the initial http requests to one per asset type. Having only one stylesheet and one javascript file would be an architectural nightmare in many cases, but that doesn't mean that you can't still present it to the browser that way. I use .NET, so I'm not sure how you handle this in PHP, but I'm sure the functionality is out there.

how to use jQuery ajax calls with node.js

4 votes

This is similar to Stream data with Node.js, but I don't feel that question was answered sufficiently.

I'm trying to use a jQuery ajax call (get, load, getJSON) to transfer data between a page and a node.js server. I can hit the address from my browser and see 'Hello World!", but when I try this from my page, it fails and shows that I get no response back. I setup a simple test page and hello world example to test this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>get test</title> 
</head>
<body>
    <h1>Get Test</h1>
    <div id="test"></div>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js"></script>
    <script>
        $(document).ready(function() {
            //alert($('h1').length);
            $('#test').load('http://192.168.1.103:8124/');
            //$.get('http://192.168.1.103:8124/', function(data) {                
            //  alert(data);
            //});
        });
    </script>
</body>
</html>

and

var http = require('http');

http.createServer(function (req, res) {
    console.log('request received');
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(8124);

If your simple test page is located on other protocol/domain/port than your hello world node.js example you are doing cross-domain requests and violating same origin policy therefore your jQuery ajax calls (get and load) are failing silently. To get this working cross-domain you should use JSONP based format. For example node.js code:

var http = require('http');

http.createServer(function (req, res) {
    console.log('request received');
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('_testcb(\'{"message": "Hello world!"}\')');
}).listen(8124);

and client side JavaScript/jQuery:

$(document).ready(function() {
    $.ajax({
        url: 'http://192.168.1.103:8124/',
        dataType: "jsonp",
        jsonpCallback: "_testcb",
        cache: false,
        timeout: 5000,
        success: function(data) {
            $("#test").append(data);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert('error ' + textStatus + " " + errorThrown);
        }
    });
});

There are also other ways how to get this working, for example by setting up reverse proxy or build your web application entirely with framework like express.