SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Guru tictike's Avatar
    Join Date
    Apr 2008
    Location
    Canada
    Posts
    863
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    question about passing arguments

    This is a part of a script I have....

    Code:
    function initNav(){
    	var navLinkDiv = document.getElementById("nav");
    	var navLinks = navLinkDiv.getElementsByTagName("a");
    	
    	for(var i = 0; i<navLinks.length; i++){
    		navLinks[i].onmouseover = changeliststyle;
    		navLinks[i].onmouseout = changelistback;
    	}
    }
    
    function changeliststyle(){
    	var obj = this;
    	if(window.opera){
    		return false;
    	}
    	obj.parentNode.style.listStyleType="square";
    }
    Before I settled on this code I tried passing 'this' to function changeliststyle (instead of declaring var obj = this;] but it didn't work. Can someone please tell me why the following code didn't originally work for me? Thanks.

    .
    .
    .
    navLinks[i].onmouseout = changeliststyle(this);
    }
    }

    function changeliststyle(obj){
    if(window.opera){
    return false;
    }
    obj.parentNode.style.listStyleType="square";
    }[/CODE]

  2. #2
    SitePoint Evangelist
    Join Date
    Jul 2007
    Posts
    345
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    navLinks[i].onmouseout = changeliststyle(this);
    The above code will call changeliststyle immediately and assign the return value to the onmouseout handler.

    To enforce the context you could wrap the event handler in a function
    Code:
    for(var i = 0; i<navLinks.length; i++){
      (function(i){
         navLinks[i].onmouseover = function(){changeliststyle(navLinks[i]);};
         navLinks[i].onmouseout = function(){changelistback(navLinks[i]);};
      })(i);
    }
    If you have lots of list items, you could consider event delegation. Attach the event handler to the list itself rather than the links, then identify which child element fired the list event. One event handler is often better than many.


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
  •