Category: Javascript

 | Javascript | 0 Comments

It's been quite some time since I did any Flash, besides so much has changed since then that I doubt I could make anything spectacular anymore.

However, in the meantime I've been having a look at the new <canvas> tag, which in my opinion does alot of interesting graphics stuff for JavaScript. Nothing super fancy, but fun to play around with anyway.

Here's a simple example that draws two intersecting rectangles, one of which has alpha transparency:


<script type="application/x-javascript">
function draw_rects() {
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");

    ctx.fillStyle = "rgb(200,0,0)";
    ctx.fillRect (10, 10, 55, 50);

    ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
    ctx.fillRect (30, 30, 55, 50);
}
</script>

<canvas id="canvas"></canvas>

 

Some related links:

 | Javascript | 0 Comments

Let's say that you want to insert a node somewhere in the DOM, but if it is a string, then you want to insert it automatically as a text node. Here is how you might want to achieve this:


function checkElem(elem)
{
    // If only a string was provided, convert it to a Text Node
    return elem && elem.constructor == String ?
        document.createTextNode(elem) : elem;
}

Borrowed from the book Pro JavaScript Techniques by John Resig.
 | Javascript | 0 Comments

Let's say that you want to select a random link within a certain div tag which has a given id and then jump to where that link points to. Here's a way to do that.


function random_link(id)
{
    var obj = document.getElementById(id);
    var links = obj.getElementsByTagName("a");
    var offset = Math.floor(Math.random() * links.length);
    document.location = links[offset].href;
}
 | Javascript | 0 Comments
typeof(NaN) == 'number'

NaN stands for 'Not a Number' but as you can see it is a 'number' nonetheless.

null is a value that isn't anything.

undefined is a value that isn't even that.

A variable can be both defined and have a value of undefined at the same time.

boolean("0") = true

boolean("false") = true

+"42" = 42

!! produces a boolean

All of the above have been taken from the following video tutorial.
 | Javascript | 0 Comments

Today I learned that there is more than one way to implement Ajax, namely:

  • using a hidden frame
  • using a hidden iFrame
  • calling ActiveXObject() for IE6 or earlier
  • calling XMLHttpRequest() for all other browsers
  • using a third party library like zXML or DWR
  • creating dynamic images by using new Image() on the fly
  • dynamic script loading by using document.createElement("script")

The book I am reading is called Professional Ajax.

 | Javascript | 2 Comments | 0 TrackBacks

So I decided to be clever again, but this time around in an unusual javascript kind of way.

Do you see all of those links down the left and right columns? Well, if you have javascript enabled in your browser, then you should see a bunch of messed-up looking links which are randomly sized, some bold, some italic and others just plain old normal.

For those lucky enough to be knowledgeable in the fine art of Dynamic HTML, I will reveal my secret.

Here it is:

<script type="text/javascript">
// Creates random fontsize, bold, italic or normal for links.
function resize_menu_links(class_name, h2_names, min, max) {
  var divs = document.getElementsByTagName('div');
  for (var i = 0; i < divs.length; i++) {
    if (typeof(divs[i].className) == 'string' && divs[i].className == class_name) {
      var h2s = divs[i].getElementsByTagName('h2');
      if (h2s && is_in_array(h2_names, h2s[0].innerHTML)) {
        var a_links = divs[i].getElementsByTagName('a');
        for (var j = 0; j < a_links.length; j++) {
          var fs = min + Math.floor(Math.random()*(max-min+1));
          a_links[j].style.fontSize = fs+'px';
          var rx = Math.floor(Math.random()*4);
          if (rx == 1) { // bold
            a_links[j].style.fontWeight = 'bold';
          } else if (rx == 2) { // italic
            a_links[j].style.fontStyle = 'italic';
          } else if (rx == 3) { // both
            a_links[j].style.fontWeight = 'bold';
            a_links[j].style.fontStyle = 'italic';
          }
        }  
      }
    }
  }
}

The function is_in_array checks to see if a given string matches one of the elements of the array, returning true or false.

function is_in_array(the_array, what) {
  for (var i = 0; i < the_array.length; i++) {
    if (the_array[i] == what) return true;
  }
  return false;
}

Finally, I use the standard setTimeout function to make sure that the changes are made once the page has been loaded, waiting 50 milliseconds before firing off the function resize_menu_links , passing the array of allowed section strings as well as the range of font sizes, in this example 9-17px.

// Only for titles given in 2nd array parameter.
setTimeout("resize_menu_links('menu_subsection', ['Categories', 'More links', 'Archives', 'More entries'], 9, 17)", 50);
</script>

Do you have javascript enabled?

The answer is:

 | Javascript | 0 Comments

Found at The JavaScript Source

 | Javascript | 3 Comments

So you thought that you knew everything there was to good old javascript did you? Well then, check out the slayeroffice web site first and then ask yourself again whether or not you are such a big shot afterall.

Personally, I found the Mouseover DOM Inspector the most impressive of all.

 | Javascript | 5 Comments

Don't you just hate it when you include some external piece of (javascript) code from another site, and it breaks up the layout of your web page?

This is the problem I've been having with Blogsnob. The kind folks there provide a free service for members of the blogging community, enabling you to increase your blog's exposure via simple text-based ads.

All you have to do is insert the following code somewhere and hope everything works out okay:

<script src="http://blogsnob.idya.net/ad.php?id=n"
  type="text/javascript"></script>

I have placed this at the very bottom of my right-hand margin. This margin is set to a width of around 160 pixels and it is meant to stay that way.

The only problem with inserting this piece of code is that you do not know ahead of time how much text and/or images might be thrown into your site. Now I trust the service for what it is, and most of the time it seems to be working alright. However, sometimes I get really long words containing say 50 characters in a row. This breaks up my layout. In order to accommodate this exceptionally long word, the poor 160 pixel wide margin is expanded so that a much larger vertical bar appears. You see, HTML has no character wrapping, only word wrapping at the white-space borders. My main content area is covered up on the right side and shifted to the left. Bummer, man.

So what's a poor soul like myself going to do? Well, I have chosen to solve this using good old Javascript based on the DOM-interface. Here is what I do. First of all, I bracket the inserted code above like this:

<div id="blogsnob">
<script src="http://blogsnob.idya.net/ad.php?id=n"
  type="text/javascript"></script>
</div>

Note that I have wrapped the ill-behaved section of code with another div-tag and I have labeled it "blogsnob" accordingly.

Then just right after the spot where I have inserted the code above, I add the following function call:

<script language="javascript" type="text/javascript">
<!--
mxw("blogsnob");
//-->
</script>

Alright, so what does this magical function called mxw() really do? Well, it looks within the div-tag that I labeled as "blogsnob", recursively parses through the nodes and child-nodes, and grabs each TEXT-element. If it then finds any words which are longer than a pre-defined maximum length, say 20 characters (mxw_max = 20;), then it will truncate this bugger to this given length. Pretty neat, huh?

Just in case you were curious what this function looks like, and assuming that you not only have a good knowledge of Javascript, but also at least some limited experience with that thing called DOM, then here it is:

<script language="javascript" type="text/javascript">
<!--
// Maximum allowed length of text words.
var mxw_max = 20;
//
// mxw(id)
//
// Wrapper function which checks that certain DOM
// is supported before calling recursive mxw2(). 
//
function mxw(id)
{
  if (!document.getElementById) return;
  var n = document.getElementById(id);
  if (!n || !n.nodeType) return;
  mxw2(n);
}
//
// mxw2(id)
//
// Checks all text of given node and all its
// descendant nodes, truncating each word that
// is longer than allowed length mxw_max. This
// is an extra safety valve preventing unwanted
// overrun, e.g. of sidebars and/or margins.
function mxw2(n)
{
  if (n.nodeType == 3 /*Node.TEXT_NODE*/)
  {
    var flag = 0;
      var words = n.data.split(" ");
    for (var i = 0; i < words.length; i++)
    {
      if (words[i].length > mxw_max)
      {
        flag++;
        words[i] = words[i].substr(0, mxw_max-2) + ". "; 
      }
    }
    if (flag > 0) n.data = words.join(" ");
  }
  var children = n.childNodes;
  for (var i = 0; i < children.length; i++) mxw2(children[i]); 
}
//-->
</script>

Hope you like it and find it useful for your own web pages somewhere. You're welcome.

 | Javascript | 3 Comments

Here's some more javascript stuff which you too can use in order to achieve yet another truly amazing affect. Boggle the minds of your readers and make new friends. Just click on the following button to find out for yourself:

Recent Assets