Member Avatar for Rahul47

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

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

Member Avatar for Rahul47

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.

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.

Member Avatar for Rahul47

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 ?

Member Avatar for Rahul47

.

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 :).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.