Search code examples
clojuremouseeventclojurescript

Right Click in ClojureScript?


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!


Solution

  • 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.