I am trying to alert the correct css selector and xpath on right click on a dom element. I can show a menu on right click but I'm blocked getting the css selector and xpath value. Input for the code will be any website source code (right click on site, view source) or sample html code which has some classnames. I have a reference to pull unique css selector here
Any pointers on how to get unique css selector and xpath on right click on any dom element?
My Fiddle is here
<h2>Copy paste source code</h2>
<textarea id="txtSrcCode"></textarea>
<input type="button" value="Load Page" id="btnLoadPage" />
<div id="divToBindSrcCode">
</div>
<ul class='custom-menu'>
<li data-action="first">First thing</li>
<li data-action="second">Second thing</li>
<li data-action="third">Third thing</li>
</ul>
Jquery code
$('#btnLoadPage').click(function() {
$('#divToBindSrcCode').html($('#txtSrcCode').val()); // Laod dom on to the page
});
$(document).bind("contextmenu", function(event) {
// Avoid the real one
event.preventDefault();
// Show contextmenu
$(".custom-menu").finish().toggle(100).
// In the right position (the mouse)
css({
top: event.pageY + "px",
left: event.pageX + "px"
});
});
// If the document is clicked somewhere
$(document).bind("mousedown", function(e) {
// If the clicked element is not the menu
if (!$(e.target).parents(".custom-menu").length > 0) {
// Hide it
$(".custom-menu").hide(100);
}
});
// If the menu element is clicked
$(".custom-menu li").click(function() {
var kk = $(this).val();
// This is the triggered action name
switch ($(this).attr("data-action")) {
// A case for each action. Your actions here
case "first":
alert(kk);
break;
case "second":
alert("second");
break;
case "third":
alert("third");
break;
}
// Hide it AFTER the action was triggered
$(".custom-menu").hide(100);
});