1

I have a div class called 'cat'. In mouseover event another div is displayed with two anchor link on which click event are hard coded. Now when anchor is clicked its parent div click also gets fired. I tried to return galse, but it is not working. The code is as below

         function onload()
    {
        $('.cat').css('cursor', 'pointer');
        $('.cat').mouseenter(function (e) {
            $('<div />', {
                'class': 'tip',
                html: 'Name: ' + $(this).data('cat-name') + '<br/>Web Name: ' + $(this).data('web-name') + '<br/>Total No. Of SubCategories: ' + $(this).data('total-subcategory') + '<br/><br/><a href="#" onclick = "return addsubcategory(' + $(this).data('cat-id') + ',this)">Add Sub Category</a>&nbsp;<a href="#" onclick = "editcategory(' + $(this).data('cat-id') + ',this)">Edit Category</a> ',
                css: {
                    position: 'fixed',
                    top: e.pageY,
                    left: e.pageX,
                    border: '1px solid red',
                    background: 'yellow',
                    padding: '5px',
                    font: '8'
                }
            }).appendTo(this);


        });
        $('.cat').mouseleave(function (e) {
            $('.tip', this).remove();
        });

        $('.cat').on('click', getsubcategory);



    }
    function getsubcategory()
    {

        var clicked = $(this).parent().attr('id');
        gatsubcategory(clicked);
        return false;
    }
    function editcategory(catid,e) {
        alert("Edit " + catid);

        return false;

    }
    function addsubcategory(catid,e) {
        alert("Add " + catid);

        return false;
    }
Ratna
  • 2,289
  • 3
  • 26
  • 50

2 Answers2

2

You need to use event.stopPropagation() to prevents the event from bubbling in child elements click event(which are anchor tag in your case). something like this:

$('.cat a').click(function(e){
    e.stopPropagation();
});
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
  • event is not defined. It is hard coded function with only one parameter – Ratna Jun 27 '14 at 10:44
  • You can modify the inline click event to accept parameter as object of current element and then stopPropogation in called function. see this http://stackoverflow.com/a/387823/1719752 – Milind Anantwar Jun 27 '14 at 10:46
0

You should use event.stopPropagation for that.

It Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

$('.cat').mouseleave(function (e) {
      e.stopPropagation();
      $('.tip', this).remove();
});

Edit

You can also do it in the inline javascript too, just pass event as another parameter like this,

<a onclick="test(event)"></a>

javascript

function test(event)
{
  event.stopPropagation();
}
Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53