Posts Tagged ‘JavaScript’

I just created a JavaScript method that sorts a JavaScript object by key name case insensitive. Source at https://gist.github.com/CFJSGeek/5550678.

/**
 * Sort JavaScript Object
 * CF Webtools : Chris Tierney
 * obj = object to sort
 * order = 'asc' or 'desc'
 */
function sortObj( obj, order ) {
	"use strict";

	var key,
		tempArry = [],
		i,
		tempObj = {};

	for ( key in obj ) {
		tempArry.push(key);
	}

	tempArry.sort(
		function(a, b) {
			return a.toLowerCase().localeCompare( b.toLowerCase() );
		}
	);

	if( order === 'desc' ) {
		for ( i = tempArry.length - 1; i >= 0; i-- ) {
			tempObj[ tempArry[i] ] = obj[ tempArry[i] ];
		}
	} else {
		for ( i = 0; i < tempArry.length; i++ ) {
			tempObj[ tempArry[i] ] = obj[ tempArry[i] ];
		}
	}

	return tempObj;
}

img Element error Event

Posted: January 8, 2013 in JavaScript
Tags: , , , , , ,

If you develop and push to production, you most likely have experienced broken images on your dev instance. You may have also run into broken images on production due to user/admin error, etc. Wouldn’t it be nice if you could display a default placeholder image without having to take a hit on your file system, checking to see if it exists, before your load each image?

Thanks to Ryan Stille’s recent blog post, I have been made aware of a (not so great) solution. Apparently the img tag, along with others such as object, script and style have error events. We can listen for the error event and load a placeholder image in place of the default browser error image.

The catch is the event handler must be attached before the browser fires the error event. Also, the error event may not be correctly fired when the page is served locally. The error event relies on HTTP status codes and will generally not be triggered if the URL uses the “file:” protocol.

In┬ásimpler┬áterms, the only solution I’ve found is to either place the event handler inline with the img tag, assign the img src via JavaScript or recursively search each image’s complete state or naturalWidth once the window is done loading. I’ve tried using “$().on()” and “$(“img”).error()” both after the document loads and inline before the element is loaded. However neither solution works, which doesn’t make much sense to me.

I am including multiple examples because this is not a one-solution-fits-all scenario.

The first working example displays a placeholder image using the inline method if the error event is thrown. Notice the onerror handler is reset when it’s run so you don’t run into an infinite loop if your placeholder image also fails.

<img src="images/myImage.jpg" alt="My Image" onerror="imageError(this)">

<script>
function imageError(element) {
    element.onerror='';
    element.src='/images/imgPlaceholder.png';
}
</script>

The second working example, also using the inline method, will call a script that will report the broken image and load the placeholder. The script returns an image with the proper image MIME type.

<img src="images/myImage.jpg" alt="My Image" onerror="imageError(this)">

<script>
function imageError(element) {
    element.onerror='';
    element.src='logBrokenImage.cfm?image=' + element.src';
}
</script>

The third working example uses JavaScript to load the image and displays a placeholder if that image fails to load.

<img id="myImage">

<script>
    $('img').one( 'error', function() {
        $(this).attr( 'src', '/images/imgPlaceholder.png' );
    });

    $('#myImage').attr( 'src', 'myImage.jpg' );
</script>

The final working example recursively searches through each image after the window loads. If it finds the state incomplete or the natural width of the image is 0, then it loads the placeholder image.

<img src="images/myImage.jpg" alt="My Image">

<script>
$(window).load(function() {
    $('img').each(function() {
        if ( !this.complete || ( !$.browser.msie && ( typeof this.naturalWidth == "undefined" || this.naturalWidth == 0 ) ) ) {
            this.src = '/images/imgPlaceholder.png';
        }
    });
});
</script>

I’ve used FCK Editor for years, but now with the FireFox 17+ incompatibility it’s time to upgrade to CKEditor.

I ran into some “stupid challenges” along the way. For example I tired out my brain trying to get it to work with jQuery. It appears in CKEditor v3.x there was a jQuery adapter. But in version 4 it wasn’t included. I tried to reuse it, but that seems to fail horribly for me. So I finally gave up on that concept. If anyone has a good way to implement jQuery with CKEditor I’d love to hear from you!

To get things rolling a just call the ckeditor.js file and add the class “ckeditor” to my textarea.

<form>
    <textarea class="ckeditor" id="noticeMessage" name="message"></textarea>
</form>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>

Now I want to verify that there’s actual text entered. To do that I remove all HTML markup and return the length of the string returned from the CKEditor API. The “noticeMessage” for the “instances” variable is the ID of the “textarea” element.

<form>
    <textarea class="ckeditor" id="noticeMessage" name="message"></textarea>
</form>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<script type="text/javascript">
    $("form").submit( function() {
        var messageLength = CKEDITOR.instances['noticeMessage'].getData().replace(/<[^>]*>/gi, '').length;
        if( !messageLength ) {
            alert( 'Please enter a message' );
        }
    }
</script>

Now if we test this with the word “test” it returns 5 characters. Well that’s not good, because last I knew math “test” only contains 4 characters. If we remove “test”, the correct value of 0 is returned. In this case it really doesn’t matter much because I’m just looking to see if anything is there. But it was annoying me and could prove bad in the future for further tests if I forgot about the issue.

The reason for this is if you view the source it inserts a line return automatically during editing. Normally I can fix this quite easily with jQuery, but because that concept made my head explode, I had to find a different way.

The trim() method didn’t come along in JavaScript until version 1.8.1. So while my current browser users are okay, my older browsers users such as IE8 aren’t so lucky.

To resolve this issue, I test for the “trim()” prototype method. If it doesn’t exist I extend the String prototype object with a trim() method. So thanks to some guy with the alias “Timo” I’ve put this thinking into place. The length result of string “test” now returns an accurate value of 4.

<form>
    <textarea class="ckeditor" id="noticeMessage" name="message"></textarea>
</form>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<script type="text/javascript">
    /**
     * Compatibility fix for trim()
     * Browsers 3.5+, Safari 5+, IE9+, Chome 5+ and Opera 10.5+ support trim() natively
     * So we're detecting it before we override it
     * This is here because CK Editor isn't playing nice with jQuery
     * Thanks to http://blog.stevenlevithan.com/archives/faster-trim-javascript
     */
    if(!String.prototype.trim) {  
        String.prototype.trim = function () {  
            var c;
                 for (var i = 0; i < this.length; i++) {
                     c = this.charCodeAt(i);
                     if (c == 32 || c == 10 || c == 13 || c == 9 || c == 12) continue; else break;
                 }
                 for (var j = this.length - 1; j >= i; j--) {
                     c = this.charCodeAt(j);
                     if (c == 32 || c == 10 || c == 13 || c == 9 || c == 12) continue; else break;
                 }
                 return this.substring(i, j + 1);
        };  
    }

    $("form").submit( function() {
        var messageLength = CKEDITOR.instances['noticeMessage'].getData().replace(/<[^>]*>/gi, '').trim().length;
        if( !messageLength ) {
            alert( 'Please enter a message' );
        }
    }
</script>