SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Member
    Join Date
    Feb 2008
    Location
    Sacramento
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Fine tuning my first event listener

    I've been intrigued by the concept of event listeners since I first heard of them, but I never really took the plunge before.

    Essentially, the project I'm working on is to launch one of 3 different popup routines based on the extension of a link. If the existing code already uses an onclick attribute, I want to ignore it (not have the listener over ride what's already coded).

    This code actually does what I need, but I feel that the listener may be made to be more efficient, and the function used in the listener call may be coded better also.

    Anyway, here goes... any suggestions for improvement would be welcome.

    Code:
    <html>
    <head>
    	<title>Link Listeners</title>
    	<script type="text/javascript">
    		/********************/
    		/* pre-defined functions */
    		/********************/
    	
    			function popup(url) {
    				alert("Popup function:\n\n\tURL = "+ url);
    				/* real code would go here */
    			}
    		
    			function popupDoc(url) {
    				alert("PopupDoc function:\n\n\tURL = " + url);
    				/* real code would go here */
    			}
    		
    			function popupPDF(url,title_string) {
    				alert("PopupPDF function:\n\n\tURL = " + url + "\n\tTITLE_STRING = " + title_string);
    				/* real code would go here */
    			}
    			
    			function popupImage(url,title_string) {
    				alert("PopupImage function:\n\n\tURL = " + url + "\n\tTITLE_STRING = " + title_string);
    				/* real code would go here */
    			}
    	
    		/************************/
    		/* end pre-defined functions */
    		/************************/
    		
    		// load my event handler into listener
    		addLoadListener(initEvents);
    		
    		/**************************/
    		/* My event handler for onclick */
    		/**************************/
    		function initEvents() {
    			var links = document.getElementsByTagName("a");
    			var thisExtension;
    			for (i=0; i<links.length; i++) {
    				if (!links[i].onclick) {
    					links[i].onclick = function() {
    						thisExtension = getExtension(this.href);
    						switch (thisExtension) {
    							case ".pdf":
    								popupPDF(this.href, this.title);
    								return false;
    								break;
    							case ".doc":
    							case ".xls":
    							case ".ppt":
    							case ".pps":
    								popupDoc(this.href);
    								return false;
    								break;
    							case ".jpg":
    							case ".gif":
    								popupImage(this.href, this.title);
    								return false;
    								break;
    							default:
    								alert("No popup assigned... link disabled for test purposes.");
    								return false;
    						}
    					}
    				}
    			}
    			return true;
    		}
    		
    		// used in my event handler to get the extension of the url
    		// yes, I know, it's not bulletproof, but satisfies the basic need for now
    		function getExtension(url) {
    			return url.substring((url.length)-4,(url.length)+1).toLowerCase();
    		}
    		
    		// listener function that I found somewhere.... not sure how efficient it is... there may be a better listener routine out there?
    		function addLoadListener(fn) {
    			if (typeof window.addEventListener != 'undefined') {
    				window.addEventListener('load', fn, false);
    			} else if (typeof document.addEventListener != 'undefined') {
    				document.addEventListener('load', fn, false);
    			} else if (typeof window.attachEvent != 'undefined') {
    				window.attachEvent('onload', fn);
    			} else {
    				var oldfn = window.onload;
    				if (typeof window.onload != 'function') {
    					window.onload = fn;
    				} else {
    					window.onload = function() {
    						oldfn();
    						fn();
    					};
    				}
    			}
    		}
    	</script>
    
    </head>
    
    <body>
    	<p><a href="contactlist.xls">Contact List</a></p>
    	<p><a href="resume.doc">Resume</a></p>
    	<p><a href="orgchart.pdf" title="Org Chart" onclick="popup(this.href); return false;">Organization Chart</a></p>
    	<p><a href="photo.JPG" title="Picture of our Fearless Leader">Photo</a></p>
    	<p><a href="http://www.disney.com/">Disneyland</a></p>
    	<p><a href="chart.pdf" title="Financial Chart">Financial Chart</a></p>
    </body>
    
    </html>
    Thanks for indulging me on my first listener project.
    -clarko

  2. #2
    SitePoint Addict
    Join Date
    Dec 2007
    Posts
    207
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Although lots of people use it and it was written by some smart people IMHO I think its overkill. Here is what I would use; supported by Yahoo's A Graded Browsers

    Code javascript:
    function addLoadListener(fn){
    	window.addEventListener ?
    		addEventListener('load', fn, false) :
    		attachEvent('onload', fn);
    }



    heh

  3. #3
    SitePoint Member
    Join Date
    Feb 2008
    Location
    Sacramento
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well that certainly is a lot simpler, and for my purposes (relatively controlled Intranet environment), if it is compatible with IE (mainly) and Firefox then I'm happy.

    Thanks,
    clarko

  4. #4
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,684
    Mentioned
    99 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by clarko View Post
    If the existing code already uses an onclick attribute, I want to ignore it (not have the listener over ride what's already coded).
    It's not possible to determine if addEventListener or attachEvent have already been used on a specified element. You can however check for the pseudo-javascript protocol (href="javascript:statement"), the event attributes (onclick="...") and traditional event registration (element.onclick = functionName

    Quote Originally Posted by clarko View Post
    any suggestions for improvement would be welcome.
    Each link is being given a vast amount of onclick code that can be greatly simplified by passing just the function name to the event.

    The function then can retrieve just what it needs.

    Consider this sample:

    Code Javascript:
    function popupPDF() {
        alert("PopupPDF function:\n\n\tURL = " +
            this.href + "\n\tTITLE_STRING = " + this.title);
        /* real code would go here */
        return false;
    }
     
    function linkDisabled() {
    	alert("No popup assigned... link disabled for test purposes.");
    	return false;
    }
     
    function initEvents() {
    	var links = document.getElementsByTagName("a");
    	var link;
    	for (i=0; i<links.length; i++) {
    		link = links[i];
    		// skip this link if event is already attached
    		if (link.onclick || link.getAttribute('onclick') ||
    			link.href.match(/^javascript:/i)) {
    			continue;
    		}
    		switch (getExtension(link.href)) {
    			case ".pdf":
    				link.onclick = popupPDF;
    				break;
    			// More cases here
    			default:
    				link.onclick = linkDisabled;
    				break;
    		}
    	}
    }
    Last edited by paul_wilkins; Feb 16, 2008 at 01:26.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  5. #5
    SitePoint Member
    Join Date
    Feb 2008
    Location
    Sacramento
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Each link is being given a vast amount of onclick code that can be greatly simplified by passing just the function name to the event.

    The function then can retrieve just what it needs.
    So, let me see if I understand... I see two main differences in the approach.
    1) Instead of creating a function each time through the loop to assign to the onclick event, the switch statement just assigns the onclick event to the corresponding function call.
    2) Instead of passing parameters to the function call, just call the function and use 'this' inside the function. I'll need to create clones of my existing popup functions, to preserve any legacy function calls that might exist on hundreds of web pages... that won't be a problem.

    All in all, the code you provided is leaner and more efficient than my original. Looks like I have a lot to learn about assigning function calls to events.

    Thanks for the response...
    clarko

  6. #6
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,684
    Mentioned
    99 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by clarko View Post
    All in all, the code you provided is leaner and more efficient than my original. Looks like I have a lot to learn about assigning function calls to events.
    You're welcome clarko.

    As Antoine de Saint-Exupery once said:
    Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


Bookmarks

Posting Permissions

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