Featured Post

Attaching a footer to the bottom of the page

I've been messing around with positioning a footer at the bottom of a page for a few hours now and finally after trial and error have a workable solution that seems to be cross browser compliant. My first thoughts were to absolutely position the footer element at the bottom of the page, but I knew that...

Read More

Replacing HTML character codes / escaped strings

Posted by chelfers | Posted in HTML, Javascript, Web | Posted on 17-07-2009

Tags: , ,

0

I've been coding web pages and applications for quite a few years using quite a few different languages. When I learn something so basic and fundamental I often wonder how much of a noob I really am, and then how many other developers are in my same shoes.

The problem I had was converting HTML character codes such as & # 35 ( apostrophe ) to its ascii equivalent. I've done this many times before, but have always been too lazy to find a different method. After searching through various blogs for a solution I finally came across a beauty.

.replace(/\&\#(\d+);?/g, function (m,n) { return String.fromCharCode(n); } )

A basic explanation of the code goes a little something like this; now this is a story all about how my life got flipped-turned upside down, and I liked to take a minute just sit right there, I'll tell ya how I became the prince of a town called Bel Air *record scratch*, err no wait.

Back on track, this function call does a couple of different things; first we are will search the entire string for every instance of our matches, and secondly we try to make our two matches ( yes two! ). The first match for our regular expression is looking for "&#"; this is our entry point into the search and should nab us every instance of those dang character codes. The second part of our match is the (\d+) sub expression, this is really what we are after and will give us the correct end result.

Once our expression has found a good match we will pass it to our callback function.

function (m,n) { return String.fromCharCode(n); }

The first thing you should notice are the m and n parameters that are being passed, these are tied directly to the matches and follow the order they were matched in, or in other words m = "&#", and n = [ our numerical match ]. These could really be variable name you wish, I stuck with the original example because that's how I rock out.

On the inside of our function we simply ignore the m parameter as we are only interested in the digits baby. We pass the n parameter to our Javascript function and BAM, straight up ascii conversion, what, WHAT.

As always, hope this helps someone :]

How to tell if a property exists in a JSON object

Posted by chelfers | Posted in Javascript, Web | Posted on 12-07-2009

Tags:

0

I usually don't claim to be an expert in anything, but that really depends on who I am talking to at the time. In my never ending crawl across the web trying to pick up the latest in web development I often come across blog posts or comments questioning how to tell if a property is set or not in a JSON object.

I'm not sure if the way I handle this is the best way, but it works for me and hopefully it will for you too. For this example I will simply make a function call and alert the result if it exists.

Dialog({ 'question':'can you hear me?' });

In this function call we are passing a simple JSON object with the 'question' property equal to 'can you hear me?'. Below is the function to alert our message and test if our properties are set.

function Dialog( setOptions ) {   setOptions = {         question : ( 'question' in setOptions ) ? setOptions.question : null,         answer   : ( 'answer' in setOptions ) ? setOptions.answer : 'No, type louder'   };   if ( setOptions.question != null ) { alert( setOptions.answer ); } }

The important part to pay attention to is the in statement. The bread-n-butta of this whole guy is 'question' in setOptions, or in other words, is the 'question' property residing in the setOptions object?

If the 'question' property is indeed passed we should get our defaulted answer. If we passed the 'answer' property initially with our 'question' property we could have set our own answer just like we did for the question answering our own question.

I'm sure there are many different ways of doing this, but like I said it works for me and so far I haven't required an alternative on any project I have worked on so far.

Keep your heads down and fingers flying!

Javascript href Voids and More

Posted by chelfers | Posted in HTML, Javascript, Web | Posted on 07-07-2009

Tags: , ,

2

- If you are a web developer raise your hand. *raises hand*
- If you have ever referenced Javascript for a link address raise your hand. *raises hand*

I'm sure there are many guilty developers out in the wild who use the age old classic

<a href="javascript:function();">Click Here</a>

A basic explanation is this little call tells the browser to call the function provided after "javascript:" when the link is clicked. Great, so we have an easy way to call a function using a link! What if I wanted the user to click the link and have the page do nothing? Easy!

<a href="javascript:void(0);">Click Here</a>

Awesome! Now when the user clicks the link the browser interprets void(0) as stop right there, don't do a thing. The problem is "javascript:" wasn't exactly meant for this sort of use and some quirky stuff can happen ( obviously the keyword is there for a reason, but that does not make it a good one).

So what is the solution? Our trusty old pound sign, an onclick trigger, and of course a tiny bit of Javascript.

<a href="#" onclick="return false;">Click Here</a>

This will give the same end result as using void(0) and it is the correct way supported by all major browsers; hell some browsers specifically state to avoid "javascript:" in any link addresses, but this is the web, who sticks to standards?

If you really want to be anal about the whole thing and want to argue about Javascript being enabled on the browser ( which you should be sniffing for anyways if you really care that much ) you could do the following.

<a href="backupFunctionalityPage.php" onclick="YourFunction(); return false;">Click Here</a>

This will take the user to the page set by the href if and only if Javascript is disabled, but then I ask myself why not just push them to that page as the default?

Anyway, here is an example showing the bad and better ways of doing this for those that might need a side by side.

<script type="text/javascript">   function Testing(){ alert('hio'); } </script> //BAD <a href="javascript:Testing();">Click Here</a> //Better <a href="#" onclick="Testing(); return false;">Click Here</a> //BAD <a href="javascript:void(0);">Click Here</a> //Better <a href="#" onclick="return false;">Click Here</a>

Hope everyone had a good 4th of July weekend!

Google Javascript Library CDN

Posted by chelfers | Posted in AJAX, JQuery, Javascript, Javascript Libraries, Web | Posted on 04-07-2009

Tags: , , , ,

0

I have a bad habit of clicking the 'view source' option on any page I find remotely interesting or flashy to take a gander at the CSS and Javascript. I am amazed how often I see so many non-compacted includes for CSS and Javascript alike, and not only non-compacted but more often than not more includes than I can count on my two hands.

I understand if you have a simple site with low traffic; you might not really care about bandwidth, or how long it takes your users to load the page, or hell you probably don't even have a test site so it's a pain in the ass to keep track of multiple versions. My issue is with large sites with thousands of visitor a day with 10 include files ranging in thousands of lines of code, non-compacted files, and not a single CDN. I would venture to guess that any site banking on its visitors probably has a test site and most likely even a development site - there really is no excuse except laziness.

How hard is it to throw all of your Javascript in one file, obfuscate and compact it, reduce the overall file size by more than 50%, and reduce the overhead that comes with downloading multiple includes for your users? Sounds like a long process but with programs such as Yahoo Compressor it's actually one simple step.

This was suppose to be a post about Google hosting most of the popular Javascript libraries, but man I suck at not ranting sometimes.

Time for the goods!

Unless you really feel the need to modify any of these libraries there really isn't a good reason why you should not be using the Goog as a free CDN for your most used content. Obviously if you already have your own CDN this post is not meant for you but for the average llamas out there go-to-this-link.

Google AJAX Libraries API

Now because I'm a JQuery fan-boy I will post the easiest way to get it rolling on your site in the compacted version, because again, your site has no real reason to be running any other version.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

Ta-da! All of your beautiful plugins still work, and best of all you get the help of big brother to serve up your content.

jQuery Delay

Posted by chelfers | Posted in JQuery, Javascript, Javascript Libraries, Web | Posted on 02-07-2009

Tags: , ,

14

Happy Note: I was contacted by the jQuery team and my code is being added to the core functionality; that really made my day!  You will want to remove the current code from your site if you plan on upgrading to the latest release of jQuery - can see the official landing here.


Today in my attempt at sexifying a project with a simple fade out saved message I wanted a cleaner way to delay my fade.

When the user clicks the save button an ajax call is made and the data is saved, the returning JSON data includes a savedOn property which I then place in my blank div. After 20 seconds the "Saved On [date]" gently fades away and all is good.

My current method for calling this timed-fading functionality was something along the lines of this :

setTimeout( "$('+ selector +').fadeOut('slow', function(){ $(this).html('').fadeIn(); });", 20000 );

This basically took my div and faded it out, once faded the div was made blank again, and finally faded the blank div back in so the next time the user clicked save the text would actually appear.

So while that worked great I needed to reuse the code in various other places multiple times, and after some browsing on jQuery's site I found the queue and dequeue references. *Choir singing while hands are raised to the sky*

It appears that all fx ( and well basically everything else ) functionality like .show, .addClass, .fadeIn, all are put in a queue and ran through from start to finish; using the .queue function we can modify the way we run through the list, and well I'm sure you see where I am going with this.

As soon as I read that I could add my own function to the queue of my choice the first thing that jumped into my head is a simple timer that calls the dequeue method after a time I specified. Damn, could it be that simple?

.queue accepts two arguments: name, and of course the callback. The name arguments is the queue you wish to play with, in my case it will probably be the "fx" queue 100% of the time. The callback of course is our ticket to winnersville ( not to be confused with wienersville ).

As an example, the following code will .fadeOut the div five seconds after the function is called.

$(selector).delay(5000).fadeOut('slow');

And to show how the chaining works try this one out. It should fade the element after five seconds, and five seconds later fade it back in.

$(selector).delay(5000).fadeOut('slow').delay(5000).fadeIn('slow');

The great thing about it is the placement of the function operates just like any other fx function; it is executed linearly and there is no "chaining" using callsbacks or hacky animation scripts to try and work around a timer like so many other delay functions do.

Download jQuery Delay 1.0.0
Download jQuery Delay 1.0.0 minified

Enjoy :]

jQuery and Forms

Posted by chelfers | Posted in JQuery, Javascript, Javascript Libraries, Web | Posted on 30-06-2009

Tags: , ,

0

On my latest searches for various ways jQuery interacts with the DOM, and more importantly forms for my recent project I've found that various sites could answer some of my questions but most focused on single form elements and not much more.

jQuery can access elements in quite a few different ways, such as by tag name and css class; I often find myself selecting elements based on ID more than anything. A function many people are probably familiar with is the $() function; aside from just looking completely awesome it is a huge time saver in terms of typing.

What I consider to be the "original" $ function was simply a quick shortcut for typing out document.getElementById(element); of course now it has grown far beyond that and many Javascript libraries use it as an entry point to their objects.

//this is not the jQuery $() - simple syntax is $('element') and from there you can //manipulate it how you like $('element').value, $('element').innerHTML, //$('element').style.cssText, etc - this function only accepts IDs function $() {    var elements = new Array();      for (var x = 0; x < arguments.length; x++) {           var element = arguments[x];                if ('string' == typeof element){ element = document.getElementById(element); }                if (arguments.length == 1){return element};           elements.push(element);      }      return elements; }

A simple and beautiful ( especially if you don't want to run the jQuery library ) function that will take one or many IDs and pass them back as a single result or an array. But anyways, enough with the jib-jab on with the examples!

Text Box
<input type="text" id="text_1" class="HappyCow" value="" /> <input type="text" id="text_2" class="HappyCow" value="" /> <input type="text" id="text_3" class="MadCow" value="" />
//set a value for the given text box $('#text_1').val('test'); //set a value for the given text box - traditional method $('#text_1')[0].value = 'test'; //get a value for the given text box var test = $('#text_1').val(); //get a value for the given text box - traditional method var test = $('#text_1')[0].value; //set a value for every textbox with the HappyCow class $('.HappyCow').val('Moooo');
Check / Radio
<input type="radio" id="radio_1" name="group_1" class="HappyCow" value="1" /> <input type="radio" id="radio_1" name="group_1" class="HappyCow" value="1" /> <input type="radio" id="radio_1" name="group_1" class="HappyCow" value="1" />
//is the element checked? - result: 1 or 0 var test = $('#radio_1:checked').length; //is the element checked? - result: true or false var test = $('#radio_1').is(':checked'); //is the element checked? - result: true of false var test = $('#radio_1')[0].checked; //check the element $('#radio_1').attr('checked','checked'); //what is the value of the checked option in the group? var test = $('.HappyCow:checked').val()
Selectbox
<select id="select_1">   <option value="1">one</option>   <option value="2">two</option>   <option value="3">three</option> </select>
//select the option that matches the value provided $('#select_1 option[value=1]').attr('selected', true); //get the selectedIndex - note the first element is 1 var test = $('#select_1 option[selected]').val(); //how about something even easier? var test - $('#select_1').val(); //get the selectedIndex - traditional method, first element is 0 var test = $('#select_1')[0].selectedIndex;

Hope this helps someone out!