SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    Awesome Addict
    Join Date
    Mar 2004
    Location
    Toronto, Canada
    Posts
    326
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Getting the thing that fired something

    I know all about using addEvent() or window.onLoad to apply events to specific things. However, a colleague of mine has run in to a problem that she can't seem to solve. Consider this:
    Code:
     function doSomething() {
     	e = e ? e : window.event;
    	console.log(this);
    	console.log(e.srcElement);
    	console.log(e.target);
     }
    
    <a href="#" onclick="doSomething(); return false">dosomething test event</a>
    The console logs produce:
    Code:
    1. Window test2.html
    2. e has no properties - console.log(e.srcElement);
    (break in script fired here -- 3rd log never gotten to)
    It's a simple question, but how can I reference "the thing that fired this function" within the doSomething function? Thanks!

  2. #2
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    function doSomething(e) {
    e = e || window.event;
    console.log(e);
    console.log(e.srcElement||e.target);
    }

  3. #3
    CSS & JS/DOM Adept bronze trophy
    Join Date
    Mar 2005
    Location
    USA
    Posts
    5,482
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The event object isn't being passed.

    Try this.
    Code:
    onclick="doSomething(event); return false"
    and pass "e" as an argument to the function.
    Code:
    function doSomething(e) {
    I recommend you read up on JavaScript Best Practices.
    We miss you, Dan Schulz.
    Learn CSS. | X/HTML Validator | CSS validator
    Dynamic Site Solutions
    Code for Firefox, Chrome, Safari, & Opera, then add fixes for IE, not vice versa.

  4. #4
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    function myOnClick(e)
    {
      e = e || window.event;
      var t = e.target || e.srcElement;
      // now t points to the element that was clicked
    }
    If you added the event listener like this:
    Code:
    window.onload = function()
    {
      document.getElementById('someEleId').onclick = myOnClick;
    }
    then, in the listener, "this" would also point to the element that was clicked.

  5. #5
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Wow - I was sure slow on the trigger!


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
  •