SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Zealot
    Join Date
    May 2009
    Posts
    116
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question on this keyword

    Here's a link (since I am new to this forum I am not allowed to use the real url, so I used the word "LINK" instead):

    <p>Click <a href="LINK" id="nytimes">here</a> to visit NyTimes</p>

    The javascript resides in a external file and looks like this:

    window.onload=function()
    {


    function nt()
    {

    WHAT DO I WRITE H E R E????


    }


    if (document.getElementById("nytimes").attachEvent)
    {
    document.getElementById("nytimes").attachEvent("onclick",nt);
    }

    else
    {
    alert("something....");
    }


    }


    ----------

    I want to use the event listener, but how do I get the url from the link. I have tried different methods using this.href, but it will not work

  2. #2
    SitePoint Evangelist TommiChi's Avatar
    Join Date
    Oct 2008
    Posts
    440
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    When you add event listeners in the way that you are doing now, the "this" keyword gets interpreted differently; unless I am mistaken, "this" will return the window object, and therefore you always have problems identifying the target element in this way.

    Instead of using AttchEvent, you could use something like this:
    document.getElementById("nytimes").onclick = nt;

    The function below should return the HREF of the target element in an alert box, before navigating to that page:
    function nt() {
    alert(this.href);
    }

  3. #3
    SitePoint Zealot
    Join Date
    May 2009
    Posts
    116
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks TommiChi!
    I know that you could do it the way you're describing, I just wondered if you also could do it using an event listener like attachEvent.

  4. #4
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)


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
  •