Function Fails in Chrome


                function backspace_delete(e, delete_ele_id) 
		{
			if (!e) 
			{ 
				// IE reports window.event instead of the argument
				e = window.event;
			}
			var keycode;
			
			if (document.all) 
			{
				// IE
				keycode = e.keyCode;
			} 
			else 
			{
				// Not IE
				keycode = e.which;
			}
			
			if (keycode == 8 && with_field.value == '')
			 {
				if (document.all)
				{
					//IE
					removeElementById(delete_ele_id);
				} 
				else 
				{
					//Non IE
					removeElementById(delete_ele_id);
				}
			}
		}

I’m investigating the cause, but first a small note on the formatting of your code.

You may be used to putting brackets on the left in some other language, but in Javascript that is broken. In Javascript you should put brackets on the right to prevent the language from misunderstand you.

One of these works as expected, the other one doesn’t.


return {
    animal: 'dog',
    name: 'Doug'
};


return
{
    animal: 'dog',
    name: 'Doug'
};

Try to work out why one of them doesn’t work. It involves strange things like automatic-semicolon-insertion, designated code blocks, and strangely enough, labels.

JavaScript is one of the few languages where the formatting of your braces is not just a stylistic choice, it really does make a difference to whether your code runs or not.

I’ve attempted to also create some HTML and scripting code to use the above function, and in the process found that with_field is a variable that hasn’t been defined.

Do you have a simple test page that demonstrates the use of your function? Because we can provide advice on how to improve what you are doing there.

Paul… I’ll work on formatting my javascript properly from now on. I didn’t know you couldn’t change the “style” and I had no clue it would make a difference in the output. Anyway… to work out this chrome issue I made a JS fiddle. This really showcases the problem. Open the fiddle in firefox, hit backspace in the input field and you’ll see the div disappear. Open it in chrome and it’s a lost cause. I could really use your help on this.

Link to the JS Fiddle

Edit this Fiddle - jsFiddle - Online Editor for the Web (JavaScript, MooTools, jQuery, Prototype, YUI, Glow and Dojo, HTML, CSS)

The problem stems from Internet Explorer. Who would have guessed.

IE doesn’t fire the keypress event for special keys that don’t change the field value. Such special keys include delete, end, enter, escape, function keys, home, insert, pageUp/Down and tab. It seems that Webkit (used for Chrome and Safari) decided to be compatible with Internet Explorer in this regard.
Techy details: detecting keystrokes

The onkeydown and onkeyup events do fire for those special keys though.

So I suppose all I have to do is change it to an onkeydown function?

Try it out, what do you find?