Reputation: 21351
I have 2 images, one
and two
On hover of one
, the two
is displayed, and one
is hidden
And then, if I clicked two
, it should hide and show the one
again
So far all okay
BUT, problem is, mouse is already on the one
image so onmouseenter
triggers again. I want it to trigger only if mouse came from outside of image without jQuery
Just like the Chat icon here on bottom-right
document.getElementById("one").onmouseenter = function onmouseoverRobot() {
document.querySelector("#two").style = 'display:inline-block !important'
document.querySelector("#one").style = 'display:none !important'
}
document.getElementById("two").onclick = function X_CHAT_01() {
document.querySelector("#two").style = 'display:none !important'
document.querySelector("#one").style = 'display:inline-block !important'
}
<img id='one' src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSoMUKwCL1uINRV035jkpfQzAbiObKqraXA6369mZBe0To0UuWP'>
<img id='two' style='display:none' src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSMYIpY4d8KlTzhAd38KZW8DIadeEV59WtLlxeIH3PS4uPXL0RP'>
Upvotes: 1
Views: 55
Reputation: 1067
The simplest solution that doesn't require event listeners mangling is to add a boolean indicator that tells if the chat has been enabled or not.
var chatEnabled = false;
var one = document.getElementById('one');
var two = document.getElementById('two');
one.onmouseenter = function onmouseoverRobot() {
if (chatEnabled) {
return;
}
two.style = 'display:inline-block !important';
one.style = 'display:none !important';
};
one.onmouseout = function onmouseoutRobot() {
chatEnabled = false;
};
two.onclick = function X_CHAT_01() {
chatEnabled = true;
two.style = 'display:none !important';
one.style = 'display:inline-block !important';
};
Please, take a look at the demo.
Upvotes: 1
Reputation: 34236
In order to avoid the mouseenter
event firing when you show the image try removing the listener and then adding it back after a mouseleave
event.
img#one
:mouseenter
- Remove mouseenter
listener from img#one
. Hide img#one
and show img#two
.
img#two
:click
- Show img#one
and hide img#two
.
img#one
:mouseleave
- Add mouseenter
listener to img#one
.
You can also use one-time listeners for a simpler flow.
const onMouseEnter = function() {
hide(one)
show(two)
two.addEventListener("click", onClick, { once: true })
}
const onClick = function() {
one.addEventListener("mouseleave", onMouseLeave, { once: true })
hide(two)
show(one)
}
const onMouseLeave = function() {
one.addEventListener("mouseenter", onMouseEnter, { once: true })
}
one.addEventListener("mouseenter", onMouseEnter, { once: true })
Upvotes: 2