SitePoint Sponsor

User Tag List

Results 1 to 4 of 4

Hybrid View

  1. #1
    SitePoint Zealot
    Join Date
    Nov 2007
    Posts
    102
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    attachEvent - this keyword problem

    I know, i have been searchin the forums, and i did find some results on this subject, but i still don't know exactly how to work this out.

    The problem is, that i'd like to use attachEvent, and inside event listener i'd use THIS keyword. BUt from what i get, i is refering to global object instead of object that function was called upon.

    From what i understand, to corect this, i would need to somehow call this event listener function as a method/property of target element, but whatever i do, i can't achive this. So can somebody write a verry simple example how this would work the same way as in w3c browsers?
    Tnx.

  2. #2
    SitePoint Addict
    Join Date
    Dec 2007
    Posts
    358
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    FireFox example:
    Code:
    <button id="btn">Click me</button>
    <script type="text/javascript">
    function listener(event) {
      alert(event.target.textContent);
    }
    document.getElementById('btn').addEventListener("click", listener, true);
    </script>
    IE example:
    Code:
    <button id="btn">Click me</button>
    <script type="text/javascript">
    function listener(event) {
      alert(event.srcElement.innerText);
    }
    document.getElementById('btn').attachEvent("onclick", listener);
    </script>
    I'm creating trouble-free Apache, PHP, MySQL installer, WITSuite,
    and use it to setup my development environment.
    Demo, support, contact. Questions?

  3. #3
    SitePoint Zealot
    Join Date
    Nov 2007
    Posts
    102
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    ok tnx a lot.
    Is there any way to make it work with THIS keyword?
    So that you could write this.style.....?

  4. #4
    SitePoint Addict
    Join Date
    Dec 2007
    Posts
    358
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Only with this one:
    Code:
    <button id="btn">Click me</button>
    <script type="text/javascript">
    function listener(event) {
      alert(this.innerText);
    }
    document.getElementById('btn').onclick = listener;
    </script>
    I'm creating trouble-free Apache, PHP, MySQL installer, WITSuite,
    and use it to setup my development environment.
    Demo, support, contact. Questions?


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
  •