Inline JavaScript in HAML + SEO

  • Digg this article
  • Sphinn this article
  • Stumble this article
  • Facebook
  • del.icio.us
  • LinkedIn
  • Twit this article

Sunday, 08 February 2009

After putting together that microsite this weekend in HAML & Sinatra, I needed to do the usual SEO stuff inside the index.haml document; thankfully HAML 2.0+ comes with a filter for Javascript.

Example HAML'd Google Analytics Code

:javascript
  var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
  document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
  try {
    var pageTracker = _gat._getTracker("UA-393335-18");
    pageTracker._trackPageview();
  } catch(err) {}

Next up my robots.txt file

User-Agent: *
Allow: /

Disallow: /css/
Disallow: /images/
Disallow: /javascripts/

Sitemap: http://www.mysite.com/sitemap.xml

And the sitemap.xml

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>http://www.mysite.com/</loc>
    <changefreq>daily</changefreq>
  </url>
</urlset>

...ok the last two i'll get generated via ruby, but they're good examples ;-)

...something we'd like to disinvent

  • Digg this article
  • Sphinn this article
  • Stumble this article
  • Facebook
  • del.icio.us
  • LinkedIn
  • Twit this article

Sunday, 26 October 2008

The Rock

IE6 is a pain, especially supporting it when you're trying to build something really wonderful with javascript. However when you're web metrics come back showing over 60% of your users use it you really have to go that extra yard to put a smile on their face, it's tough but it's worth it in the end.

Thankfully a good friend pointed me to a site called evolt.org providing standalone copies of IE6, should help.

There are alternatives, Microsoft provide Virtual PC images to help you support their latest browsers; they've got a lifespan of about 3 months per download so you've got to grab a new one every couple of months but good as an acid tester.

On the Linux front you should be able to use the standalone IE6 build from the link above with WINE, or IE4LINUX.

Beyond that there's IETester for Windows, good for Vista as it's hard to get IE6 on Microsoft's latest O/S (xp is easier).

There's also another browser built by the Japanese company fenrir called Sleipnir for Windows which allows you to run Firefox and Internet Explorer side-by-side, last time I tried it had some stability issues but it looks to be getting there with the 2.8.2 release.

Should help.

...by the way the engine used by IE is called Trident ;-)

Javascript - Killing the TAB Key

  • Digg this article
  • Sphinn this article
  • Stumble this article
  • Facebook
  • del.icio.us
  • LinkedIn
  • Twit this article

Monday, 10 March 2008

One thing that might muck up your beautifully designed AJAX popups is the user repeatedly hitting the tab key, simple way of stopping this is by inserting a onkeydown event for the keypress..

Trapping TAB

<typo:code lang="ruby"> </typo:code>

Simple and effective, as soon as the user's cursor gains focus for the username textbox if they then try to hit TAB within it it won't do anything; effectively trapping the action dead.

Obviously if you've got two boxes (username + password), you'll want to put this kind of trap on the password textfield otherwise the user won't be able to tab to the next cell, but as a quick fix it works well.

Setting Focus

You can also set focus via...

<typo:code lang="ruby"> $('username').focus(); </typo:code>

IE 7 and password fields

  • Digg this article
  • Sphinn this article
  • Stumble this article
  • Facebook
  • del.icio.us
  • LinkedIn
  • Twit this article

Thursday, 06 March 2008

Quick Note. Unlike Firefox, Internet Explorer handles password fields a little differently, blanking out whatever value you pass it within a 'value' tag.

So...

<typo:code lang="ruby"> </typo:code>

Will have a password box in Firefox starred out, but in IE it'll appear blank.

To get around this you can use Prototype to inject a value into the password field, so the user see's it as starred out.

<typo:code lang="ruby"> $('mypass').value='********'; </typo:code>

Note, if you're generating the form dynamically with...

<typo:code lang="ruby"> var innerhtml='

Only fire your $('mypass') code after the form has been written to the page otherwise you won't be able to get a handle on it (most cases you won't ever have this problem).

Safari 2 escaped characters

  • Digg this article
  • Sphinn this article
  • Stumble this article
  • Facebook
  • del.icio.us
  • LinkedIn
  • Twit this article

Wednesday, 05 March 2008

Note to self: safari doesn't seem to like escaped characters being injected into an object within the DOM, seems to break them up.

So,

myObj.innerHTML = '<a onclick=\"do();\">execute</a>';

Comes out as...

<a onclick="; do(); ";>execute</a>

Doesn't happen in Firefox 2, IE6/7 or Safari 3 but fails in Safari 2.0.4

Prototype Trim()

  • Digg this article
  • Sphinn this article
  • Stumble this article
  • Facebook
  • del.icio.us
  • LinkedIn
  • Twit this article

Monday, 03 March 2008

Here's a nice little addon to the Prototype Ajax library that adds the ability to trim text, etc. with Prototype.

First add this to one of your .js include files,

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
    return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
    return this.replace(/\s+$/,"");
}

now with protoype loaded you can trim your text simply and effectivly,

$('myfield').value.trim() == '';

this will simply get the value from the textbox 'myfield', trim it for whitespace and then compare it to see if it's empty.

Sweet!

Thanks goes to SOMACON.COM for this one.

IE Debugging Tools

  • Digg this article
  • Sphinn this article
  • Stumble this article
  • Facebook
  • del.icio.us
  • LinkedIn
  • Twit this article

Monday, 25 February 2008

It's hard to do but these might help,

  • X-Ray, a bookmarklet to examine elements within the document model, similar to firebug's 'inspect'.

  • Fiddler, an http debugger for ie 6/7

  • IE Developer Toolbar, similar in power to firebug but in no way as comprehensive.

  • IETester, full-blown IE6 standalone browser, finally you can test against IE6 on Vista!

Prototype: if element exists + more

  • Digg this article
  • Sphinn this article
  • Stumble this article
  • Facebook
  • del.icio.us
  • LinkedIn
  • Twit this article

Wednesday, 20 February 2008

If Element Exists

Real quick, use this JS with Prototype to determine whether a particular DOM element exists,

if ($(element) == undefined) { alert('sorry not here'); }

If Not A Number

isNaN($(element)) => returns true if not a valid number

Overlapping Text in a Cell

First set the element's...

overflow: hidden;

Then to fix IE, set it's width...

width: 40px;

Programmatically..

$(element).style.overflow="hidden";
$(element).style.width="40px";

Form Elements

$F('firstname').value => returns value of form element
Updated

thanks Owen ;-)

Request.QueryString + Select Redirect

  • Digg this article
  • Sphinn this article
  • Stumble this article
  • Facebook
  • del.icio.us
  • LinkedIn
  • Twit this article

Thursday, 14 February 2008

Quick post, to handle parameters in your webpage via javascript, try this...

Request.QueryString with JS

Include the file in your header section then use like...

mypage.html?username=john

With the Javascript...

var name = '';
if (Request.QueryString("username").Count > 0) {
    name = Request.QueryString("username").Item(1);
}

The function returns the querystring as an object, so to determine whether you have any parameters returned count the number of objects. The first of which we want so we use .Item(1) to grab that and stick it in our variable name after which we can give to an alert() popup or whatever we need.

On Select Redirect with JS

Here's another bit, this will force the browser to redirect to another page once the user selects a value from the drop-down box and clicks the button image.

Javascript...

function goto(form) { 
var index=form.select.selectedIndex
    if (form.select.options[index].value.length != 0) {
        location.replace(form.select.options[index].value);
    }
}

Html...

<FORM NAME="form1">
<select name="select" id="select" style="width:90px;">
<option value="http://www.red91.com/">my site</option>
</select>
<img src="button.gif" onclick="goto(form1)" />
</FORM>

Injecting Elements After Load

  • Digg this article
  • Sphinn this article
  • Stumble this article
  • Facebook
  • del.icio.us
  • LinkedIn
  • Twit this article

Tuesday, 12 February 2008

Here's a javascript technique which you might need down the line and which helped me out a lot when handling a ppc event. Basically the code below allows you to execute a script that would normally be run on load, but here we run it when we want to; because say in this case you don't want to reload the page just for an extra script.

Injecting Scripts After Load

So,

var oScript = document.createElement("script");
oScript.src = "signed_up_user.js";
document.body.appendChild(oScript);

What this does is create a new script element and append it to the current page.

The createElement() bit defines what kind of object you're going to create,

  • img => image
  • a => hyperlink
  • script => javascript

...giving you all the properties related to that object, so to set the script for a script object we do...

oScript.src = "signed_up_user.js";

The appendChild injects the element into the area you specify within the DOM model, in this case the body.

!! Document.Write !!

Important note, you can't fire a Document.Write after the page has loaded, just won't work.

To add elements to your page use document.body.appendChild or Prototype / MooTools, which add some really efficient handlers for you to do this even faster and cross-browser.

Injecting Images After Load

We can also add an image generated off of some ppc script we've been given (big help if you've got googleppc to handle), like...

var oScript = document.createElement("img");
oScript.height = "1";
oScript.width = "1";
oScript.src = "some_ppc_script_function()";
document.body.appendChild(oScript);

In this case our image element is generated with the appropriate width & height, and then the source is put in from our ppc function that returns back an image element and injects it into the page.

All without refreshing the page, but more importantly when you add that script to the page after-load it IS processed!.

Hardcore AJAX ;-)

Have fun!

Cookies + Persistence in JavaScript

  • Digg this article
  • Sphinn this article
  • Stumble this article
  • Facebook
  • del.icio.us
  • LinkedIn
  • Twit this article

Monday, 04 February 2008

In this article we're going to play around with creating client-side cookies using JavaScript. First off here's a function to use which makes handling them easy.

JavaScript Cookie Library

var Cookie = {
  set: function(name, value, daysToExpire) {
    var expire = '';
    if (daysToExpire != undefined) {
      var d = new Date();
      d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
      expire = '; expires=' + d.toGMTString();
    }
    return (document.cookie = escape(name) + '=' + escape(value || '') + expire + '; path=/');
  },
  get: function(name) {
    var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
    return (cookie ? unescape(cookie[2]) : null);
  },
  erase: function(name) {
    var cookie = Cookie.get(name) || true;
    Cookie.set(name, '', -1);
    return cookie;
  },
  accept: function() {
    if (typeof navigator.cookieEnabled == 'boolean') {
      return navigator.cookieEnabled;
    }
    Cookie.set('_test', '1');
    return (Cookie.erase('_test') === '1');
  }
};

Usage

To create a cookie do,

Cookie.erase('mycookie'); Cookie.set('mycookie', 'myval', 365);

...365 is the days till expiry, we erase it before we set a new value just to be sure,

To erase,

Cookie.erase('mycookie');

To read a cookie,

var ii = Cookie.get('mycookie');

and if you get problems with bad numerics, try this,

var ii = Math.floor(Cookie.get('mycookie'));

or problems checking cookie exists, try this,

if (document.cookie.indexOf('mycookie=')>0) {

Persistence

Now persistence can be a pain in the rear if your cookies are getting cleared out when people navigate to somewhere else in your sites tree structure. So to make sure they stay around, set the path=/; this will force your cookies to be relevant right across your site. So if the person is in the photos area and then navigates down one they'll still be relevant and accessible via the functions above.

The function above does this already so you should be ready to roll if you use the code, ok my explanation's probably not 100% perfect but the codes working good this end, hope it does the same for you.

DOM + Setting Style

  • Digg this article
  • Sphinn this article
  • Stumble this article
  • Facebook
  • del.icio.us
  • LinkedIn
  • Twit this article

Monday, 07 January 2008

Quick little article for those hacking AJAX.

One of the powers of JavaScript is it's ability to let you change the property of elements within your webpage on-the-fly (the cornerstone of ajax).

So say you've got an element in your html like;

<span id="elem">some text</span>

Now if i wanted to make it strikethru in JavaScript I'd do...

<script type="text/javascript">
document.getElementById("elem").style.textDecoration="line-through";
</script>

Cool eh, your basically telling the DOM to hunt down any html element with the ID of 'elem' and then change it's CSS text style programatically.

NOTE: style is lowercase, not uppercase!