Ketha Kavya
Ketha Kavya

Reputation: 588

Execute a function on Mouseover for nested divs

I am showing an example code:

<div onmouseover="function1(e)">
   SomeContent 1
   <div onmouseover="function2(e)"> SomeContent 2</div>
</div>

Here both function1() and function2() are being executed when mouseover is on inner div. If the mouse is on inner div it should only execute function2(). I have even tried using e.stopPropagation() too.

Any help is appreciated and thanks in advance.

Upvotes: 2

Views: 684

Answers (3)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

Because you're using JQuery i suggest to use on() :

Description: Attach an event handler function for one or more events to the selected elements.

Instead of inline event handlers that considered as a bad practice e.g :

$('#content_1').on('mouseover' , function(e){
    $('#console').text('function 1');
});

$('#content_2').on('mouseover' , function(e){
    e.stopPropagation();
    $('#console').text('function2');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="content_1">
   SomeContent 1
   <div id="content_2"> SomeContent 2</div>
</div>

<br>
<span id='console'></span>

Upvotes: 0

George Irimiciuc
George Irimiciuc

Reputation: 4633

stopPropagation() is working for me. Maybe you weren't using it right?

Below snippet also works for .on('mouseenter',..

$('div').hover(function(e) {
  if ($(e.target).is('div.parent')) {
    console.log('parent');
    e.stopPropagation();
  } else if ($(e.target).is('div.child')) {
    console.log('child');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
  SomeContent 1
  <div class="child">SomeContent 2</div>
</div>

Upvotes: 1

Bhargav Ponnapalli
Bhargav Ponnapalli

Reputation: 9412

This works for me. Does this help? "window.event" is the object which is available for onclick, not "window.e".

var function1 = function(){
  console.log("func1"); 

}

var function2 = function(e){
  e.stopPropagation();
  console.log("func2"); 

}
<div onmouseover="function1(event)" style="padding:30px;background:red;">
   SomeContent 1
   <div onmouseover="function2(event)" style="background:yellow"> SomeContent 2</div>
</div>

Upvotes: 0

Related Questions