04th

innerHTML, innerText and textContent

1

innerHTML, innerText, textContent, html() and text()?

Issue: I recently ran into a bug that there is a div block (see image below) that contains a few links (as in <a> tags) and a couple of line breaks (as in <br>s). There is an edit button associated with the div block. Clicking the edit button will reveal a textarea, which should contain the plain text version of the content inside the div block.

Sample “div block” (note that the edit link is not considered part of the div):

innerText issue - div content

Expected content in the textarea for the purpose of edit should be:

Welcome to http://www.test.com!
Hope you enjoy it!

However, the actual content in the textarea is:

Welcome to <a target="_blank" href="http://www.test.com">http://www.test.com</a>!<br><br>Hope you enjoy it!

innerText issue - textarea content

The cause is that it was using the innerHTML property of the div (actually, it’s using jQuery, so it is html()), and I do not want HTML tags!

My first thought was to use innerText, which is supported by IE5.5+, Safari, Chrome and Opera. Wait… Firefox does not support innerText.

Firefox has its own property called textContent, which is actually what W3C recommended. It is also supported by Chrome and Opera. However, IE does not support it.

See the W3C DOM Compatibility table.

innerText v.s. textContent

Let’s take a look at how they behave differently in Chrome. Chrome supports both properties, but they yield different results.

Doing textContent on the aforementioned div would return:

Welcome to http://www.test.com!Hope you enjoy it!

Doing innerText on the same div would return:

Welcome to http://www.test.com!
Hope you enjoy it!

Looks like innerText is what I want!

What about jQuery’s text()?

jQuery has a nice text() method, which works on all browsers. The only issue is that it works like the textContent property in Firefox – it strips out linebreaks. We want something like innerText that honestly includes linebreaks.

My solution

Rather than messing with text(), innerText and textContent, I used the following solution

1
var message = div.innerHTML.replace(/\&lt;br\&gt;/gi,"\n").replace(/(&lt;([^&gt;]+)&gt;)/gi, "")

The advantage is that innerHTML is supported in all browsers. It’s all native JavaScript, so no jQuery’s html() or text(). Replacing <br> tags by \n makes sure that it works like innerText, and the final replace() is a regular expression that removes all HTML tags.

Arguably, you could use this block instead.

1
2
3
4
5
if (document.body.innerText) {
var message = div.innerText;
} else {
var message = div.textContent;
}

It is a bigger block, but I believe it is faster on a big chunk of content in the div.

Comments?

Bookmark and Share
28th

Box.net

0

I’ve finally made my move from San Francisco/ Berkeley to the heart of Silicon Valley!

I am joining Box.net as a software engineer. I am fascinated by the ideas of this company, and the technology behind. They are totally awesome. I can’t say much yet as I am still pretty new to the team, but I am excited about the new adventure! Here, I don’t have to read and write 80 emails a day. No more client conference calls. No more consulting but only engineering!

Good-bye Isobar/ Molecular! For those who don’t know, Isobar is the world’s biggest digital agency network. I was fortunate enough to be part of the engineering team in the San Francisco office. I enjoyed the past three years with Isobar/ Molecular, and I would highly recommend this place for web developers, engineers and interaction designers who want to participate in all kinds of fun projects with big-name clients.

Bookmark and Share
25th

jQuery Conference 2010: Key Takeaways

1

The past weekend is all about jQuery, JavaScript and web development.

Similar to many other tech conferences, the jQuery conference at Microsoft’s campus in Mountain View allows developers to choose one of the two available sessions at a time slot. For me, making choices on weekends is often not desired, especially when I do not want to miss out anything.

Here I am going to share the takeaways from half of the sessions I attended.

Ads, widgets, and analytics – Steve Souders

A similar talk on site performance was given earlier at JS Conf. See the recap here at Ajaxian.

Steve recommended using both YSlow and Google Page Speed Firefox plugins. Google Webmaster Tool gives performance recommendations; webpagetest.org and ShowSlow.com are also valuable tools to evaluate site performance.

Third party scripts are often very slow. Placing them near the top of the document can seriously impact the page performance. Here is a way to get around it:

1
2
3
var head = document.getElementsByTagName("head")[0] || document.documentElement, script = document.createElement("script");
...
head.insertBefore(script, head.firstChild);

High Performance jQuery – Robert Duffy

Key points:

  • Single-page application can degrade performance. Event binding can seriously affect the performance if the application keeps binding events to the same element, which is a common mistake of many applications.
  • Use the right tool. show() and hide() can often be replaced by .addClass(“show”) and .addClass(“hide”).
  • Use for-loop instead of each() can often improve performance.
  • Cache selectors in a local variable in order to avoid making unnecessary queries. E.g.
  • 1
    2
    3
    4
    var headers = $("headers");
    headers.doSomething();
    ...
    headers.doSomethingElse();

High Performance JavaScript – Nicholas Zakas

Slides of this presentation can be found here. Nicholas’ website also has plenty of posts and demos.

Takeaways:

  • The browser UI thread is responsiblefor both JS execution and UI update.
  • Long-running JavaScript = unresponsive UI
  • Limit JavaScript execution to 50ms – use Timers and web workers
  • JavaScript timers – time to add the execution command to the UI queue, not guaranteed to be the time of execution
  • A repaint occurs when a visual change doesn’t require recalculation of layout. This include changes to visibility, colors, background images, etc.A reflow occurs when a visual change requires a change in lauout. This include initial page load, browser resize, DOM structure change, layout style change, layout information retrieved, etc
  • A reflow occurs when a visual change requires a change in lauout. This include initial page load, browser resize, DOM structure change, layout style change, layout information retrieved, etc
  • Avoid browser “repaint”. $(“.div1″).css(“display”,”block”).css(“background”,”black”) is much worse than $(“.div1″).addClass(“.specialStyle”). Group UI changes into a CSS class instead of adding individual CSS rules. Also consider ele.style.styleText()
  • Manipulate a DOM element out of the tree before adding it to the document
  • Minimize access to layout information such as offsetTop, clientWidth… and store them in variables

How to manage large applications with jQuery – Alex Sexton

Slides of this presentation can be found here.

  • Alex briefly discussed about the 3 major inheritance models, i.e. Pseudo-Classical, Classical and Prototypal.
  • Store DOM elements in objects… code becomes much much easier!
  • He also mentioned about using RequireJS, which is faster than just including script tags, since it’s asynchronous by default.

Future-proof HTML 5 markup with jQuery – Mike Taylor

Do this:

1
2
3
<!--[if lte IE 9]-->
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
&lt; ![endif]--&gt;

HTML 5 forms are cool, e.g. autofocus, pattern, placeholder and datalist.

Session 6 – Web Workers with jQuery – Rick Waldron

Web Workers is an API that allows running non-blocking scripts parallel to the main page. It creates a thread-like environment that processes can live in parallel. Long-running scripts can be processed by different threads without blocking the UI queue.

Things to look: jQuery Hive and Pollen JS.

Here is one of the posts by Rick on Web Workers.

Bookmark and Share
23rd

YOURLS: Your Own URL Shortener

0

There’s a long history of URL shortening services. I still remember the days when we had to host our websites on Geocities or Xoom. We all hated the long URLs, and so there came the redirect services by come.to, i.am, etc. After all, you wouldn’t argue that http://i.am/davidt looks a lot more elegant than http://www.geocities.com/neighborA/432499. The need for shortened URLs was largely due to the fact that badly generated URLs could not satisfy the sense of arrogance of being a webmaster.

As domain registration fee became cheaper and cheaper, a lot of people rather pay ten bucks a year to own a unique and permanent URL. Come.to and i.am eventually were forgotten.

Twitter created a whole new page to the history of shortened URLs. Within a limited amount of space, it is not possible to include a long URL. Bit.ly was an answer to this kind of needs. I don’t use bit.ly heavily as I am not a frequent twitter user. It caught my attention about URL shortner when recently I heard about ShadyURL.

My colleague, Aditya Mantrala, recently introduced me a self-hosted tool called YOURLS. It has an awesome name, and it is extremely easy to use and configure. With it, you can become another bit.ly.

YOURLS requires that your server supports PHP and MySQL. It took me less than 5 minutes to finish the download and installation process on my local server.

As I said before, it behaves like bit.ly, except that it uses your own domain name. The best features I like about YOURLS include:

  1. The easy bookmarklets that allow you to instantly shorten any URL you are current visiting.
  2. It gives you an API so that you can let the public shorten their URLs without exposing any admin secure credential.
  3. It is a great SEO tool. Having an URL that contains important keywords is one of the factors to grab the top spot in search results. With YOURLS, the URLs of your site are no longer limited to the technology behind the scene. http://www.yoursite.com/aboutus/contact/direction.jsp?city=139801&param1=12343&param2=2390jd can perhaps become http://www.yoursite.com/sanfrancisco-office-direction. And you can let the marketing people do the shortening work using the admin tool that requires little technical knowledge.
YOURLS panel

Tech geeks: the technology behind is pretty simple. Every URL from your site will be looked up against the .htaccess file. YOURLS’ PHP files will make queries to your MySQL database to see if an entry exists. If it does, the destination URL will be returned and you will be redirected.

Therefore, you need to make sure that .htaccess is enabled. Very often, Apache’s apache/conf/httpd.conf will have the line AllowOverride None, which could be changed to AllowOverride All. Another place to check is within httpd.conf, the line
LoadModule rewrite_module modules/mod_rewrite.so
needs to be uncommented.

As it checks every single URL against the .htaccess entries, my guess is that server performance will be affected. Also, if your web site has heavy traffic, stress test should be done on the server as this tool relies heavily on the MySQL database.

Bookmark and Share
13th

Enabling cross-domain cookies

0

I recently created a page that contains a tabbed container. In each tab, there is a different iframe that hosts a map from a third-party domain. The iframes need to rely on cookie to communicate so that they can pass address information.

The problem is that IE 6 does not seem to have cookies enabled for those iframes. And of course, this issue does not only apply to maps, but also online ads that rely on iframes.

The cause to the issue turns out to be a security restriction in IE 6. This is one of the few places where IE 6 is more secure than other popular web browsers. IE 6 does not allow third-party cookies to be downloaded. And so if you are on a page that includes resources from another domain and cookies are generated from those resources, these cookies are known as third-party cookies.

The solution is to add an extra HTTP header. When IE 6 sees the Platform for Privacy Preferences Project (P3P) header in the resource that creates cookies, it will allow those yummy cookies to be downloaded.

The code to add the header to a specific resource can be written in various languages. Note that they should be written before the code that is responsible for the view.

P3P HTTPheader in ASP.NET

1
HttpContext.Current.Response.AddHeader("p3p",  "CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND  CNT\"");

P3P HTTP header in PHP

1
header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');

P3P HTTP header in JSP

1
response.setHeader("P3P","CP='IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT'")

P3P HTTP header in ColdFusion

1
<cfheader name="P3P" value="CP='IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT'" />

A site-wide approach on an Apache server can be set in a .htaccess or the httpd.conf:

1
Header set P3P "policyref=\"/w3c/p3p.xml\", CP=\"IDC  DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\""

To verify the correct implementation of HTTP header, you can use Firebug:

Using Firebug to see HTTP headers
Bookmark and Share
03rd

Hello world!

0

This is my first post on this new site. It officially replaces the last edition of Davidalism.com, which was created back in 2006 during my senior year of college.

It’s also the first time ever that I use a theme/ template. I always thought designing (as in… creating comps, high-level wireframing, and coding) web sites from scratch is fun. However, as time goes by, I rather use an existing template that meets my taste so that I can spend more time on the actual content.  I spent too much time at work doing all these so I just want to have a place for myself to share stuff with my readers.

You probably know that this is built off of Wordpress. I am very impressed with the functionalities that Wordpress provides. It is so easy to update content here. This is key. For the past 12 years of my career, I often lacked the motivation to open up the HTML files, update the HTML code and upload via FTP. It is plain tedious. Now I can fully enjoy the easiness of using a CMS, and I hope I will never use inconvenience as an excuse to not update my site.

Welcome to this new edition of Davidalism.com. Here you can find my latest insight and research on web development, my random thoughts, and a few of photographs that I take here and there.

Enjoy!

Bookmark and Share

    About me

    I am a young web consultant based in Silicon Valley. I specialize in interaction development using cross-browser HTML, CSS, JavaScript, PHP and various other technologies. I am also experienced in implementing Content Management Systems to help my clients in managing and globalizing their web sites. When I don't work, I love to travel and shoot photographs.