9

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!

Jessie Richardson
  • 938
  • 2
  • 9
  • 24
  • 1
    see http://stackoverflow.com/questions/2405771/is-right-click-a-javascript-event – edbond Apr 11 '16 at 15:16
  • Thanks but that is for Javascript not Clojure. I understand that JS is running under the hood of Clojure but looking for a code snippet in Clojure. – Jessie Richardson Apr 11 '16 at 15:22

2 Answers2

9

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. The click listener doesn't get to see it (even if there is no contextmenu listener).
  • A second right-click will dismiss the context menu but neither listener is fired.
Peer Reynders
  • 546
  • 3
  • 6
  • The link for the events library is broken, here's a link to the source for the event types: https://github.com/google/closure-library/blob/master/closure/goog/events/eventtype.js – shark8me Apr 30 '19 at 02:23
5

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

edbond
  • 3,921
  • 19
  • 26