nt2 nt2 - 5 months ago 12
Javascript Question

right click not appear at right place

I am working on a map app where when right clicked on a google map, it shows some options.

the problem is right click is not appearing at right place.

How can I resolve this?

I tried positioning it by using position absolute.

Also tried, below Jquery code,

$( ".map-context-menu" ).click(function() {

var styleProps = $( this ).css([
"Ra", "latLng", "pixel"
]);
$.each( styleProps, function( prop, value ) {
html.push( prop + ": " + value );
});

});


this is my html

`<div class="map-context-menu" ng-show="contextMenuActive">

<div class="map-context-menu-item" >
Item 1
</div>
<div class="map-context-menu-item">
Item 2
</div>
</div>
`

Answer
$(document).bind('contextmenu', function (e) {
    e.preventDefault();
    e.stopPropagation();
    if ($(e.target).hasClass('map-context-menu')) {
        $('#contextMenu').css({
            left: e.pageX + 'px',
            top: e.pageY + 'px'
        }).show().fadeIn(500);
    }
    return false;
});

This will automatically position the #contextMenu where you have right-clicked within map-context-menu

e.stopPropagation()

This will stop method from overcrowding the DOM. Ensures the the previous context menu is destroyed before another is created. For example, say if you do 2 right clicks in a row at different locations...instead of 2 spawning, the 1st will hide before the 2nd is created

e.preventDefault()

Will prevent the browser default context menu from being shown. For example, whenever you right click on anywhere in a web page, a default context menu will appear that is created by the browser. This line prevents that and will display your custom created one instead

N.B: Please change #contextMenu to the ID or class of your custom context menu you created. For example: (the HTML)

 <ul id="contextMenu">
     <li></li>
     <li></li>
 </ul>

I have added this CSS code to my jsFiddle and everything seems to be working fine. (The styling can be modified, it's the position: fixed and display: none that are crucial to this working)

CSS

#contextMenu {
    background-color: red;
    list-style: none;
    padding: 0;
    margin: 5px 0 0 5px;
    font-size: 20px;

    display: none;
    position: fixed;
    border: 1px solid grey;
    width: 150px;
    box-shadow: 2px 2px 1px grey;
}