Could anyone tell me how to produce a right-click event handler in Clojure? I am familiar with ":on-click" for simple clicks but not right or double clicks. Can't seem to find any helpful resources online. Thanks!
To specifically capture the mouse right-click, JavaScript has a special event for that - contextmenu . Depending on the situation, instead of identifying which button has been clicked, you can specify the contextmenu event. This event still has the button property, with the number value of the, clicked button.
ClojureScript functions are regular JavaScript functions. The language provides primitives to access native browser objects, access and set properties of objects, create and manipulate JavaScript objects and arrays, and call any JavaScript function or method.
The contextmenu event fires when the user attempts to open a context menu. This event is typically triggered by clicking the right mouse button, or by pressing the context menu key.
Frequently in ClojureScript the Google Closure library (Event Handling | Closure Library | Google Developers) is used instead of raw JS. The events (Closure Library API Documentation - JavaScript) namespace contains the goog.events.EventType
enumeration which specifies each individual event type:
(ns test.core
(:require [goog.dom :as dom]
[goog.events :as events]))
(letfn [(menu-listener [event]
(.log js/console (str "contextmenu " (.-button event))))
(click-listener [event]
(let [btn (.-button event)
msg (if (= btn 2) "Right-click" (str "Button " btn))]
(.log js/console msg)))]
(events/listen (dom/getElement "click-target") "contextmenu" menu-listener)
(events/listen (dom/getElement "click-target") "click" click-listener))
;; src/test/core.cljs
.
<!DOCTYPE html>
<html>
<head>
<title>contextmenu</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<p id="click-target">Right click on me</p>
<script src="out/test.js" type="text/javascript"></script>
</body>
</html>
<!-- index.html -->
Observe:
contextmenu
listener. The click
listener doesn't get to see it (even if there is no contextmenu
listener).Using om
I got right click as context-menu event. Button number is 2 for right button:
{:onContextMenu (fn [e]
(prn e (.-button e)))}
or in plain html+cljs:
<div id="btn">Click me</div>
(.addEventListener (.getElementById js/document "btn")
"contextmenu" (fn [e] (prn e (.-button e))))
https://developer.mozilla.org/en/docs/Web/API/MouseEvent
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With