Created
November 20, 2014 15:39
-
-
Save noctivityinc/ef1c70f167ec6ca399bf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function ($, window) { | |
$.fn.contextMenu = function (settings) { | |
return this.each(function () { | |
// Open context menu | |
$this = $(this) | |
$this.on("contextmenu", function (e) { | |
//open menu | |
$(settings.menuSelector) | |
.data("invokedOn", $(e.target)) | |
.show() | |
.css({ | |
position: "absolute", | |
left: getLeftLocation(e), | |
top: getTopLocation(e) | |
}) | |
.off('click') | |
.on('click', function (e) { | |
$(this).hide(); | |
var $invokedOn = $(this).data("invokedOn"); | |
var $selectedMenu = $(e.target); | |
settings.menuSelected.call(this, $this, $invokedOn, $selectedMenu); | |
}); | |
return false; | |
}); | |
//make sure menu closes on any click | |
$(document).click(function () { | |
$(settings.menuSelector).hide(); | |
}); | |
}); | |
function getLeftLocation(e) { | |
var mouseWidth = e.pageX; | |
var pageWidth = $(window).width(); | |
var menuWidth = $(settings.menuSelector).width(); | |
// opening menu would pass the side of the page | |
if (mouseWidth + menuWidth > pageWidth && | |
menuWidth < mouseWidth) { | |
return mouseWidth - menuWidth; | |
} | |
return mouseWidth; | |
} | |
function getTopLocation(e) { | |
var mouseHeight = e.pageY; | |
var pageHeight = $(window).height(); | |
var menuHeight = $(settings.menuSelector).height(); | |
// opening menu would pass the bottom of the page | |
if (mouseHeight + menuHeight > pageHeight && | |
menuHeight < mouseHeight) { | |
return mouseHeight - menuHeight; | |
} | |
return mouseHeight; | |
} | |
}; | |
})(jQuery, window); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment