Right Click in ClojureScript?
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:
- A right-click (button 2) fires the
contextmenu
listener. Theclick
listener doesn't get to see it (even if there is nocontextmenu
listener). - A second right-click will dismiss the context menu but neither listener is fired.
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