0

I have two HTML elements that appear one over another, each having its own onclick event. Code example:

<table>
  <tr>
    <td onclick="expand('table2')">
      <div>
        name<img src="img.gif" onclick="open_popup()">
      </div>
    </td>
  </tr>
  <tr>
    <td>
      <table id="table2"><tr><td>some text</td></tr></table>
    </td>
  </tr>
</table>
<script type="text/javascript">
function expand(tableid){
   $("#"+tableid).slideToggle();
}
function open_popup(){
   alert('popup opened');
}
</script>

The problem is that if I want to click the image and open the popup, it also triggers the "expand" function, so is there any way or any suggestion that I might use to make the click on the image to trigger only the image event, without also triggerin the "expand" function? I am looking for a solution that doesnt require me to change current layout.

My goal is to make the image click trigger the open_popup() function, while any click around the image, but inside the table row, to trigger the other function.

Thank you

Coding Enthusiast
  • 3,865
  • 1
  • 27
  • 50
NVG
  • 3,248
  • 10
  • 40
  • 60
  • ve u tried to add event.stopPropagation() to the open_popup function?? – Vanojx1 Jul 14 '15 at 15:56
  • I agree about event.stopPropagation(). Here is a good explanation for you: http://stackoverflow.com/questions/5963669/whats-the-difference-between-event-stoppropagation-and-event-preventdefault#5963688 – nancyolson531 Jul 14 '15 at 15:59
  • You will need to stop the propagation or "bubbling" of the event. Have a read through these: http://stackoverflow.com/questions/387736/how-to-stop-event-propagation-with-inline-onclick-attribute – Cᴏʀʏ Jul 14 '15 at 16:00
  • 1
    @CodingEnthusiast if you've been around long enough you should know a table within a table isn't anything unusual and a lot of websites have been built like until about 7/8 years ago. – Miguel M. Jul 14 '15 at 16:00
  • Thank you for the info. I will try the stop propagation. – NVG Jul 14 '15 at 16:05

1 Answers1

2

I believe that the issue your having has to do with the the click event propagating up.

What your going to want to do is add event.stopPropagation() to your functions. So your function should look like this:

function open_popup(event){ 
    event.stopPropagation();
    alert('popup opened');
}

Here is a link for more information on propagation: Event - stopPropagation Docs

Coding Enthusiast
  • 3,865
  • 1
  • 27
  • 50
DominicValenciana
  • 1,681
  • 2
  • 16
  • 25