István Zachar
István Zachar

Reputation: 1344

How to make a toggling Mouseover button?

I have to make a toggler-like control, which performs some action, when the mouse goes over it, and performs another action when it leaves the button, but does nothing while the mouse is over and moving.

To make it clear, it is not enough to simply find out whether the mouse is over a region or not, but it must run some code only when the mouse enters and leaves the region. (clarification requested by Szabolcs)

Sadly, the AutoAction option of Button behaves differently: it constantly tries to perform the action while the mouse is moving inside the object:

switch = False;
Button["Hover", switch = ! switch, AutoAction -> True]
Dynamic[switch]

On the other hand, a simple Mouseover command cannot perform code that is executed each time the mouse leaves the object:

in = out = 0;
Mouseover[
 Dynamic["out", (in++) &],
 Dynamic["in", (out++) &]
 ]
Dynamic[Column[{in, out}]]

I thought that the second argument of Dynamic could be used to define starting and ending actions for a Mouseover object, but had no success with this approach either.

start = end = False;
Dynamic[Mouseover["out", "in"], {(start = True) &, Null, (end = True) &}]
Dynamic[Column[{start, end}]]

Any ideas?

Upvotes: 8

Views: 238

Answers (1)

Heike
Heike

Reputation: 24420

You could do something like this:

in = 0; out = 0;
Dynamic[Column[{in, out}]]
Module[{over = False},
 EventHandler[
  Pane[EventHandler[Dynamic[Framed[Pane[If[over, "In", "Out"], 40]]],
     {"MouseMoved" :> If[Not[over], over = True; in++]},
     PassEventsUp -> False], ImageMargins -> 4],
  {"MouseMoved" :> If[over, over = False; out++]}]]

What this does is to wrap the region for which you want to register the entries and exits into a slightly larger region using Pane. Both the inner region and the outer region have an EvenHandler which registers movements of the mouse. By setting PassEventsUp->False for the inner EventHandler, the "MouseMoved" events are passed to the outer EventHandler only if the mouse pointer is over the outer region but not over the inner region.

Upvotes: 10

Related Questions