Developer Developer - 3 months ago 16
CSS Question

Positioning element near the clicked area

I am trying to integrate a context menu with jQuery full calendar plugin. I couldn't find any example i tried building my own. Its working but not getting proper position. I have tried almost 10 days and googled a lot and couldn't find a solution.

I manually generate HTML for menu item based on event object passed and showing. I have used Positioning Context Menu solution to position.

How to position context menu properly?

$('#calendar').fullCalendar({
//all fullCalendar options goes here,
eventRender: function (event, element, view) {
element.bind('contextmenu', function (e) {
//generate my own <ul><li> html based on event object
var contextMenuHtml = getContextMenu(event);
//contextMenuContainer is hidden div in at the bottom of <body>
$('#contextMenuContainer').html(contextMenuHtml);

$('#contextMenuContainer').fadeIn();
var position = element.position();

$('#contextMenuContainer').css({
left: e.pageX, //to show the container close to where i click
top: e.pageY // How can i adjust or calculate position if i click near to edge of window
});

$(document).click(function () {
$('#contextMenuContainer').fadeOut();
});

return false;
});
}
});


enter image description here

I tried to use this jQuery contextMenu plugin but which doesnt suite my requirement. I need to dynamically generate menu items with links based on fullCalander event object which I shown above. But unfortunately these plugins not supporting such and no examples like that.

Answer

Moving my comment to an answer because under dependencies jQuery-contextMenu lists jQuery UI position as optional: https://github.com/swisnl/jQuery-contextMenu#dependencies

You can build a jQueryUI package with just this function here: http://jqueryui.com/download/

Or it looks like the contextMenu has a version in their distribution files: https://github.com/swisnl/jQuery-contextMenu/tree/master/dist

$('#calendar').fullCalendar({
  //all fullCalendar options goes here,
  eventRender: function (event, element, view) {                     
      element.bind('contextmenu', function (e) {

          var contextMenuHtml = getContextMenu(event);

          $('#contextMenuContainer')
             .html(contextMenuHtml)
             .position({
                 my: 'left-5 top-5',
                 of: e,
                 collision: "fit"
              })
             .fadeIn();


          $(document).click(function () {
              $('#contextMenuContainer').fadeOut();
           });

          return false;
       });
  }
});