John Rand
John Rand

Reputation: 1034

jquery separate the onclick events of wrapped elements

I have an anchor link inside a div. I would like both the anchor link and div to process onclick events separately, but right now clicking on the anchor link also triggers the onclick event for the div. How do I prevent this?

Here's the code:

<html>
     <head>
     <style>
     #box {
          background-color: #ccffcc;
          width: 400px;
          height: 200px;
     }
     </style>
     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
     </script>
     <script type="text/javascript">
          $(document).ready(function() {
               $("#mailto").click(function(event) {
                    // correctly opens an email client if clicked
                    $("a[@href^='http']").attr('target','_blank');
                    return( false );
               });

               $("#box").click(function() {
                    // always goes to the home page, even if the #mailto id is clicked
                    window.location = '/index.php';
               });
          });
     </script>
     </head>
     <body>
     <div id="box">
          <a  href="mailto:[email protected]" id="mailto">[email protected]
    </div>
     </body>
</html>

Is there a way for me to stop execution of the code after the mailto is loaded?

Thanks!

John

Upvotes: 0

Views: 522

Answers (3)

Robert
Robert

Reputation: 21388

The event is bubbling up the DOM tree, e.stopPropagation(); will stop that.

$("#mailto").click(function(event) {
    event.stopPropagation();
    // correctly opens an email client if clicked
    $("a[@href^='http']").attr('target', '_blank');
    return (false);
});

$("#box").click(function() {
    // always goes to the home page, even if the #mailto id is clicked
    window.location = '/index.php';
});​

Fiddle http://jsfiddle.net/uwJXK/
About stopPropagation() http://api.jquery.com/event.stopPropagation/

Upvotes: 0

RobertPitt
RobertPitt

Reputation: 57268

you need to make sure your html is valid, so finish the a tag off:

<a href="mailto:[email protected]" id="mailto">[email protected]<a/>

and if that still causes problems try this.

$("#mailto").click(function(event)
{
    event.stopPropagation();
    if(event.srcElement == 'HTMLAnchorElement')
    { 
        //Process
    }
});

Upvotes: 0

Paul
Paul

Reputation: 1122

It might be due to your anchor not being closed properly. Or it certainly won't be helping

Upvotes: 0

Related Questions