SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Hybrid View

  1. #1
    SitePoint Member
    Join Date
    Jun 2012
    Posts
    19
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Is there a way to access a child target in a parent/ancestor event handler?

    I am trying to figure out if its possible to access a child target element from a parent event handler once the opportunity to handle the event has passed on the child element. For instance, if I had the following markup:

    Code:
    <div id="content">
        <a id="link1" href="#">Link to table of contents</a>
        <a id="link2" href="#">Link to chapters</a>
        <a id="link3" href="#">Link to appendix</a>
    </div>
    
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
    <script type="text/javascript">
        $content = $('#content');
        $content.click(
            function(e) {
                // how can I find the innermost target which triggered the click event?
            }
        );
    </script>
    I want to be able to access the <a> element that triggered the original click event. But instead of passing a separate function to each jQuery .click() method for "each" <a> I simply want to allow all 3 <a> event handlers to bubble up to the parent <div id="content"> and find out which <a> was clicked from the parent event handler and handle any of the 3 <a> click events from the 1 parent event handler. How would I do this...do I use the Event parameter to find this reference?

    Thanks for reading

  2. #2
    SitePoint Member
    Join Date
    Jun 2012
    Posts
    19
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    39 views and no help? I guess I'll have to answer my own question. I think I have the correct answer:

    answer: e.target

    Not sure how I missed this in the beginning. I guess I couldn't see the forest because of the trees in the way.

  3. #3
    SitePoint Guru whisher's Avatar
    Join Date
    May 2006
    Location
    Kakiland
    Posts
    732
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
    $content.click(
            function(
    e) {
                var 
    tgt e.target;
                
    console.log(tgt.id);
                
    e.preventDefault();
            }
        ); 


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
  •