0

Greetings,
I am dabbling with my little code here. Problem is mouseout event handler is getting executed thrice instead of twice.

var img=document.getElementById('newImg');
img.addEventListener('mouseover',function(e){
    e.target.width+=200;
    console.log(e.target.width);
    img.addEventListener('mouseout',function(e){
        e.target.width-=200;
        console.log(e.target.width);
    },false);
    console.log(e.target.width);
},false);

89e5b5d855500aa477198af64c4e1bb1

2
Contributors
6
Replies
21
Views
2 Years
Discussion Span
Last Post by minitauros
0

Why do you have your mouseout event listener inside the other event listenere in the first place?

Sir, I am new to Javascript and learning events. This is as a result of experimentation. So, am trying to understand how events work.

1

Well, if you bind an event inside another event, i.e. binding the mouseout event as soon as the user mouseins, it means that the event will be bound every time the user mouseins.

That means that you in your current situation, you are actually saying:

When the user's mouse hits the image, bind the event "mouseout" to the image. And when the user's mouse hits the image again, the same event is bound to it again and again and again. Not sure if it is bound until infinity, but that seems to be where the problem lies in your case (please do correct me if I'm wrong, cause while writing this I'm becoming a bit unsure about if this is really the problem).

What you should do is move the mouseout event to outside the mousein event.

E.g.:

var img=document.getElementById('newImg');

img.addEventListener('mouseover',function(e){
    e.target.width+=200;
    console.log(e.target.width);
},false);

img.addEventListener('mouseout',function(e){
    e.target.width-=200;
    console.log(e.target.width);
},false);

I think that should fix it.

0

please do correct me if I'm wrong,

You are right sir. As I said, I was learning how the events work out. And here is the result after replacing with value 200 by 50.

250dd4a5da7bc58dbc6195b0c6cd1f72 As we can see, when first time 'mouseover' takes place one 'mouseout' is bound to image. Consequently, as each time 'mouseover' takes place 'mouseout' events pile up and increment linearly.

I fail to understand that when we 'mouseover' second time, why does two event handlers for 'mouseout' gets executed ?

0

That is because your "mouseout" event is bound as soon as the user mouseovers your image. So if a user mouses over the image 100 times, the "mouseout" event will be bound 100 times. If you follow the example I provided, your problem should be fixed :).

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.