javascriptevent-handlingdom-eventscreatejseaseljs

createjs prevent hyperlink interaction


In my simple application canvas wrapped by hyperlink. Some objects, which are placed on canvas stage have special mouse interaction on click event. Is there any possible solutions to prevent hyperlink jumping by clicking on objects with my mouse click event listeners?


Solution

  • Normally you can just call preventDefault on the generated mouse event, and it will stop the link event from firing.

    element.addEventListener("click", function(e) { 
        e.preventDefault(); 
    }, false);
    

    This is not possible using EaselJS because although you can access the nativeEvent on any EaselJS mouse event, EaselJS doesn't use the "click" event at all (and instead uses a combination of "mousedown" and "mouseup"). So preventing default on a click event will do nothing.

    Doesn't work

    // You would expect this to work.
    myShape.on("click", function(e) {
        e.nativeEvent.preventDefault(); // Nothing. This cancels a "mouseup" instead.
    });
    

    Workaround

    However, you can work around this pretty easily. Set a flag on the clicked item (or wherever you would set it in your application) any time it is clicked.

    myShape.addEventListener("click", function(event) {
      myShape.clicked = true;
    }, false);
    

    Then, listen for the canvas click event yourself, check and check the flag. Make sure to reset it after. This is possible because "click" is always fired after "mouseup"

    stage.canvas.addEventListener("click", function(event) {
         if (myShape.clicked) { event.preventDefault(); }
         myShape.clicked = false;
    }, false);
    

    Here is a quick fiddle showing it working. http://jsfiddle.net/buqkvb1u/

    We are looking to see if this makes sense to handle in EaselJS. Thanks for your report!