简体   繁体   中英

How can I pass a mouse click event within javascript?

I am trying to implement drag and drop for javascript.I need to pass the event but it is returning undefined. I have already tried passing window.event directly.Does not work

var lens = svg.append("circle")
.attr("id","lens")
.attr("class","draggable")
.attr("cx",40)
.attr("cy",40)
.attr("r",40)
.style("fill","grey");

//Setting click handler
lens.on("click",function(e){
selectElement(e)});

 function selectElement(e) {       
     console.log(window.event); //This prints UNDEFINED
     console.log(e);  //This prints UNDEFINED

    var evt = e || window.event;    
     console.log(evt);  //This prints UNDEFINED
 }

SVG uses evt to monitor an event. Try the following:

 <!DOCTYPE HTML> <html> <head> <title>SVG evt</title> </head> <body> <svg width=400 height=400> <circle id=myCircle cx=200 cy=200 r=100 fill=blue stroke=none onClick=showEvt(evt) /> </svg> <script> function showEvt(evt) { var target=evt.target console.log(target.getAttribute("id")) } </script> </body> </html> 

Have you checked out jQuery UI? https://jqueryui.com/ This might help you. Here is a basic set up for dragging and dropping:

$( function() {
    $( "#draggable" ).draggable();
    $( "#droppable" ).droppable({
      drop: function( event, ui ) {
        $( this )
          .addClass( "ui-state-highlight" )
          .find( "p" )
            .html( "Dropped!" );
      }
    });
  } );
  </script>

Regarding your click event try this:

$('#id').click(function(){
  $(this).data('clicked', true);
});

Here is a link to a Javascript Mouse Event tutorial that will allow you to tie into mouse events without using jQuery or other library:

JavaScript Mouse Events

with a working fiddle example:

https://jsfiddle.net/iamthejonsmith/q0sc4mae/

and example code:

<input type="button" value="click me" id="btn">
<input type="button" value="right-click me" id="btn2">



document.getElementById('btn').onclick = function() {
  alert('click!')
}

document.getElementById('btn2').oncontextmenu = function() {
  alert('right click!')
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM