www.webdeveloper.com
Results 1 to 7 of 7

Thread: Passing Variables not working

  1. #1
    Join Date
    Feb 2005
    Location
    Norwich, UK
    Posts
    140

    Passing Variables not working

    Hi, this is probably quite a basic one, but I'm struggling to get an argument passed in to a function successfully.

    When I do this, the code doesn't execute:
    Code:
    document.onclick = newTarg(5);
    document.ondblclick = newTarg(10);
    
    function newTarg(spd) {
    	alert('Working = '+spd);
           // More code here
    }
    Doing this instead works fine:
    Code:
    document.onclick = newTarg;
    
    function newTarg() {
    	alert('Working');
           // More code here
    }
    Any ideas why it won't let me pass a variable in? I've never really formally learnt Javascript so this is getting a bit frustrating...

  2. #2
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,672
    document.onclick = function(){newTarg(5);}
    document.ondblclick = function(){newTarg(10);}

  3. #3
    Join Date
    Feb 2005
    Location
    Norwich, UK
    Posts
    140
    Excellent, thanks

  4. #4
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,672
    anytime ))

  5. #5
    Join Date
    Feb 2005
    Location
    Norwich, UK
    Posts
    140
    Just to help me learn(!), why did that work?

    Seems weird that it happily called newTarg, but only until I needed to pass a value in to it...

  6. #6
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,672
    my english is not good enough for explaining, just take a look at this article (DOM element properties, DOM Event interface) or try to find smth alike to read in english

  7. #7
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,273
    With a document.onclick you affect a function, not a function call, on the onclick event !

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles