1

I have a parent DIV with a background image, when you mouseover it fades in a little icon on the top right(a child div), the little icon is clickable and the parent div (that has the background image) is also clickable.

My problem is when I click the little icon, the parent DIV's click event is also triggered.
I want only the child div's onclick to be called when I click the little icon. If I can get the href to work in the little icon that too would be acceptable.

(Parent div: img1 and id "momClickable")
(Child div with icon: topIcon1)

Working fiddle is here: http://jsfiddle.net/auhjo9nw/

My HTML:

<div class="img1" id="momClickable">- img 206x206 here - 
<div class="topIcon1"><a href="#"><img src="momIcon.jpg" border="0" /></a></div>
</div>

The css for the above is:

.img1 {
    width:206px;
    height:206px;
    margin-left: auto;
    margin-right: auto;
    background:url(Mom206x206.jpg);
}

.topIcon1 {
    position:relative;
    width:45px;
    left: 155px;
    top: -10px;
    display:none;
}

My jquery:

// To make the div clickable
$('#momClickable').click(function() {
      console.log('You clicked the DIV.');
    }); 

//To make the icon clickable
$('.topIcon1').click(function() {
      console.log('You clicked the DIV 2.');
    });     

$(function(){
    $(".pictureBoxWrapper1").hover(function(){
      $(this).find(".topIcon1").fadeIn(100);
      $('#momClickable').css('cursor','pointer');
    }
                    ,function(){
                        $(this).find(".topIcon1").fadeOut();
                    }
                   );        
});
Ryan
  • 9,821
  • 22
  • 66
  • 101

1 Answers1

3

This is known as 'Event Propagation' or more commonly 'Event Bubbling'.

The solution can be found here

$('.topIcon1').click(function(event) {
    console.log('You clicked the DIV 2.');
    event.stopPropagation();
}); 

Your revised working jsfiddle

SnareChops
  • 13,175
  • 9
  • 69
  • 91
  • Ah! Thank you for the explanation and the code! Will accept your answer as the time runs out :) – Ryan Oct 11 '14 at 03:06
  • Quick question: Is it possible to use the href in the child DIV? (instead of using JQuery's onClick that is presently attached to the child div) – Ryan Oct 11 '14 at 03:09
  • @Ryan It should work in theory, but I wonder if because it is wrapped in the jQuery `click` event that this is somehow being overridden... I haven't dealt with that specifically. Perhaps a quick search here on SO could provide you with that answer. Sorry I don't know off the top of my head. – SnareChops Oct 11 '14 at 03:13
  • No worries, thanks for answering, have accepted it. Have a good W/E! – Ryan Oct 11 '14 at 03:15