Results 1 to 3 of 3

Thread: How to change Javascript to work with IE

Threaded View

  1. #3
    I'm about to be a PowerPoster!
    Join Date
    Jan 2005
    Location
    Everywhere
    Posts
    13,647

    Re: How to change Javascript to work with IE

    The code should work in Internet Explorer versions 9+. In earlier versions the non-standard 'attachEvent' method must be used instead of 'addEventListener'.

    Also, I recommend attaching all event listeners using JavaScript instead of HTML attributes. This keeps behaviour and presentation as separate as possible.

    With those things in mind, here is how I would restructure the code:

    Code:
    function listen(who, event, callback)
    {
    	if (who.addEventListener)
    		who.addEventListener(event, callback, false);
    	else if (who.attachEvent)
    		who.attachEvent('on' + event, callback);
    }
    
    function createListener()
    {
    	var handler = function(event) {
    		var element = event.target;
    		if (element !== document.body)
    		{
    			if (element.className === '')
    				element.className = 'highlight';
    			else
    				element.className = '';
    		}
    	};
    	
    	listen(document, 'click', handler);
    }
    
    listen(document, 'ready', createListener);
    Untested, so there might be some typos.


    Edit: The document.ready listener isn't required in this particular case because you can attach the document.click listener immediately, but I added it as an example of an alternative to your original 'onload' method.
    Last edited by penagate; Nov 7th, 2012 at 08:10 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width