Delaying the display:none [final] part of fadeToggle - javascript

I'm trying to find a way to delay the final part as stated in the title.
My initial JQuery code
var debounce = false;
var elements = document.getElementsByClassName('.Menu')
$('#Option1').click(function() {
if (debounce == true) {return;}
debounce = true;
$('.Menu').each(function(index) {
anim2($(this), index * 250, function() {
if (index != elements.length) {return;}
debounce = false;
})
})
});
This produces what I want to a certain extent but due to the delays and the fact that the display becomes none, I don't get what I truly want.
GIF Representing problem : https://gyazo.com/3d8f46ec3e34dfd7b88738fc00d477e1
The initial fade in works great but on the fade out when the first button disappears the delayed buttons for the other ones shift to the left which is what I'm trying not to let happen.
I tried doing:
var debounce = false;
var isClicked = false;
var elements = document.getElementsByClassName('.Menu')
$('#Option1').click(function() {
if (debounce == true) {return;}
debounce = true;
$('.Menu').each(function(index) {
anim2($(this), index * 250, function() {
if (index != elements.length) {
if (isClicked == false) {
isClicked = true;
$('.Menu').each(function(index) {
$(this).css("display", "none");
$(this).css("opacity", "0");
})
} else {
isClicked = false;
$(this).css("display", "inline-block");
$(this).css("opacity", "1");
}
}
debounce = false;
})
})
});
But it doesn't work and creates bugs. If you need to know the anim2 function it is
function anim2(object, dt, end) {
$(object).stop().delay(dt).fadeToggle({
duration: 1000,
easing: "easeOutQuad",
quene: true,
complete: end
})
}
Just going to post the relevant parts of the LESS in case it might be the cause of it
.invisible {
background: transparent;
border: none;
}
.Hamburger {
background: #pure-white;
width: 100%;
height: 5px;
opacity: 0;
position: absolute;
.rounded
}
#Option1 {
.invisible;
position: absolute;
padding: 0px 0px 0px 0px;
top: 0px;
left: 10px;
height: 100%;
width: 40px;
#TopSpan {
.Hamburger;
top: 10px;
}
#MiddleSpan {
.Hamburger;
top: 20px;
}
#BottomSpan {
.Hamburger;
top: 30px;
}
&:active {
background: #pure-red;
}
}
I have also checked out Delay of a few seconds before display:none and Hide div after a few seconds but delay() won't work since it's an automatic effect
HTML
<!DOCTYPE html>
<html lang="en">
<head class="Setup">
<link rel="stylesheet/less" type="text/css" href="../LESS/core.less"/>
<script src="../JavaScript/less.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script type='text/javascript' src="../JavaScript/java.js"></script>
</head>
<body class="Setup">
<div class="Design">
<div class="TopDesign">
<span id="Topbar"></span>
<span id="Minibar">
<button class="Buttons" id="Option1">
<span class="Home" id="TopSpan"></span>
<span class="Home" id="MiddleSpan"></span>
<span class="Home" id="BottomSpan"></span>
</button>
<button class="Buttons Menu" id="Sub1">
<p class="SubText">Source1</p>
</button>
<button class="Buttons Menu" id="Sub2">
<p class="SubText">Source2</p>
</button>
<button class="Buttons Menu" id="Sub3">
<p class="SubText">Source3</p>
</button>
</span>
</div>
<div class="LeftDesign">
<span id="Leftbar">
<img src="" alt="">
</span>
</div>
</div>
</body>
</html>

Here is an answer not using javascript for the animation but CSS:
https://jsfiddle.net/7a1cpu0n/
I know this isn't exactly what you wanted, but it's simpler code and you should be able to apply the concept to your project. Just use CSS transition on the elements you want to show/hide and use javascript to toggle their class.
<ul>
<li>Menu</li>
<li>link1</li>
<li>link2</li>
<li>link3</li>
</ul>
$(document).ready(function(){
$('li:first-child').click(function(){
var time = 250;
$(this).siblings().each(function(){
var el = $(this);
setTimeout( function(){
el.toggleClass('show');
}, time);
time = time+250;
});
});
});
ul li:not(:first-child){
opacity: 0;
}
ul li {
float: left;
padding: 10px;
margin: 10px;
background: #e6e6e6;
list-style: none;
transition: all 1s;
}
ul li.show {
opacity: 1;
}
This is proof of concept.

Related

How do I add next and previous buttons to my slideshow with jQuery?

I have a slideshow that automatically transitions to the next picture with a timer but I want to add more functionality by pausing and by also being able to go to the next or the previous image. I am confused though on how to add those event handlers?
$(document).ready(function() {
var nextSlide = $("#slides img:first-child");
var nextCaption;
var nextSlideSource;
// the function for running the slide show
var runSlideShow = function() {
$("#caption").fadeOut(1000);
$("#slide").fadeOut(1000,
function () {
if (nextSlide.next().length == 0) {
nextSlide = $("#slides img:first-child");
}
else {
nextSlide = nextSlide.next();
}
nextSlideSource = nextSlide.attr("src");
nextCaption = nextSlide.attr("alt");
$("#slide").attr("src", nextSlideSource).fadeIn(1000);
$("#caption").text(nextCaption).fadeIn(1000);
}
)
}
// start the slide show
var timer = setInterval(runSlideShow, 3000);
})
body {
font-family: Arial, Helvetica, sans-serif;
width: 380px;
margin: 0 auto;
padding: 20px;
border: 3px solid blue;
}
h1, h2, ul, p {
margin: 0;
padding: 0;
}
h1 {
padding-bottom: .25em;
color: blue;
}
h2 {
font-size: 120%;
padding: .5em 0;
}
img {
height: 250px;
}
#slides img {
display: none;
}
#buttons {
margin-top: .5em;
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Xochitl Menjivar</title>
<link rel="stylesheet" href="main.css">
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="slide_show.js"></script>
</head>
<body>
<main>
<h1>Fishing Slide Show</h1>
<h2 id="caption">Casting on the Upper Kings</h2>
<img id="slide" src="images/casting1.jpg" alt="">
<div id="slides">
<img src="images/casting1.jpg" alt="Casting on the Upper Kings">
<img src="images/casting2.jpg" alt="Casting on the Lower Kings">
<img src="images/catchrelease.jpg" alt="Catch and Release on the Big Horn">
<img src="images/fish.jpg" alt="Catching on the South Fork">
<img src="images/lures.jpg" alt="The Lures for Catching">
</div>
<div id="buttons">
<input type="button" id="prev" value="Previous" disabled>
<input type="button" id="play" value="Pause">
<input type="button" id="next" value="Next" disabled>
</div>
</main>
</body>
</html>
Working fiddle
For play/pause you can do this
$('#play').on('click', function(e){
e.preventDefault();
isPaused = !isPaused;
if(isPaused){
$('#play').val('Play');
window.clearInterval(timer);
} else {
$('#play').val('Pause');
timer = setInterval(runSlideShow, 3000)
}
})
Declare variable for tracking play/pause state. When it is in pause state, clear timer interval, if state is play, then set interval timer again.
Also, you could have added this flag inside runSlideShow() function
var runSlideShow = function() {
if(!isPaused){
$("#caption").fadeOut(1000);
$("#slide").fadeOut(1000,
function () {
findNextSlide()
nextSlideSource = nextSlide.attr("src");
nextCaption = nextSlide.attr("alt");
$("#slide").attr("src", nextSlideSource).fadeIn(1000);
$("#caption").text(nextCaption).fadeIn(1000);
}
)
}
}
And click event would be quite short.
$('#play').on('click', function(e){
e.preventDefault();
isPaused = !isPaused;
})
For next slide one option, would be just simply clear and start runSlideShow, which will automatically force to fetch new slide with all effects.
Show previous slide, you can use same logic, and instead finding next slide, just look for previous slide. jQuery has function .prev() which is opposite of .next()
Edit:
function findPreviousSlide(){
if (nextSlide.prev().length == 0) {
nextSlide = $("#slides img:last-child");
}
else {
nextSlide = nextSlide.prev();
}
}

how to set jquery slider on auto instead of click or hover on thumbs

i am new learner of jquery and javaScript.
i want to create a slider with a big image section and a section of thumbs.
slider should slide automatically i have coded so far is working on click or hover but i dont know how to set it on auto please help me how to modify my code. code and slider screen shoot is given below.
slider image
$("document").ready(function()
{
$("#thumbs a").mouseenter(function()
{
var smallimgpath = $(this).attr("href");
$("#bigimage img").fadeOut(function()
{
$("#bigimage img").attr("src",smallimgpath);
$("#bigimage img").fadeIn();
});
return false;
});
});
</script>
#imagereplacement{
border: 1px solid red;
width:98%;
height:400px;
margin:auto;
padding-top:8px;
padding-left:10px;
}
#imagereplacement p{
text-align:inline;
}
#bigimage{
/* border: 1px solid green; */
margin:auto;
text-align:center;
float: left;
}
#thumbs{
/*border: 1px solid yellow;*/
margin: 110px 10px;
text-align:center;
width:29%;
float: right;
}
#thumbs img{
height:100px;
width:100px;
}
//This is where all the JQuery code will go
</head>
<body>
<div id="imagereplacement">
<p id="bigimage">
<img src="images/slider1.jpg">
</p>
<p id="thumbs">
<img src="images/slider1.jpg">
<img src="images/slider2.jpg">
<img src="images/slider3.jpg">
</p>
try with this example, please let me know in case of any more question from you :
$("document").ready(function(){
var pages = $('#container li'),
current = 0;
var currentPage, nextPage;
var timeoutID;
var buttonClicked = 0;
var handler1 = function() {
buttonClicked = 1;
$('#container .button').unbind('click');
currentPage = pages.eq(current);
if ($(this).hasClass('prevButton')) {
if (current <= 0)
current = pages.length - 1;
else
current = current - 1;
nextPage = pages.eq(current);
nextPage.css("marginLeft", -604);
nextPage.show();
nextPage.animate({
marginLeft: 0
}, 800, function() {
currentPage.hide();
});
currentPage.animate({
marginLeft: 604
}, 800, function() {
$('#container .button').bind('click', handler1);
});
} else {
if (current >= pages.length - 1)
current = 0;
else
current = current + 1;
nextPage = pages.eq(current);
nextPage.css("marginLeft", 604);
nextPage.show();
nextPage.animate({
marginLeft: 0
}, 800, function() {});
currentPage.animate({
marginLeft: -604
}, 800, function() {
currentPage.hide();
$('#container .button').bind('click', handler1);
});
}
}
var handler2 = function() {
if (buttonClicked == 0) {
$('#container .button').unbind('click');
currentPage = pages.eq(current);
if (current >= pages.length - 1)
current = 0;
else
current = current + 1;
nextPage = pages.eq(current);
nextPage.css("marginLeft", 604);
nextPage.show();
nextPage.animate({
marginLeft: 0
}, 800, function() {});
currentPage.animate({
marginLeft: -604
}, 800, function() {
currentPage.hide();
$('#container .button').bind('click', handler1);
});
timeoutID = setTimeout(function() {
handler2();
}, 4000);
}
}
$('#container .button').click(function() {
clearTimeout(timeoutID);
handler1();
});
timeoutID = setTimeout(function() {
handler2();
}, 4000);
});
* {
margin: 0;
padding: 0;
}
#container {
width: 604px;
height: 453px;
position: relative;
}
#container .prevButton {
height: 72px;
width: 68px;
position: absolute;
background: url('http://vietlandsoft.com/images/buttons.png') no-repeat;
top: 50%;
margin-top: -36px;
cursor: pointer;
z-index: 2000;
background-position: left top;
left: 0
}
#container .prevButton:hover {
background-position: left bottom;
left: 0;
}
#container .nextButton {
height: 72px;
width: 68px;
position: absolute;
background: url('http://vietlandsoft.com/images/buttons.png') no-repeat;
top: 50%;
margin-top: -36px;
cursor: pointer;
z-index: 2000;
background-position: right top;
right: 0
}
#container .nextButton:hover {
background-position: right bottom;
right: 0;
}
#container ul {
width: 604px;
height: 453px;
list-style: none outside none;
position: relative;
overflow: hidden;
}
#container li:first-child {
display: list-item;
position: absolute;
}
#container li {
position: absolute;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<center>
<h1>HTML Slideshow AutoPlay (Slide Left/Slide Right)</h1>
<br />
<br />
<div id="container">
<ul>
<li><img src="http://vietlandsoft.com/images/picture1.jpg" width="604" height="453" /></li>
<li><img src="http://vietlandsoft.com/images/picture2.jpg" width="604" height="453" /></li>
<li><img src="http://vietlandsoft.com/images/picture3.jpg" width="604" height="453" /></li>
</ul>
<span class="button prevButton"></span>
<span class="button nextButton"></span>
</div>
</center>
Here an example i've created that create an auto slider CodePen Demo and JSFiddle Demo
I've used an object literal pattern to create slide variable just to avoid creating many global function and variable. Inside document.ready i've initialised my slider just by calling slide.init({....}) this way it makes it easy to reuse and work like plugin.
$.extend(slide.config,option)
this code in simple words override you're default configuration defined in config key
as i mentioned in my above comment make a function slider() and place seTimeout(slide,1000) at bottom of your function before closing
Here in this code its done in animate key of slide object it is passed with two parameter cnt and all image array, If cnt is greater then image array length then cnt is set to 0 i.e if at first when cnt keeps on increment i fadeout all image so when i make it 0 the next time the fadeToggle acts as switch
if On then Off
if Off the On
and calling function slider after a delay makes it a recursive call its just one way for continuously looping there are many other ways i guess for looping continuous you can try
well i haven't check if all images Loaded or not which is most important in slider well that you could try on your own.
var slide = {
'config': {
'container': $('#slideX'),
'delay': 3000,
'fade': 'fast',
'easing': 'linear'
},
init: function(option) {
$.extend(slide.config, option);
var imag = slide.getImages();
slide.animate(0, imag);
},
animate: function(cnt, imag) {
if (cnt >= imag.length) {
cnt = 0;
}
imag.eq(cnt).fadeToggle(slide.config.fade, slide.config.easing);
setTimeout(function() {
slide.animate(++cnt, imag);
}, slide.config.delay);
},
getImages: function() {
return slide.config.container.find('img');
}
};
$(document).ready(function() {
slide.init({
'contianer': $('#slideX'),
'delay': 3000,
'fade': 'fast',
'easing': 'swing'
});
})
body {
margin: 0;
padding: 0;
}
.contianer {
width: 100%;
height: 100%;
position: relative;
}
.container > div,
.container > div >img {
width: 100%;
height: 100%;
position: absolute;
z-index: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container" id="slideX">
<div id="img1">
<img src="http://imgs.abduzeedo.com/files/articles/magical-animal-photography-gregory-colbert/5.jpg" />
</div>
<div id="img2">
<img src="http://cdn-5.webdesignmash.com/trial/wp-content/uploads/2010/10/great-dog-photography-016.jpg" />
</div>
<div id="img3">
<img src="http://onlybackground.com/wp-content/uploads/2014/01/marble-beautiful-photography-1920x1200.jpg" />
</div>
</div>

Toggle a function on click

I am trying to turn on and turn off a function on click - toggle a function.
I want .fly element to not disappear, only the animation should stop and return to its origin. When the button is clicked, the animation should stop. When it's clicked again, the animation starts again.
HTML
<div class="hobbie-box">
<div class="circle-image">
<i id="travel" class="fa fa-plane fly"></i>
</div>
<div class="circle-text">
<p>Travel industry</p>
</div>
</div>
<button type="button" class="btn toggle-effects">Turn off effects</button>
Javascript
var flyplane = function(){
setInterval(function() {
$fly.animate({
right: '-=50',
bottom: '+=50'
}, 2000, function() {
$fly.removeAttr("style");
});
}, 2000);
};
flyplane();
$(".toggle-effects").on("click", function () {
$(this).text(function (i, text) {
return text === "Turn off effects" ? "Turn on effects" : "Turn off effects";
})
$("#travel").toggle($fly);
}); //end of button click
There is a live example.
Please refer to my codepen
<div class="hobbie-box">
<div class="circle-image">
<i id="travel" class="fa fa-plane fly"></i>
</div>
<div class="circle-text">
<p>Travel industry</p>
</div>
</div>
<button class='toggle-effects'>[btn]</button>
#travel {
width: 50px;
height: 50px;
background-color: red;
display: block;
position: relative;
}
var $fly = $('.fly');
var flyplane = function() {
$fly.animate({
right: '-=50',
bottom: '+=50'
}, 2000, function() {
console.log('animation complete')
$fly.removeAttr("style");
flyplane();
});
};
//flyplane();
var count = 1;
$(".toggle-effects").on("click", function() {
console.log('click');
var isHidden = count++%2 !== 0;
if( isHidden ) {
$("#travel").show( 0, flyplane);
} else {
$("#travel").hide( 0 );
$fly.stop();
}
}); //end of button click
Not sure if that's what you are trying to achieve, but, if using setInterval:
You must save it into a variable, e.g variable = setInterval(function() { /* ... */ }, 2000);
To stop the interval, you must use clearInterval, e.g clearInterval(variable);.
And then, to star the interval again, you must call setInterval again, so it's better to encapsulate your code into a function, so you don't need to rewrite the same code twice.
Since, your flyplane function was already there, I only used it.
Take a look at the snippet below, and tell me if that's what you're trying to achive:
$(function() {
var $fly = $('.fly'), interval;
var flyplane = function() {
interval = setInterval(function() {
$fly.animate({
right: '-=50',
bottom: '+=50'
}, 2000, function() {
$fly.removeAttr("style");
});
}, 2000);
};
flyplane();
$(".toggle-effects").on("click", function() {
$(this).text(function(i, text) {
if (text === "Turn off effects") {
clearInterval(interval);
return "Turn on effects";
}
else {
flyplane();
return "Turn off effects";
}
})
}); //end of button click
});
.fly {
display: block;
width: 20px;
height: 20px;
background-color: yellow;
position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hobbie-box">
<div class="circle-image">
<i id="travel" class="fa fa-plane fly"></i>
</div>
<div class="circle-text">
<p>Travel industry</p>
</div>
</div>
<button type="button" class="btn toggle-effects">Turn off effects</button>
Thanks for your answers. I decided to try the css approach for animation using http://www.w3schools.com/css/css3_animations.asp as a guide.
All I did was add the css animation:
i.fly {
-webkit-animation-name: flying;
-webkit-animation-duration: 4s;
-webkit-animation-iteration-count: infinite;
animation-name: flying;
animation-duration: 4s;
animation-iteration-count: infinite;
}
#-webkit-keyframes flying {
0% {
right: 0px;
bottom: 0px;
}
100% {
right: -50px;
bottom: 50px;
}
}
#keyframes flying {
0% {
right: 0px;
bottom: 0px;
}
100% {
right: -50px;
bottom: 50px;
}
}
on js:
$("#travel").toggleClass("fly");
Most important thing was to toggle the effect with the button
First of all if you need an event to be executed once after a delay you should use setTimeout() function nstead of setInterval().
And instead of using .animate in JavaScript you can simply add a class fly to your element using .toggleClass() function.
This is a working snippet:
var $fly = $('.fly');
var flyplane = function() {
setTimeout(function() {
$fly.toggleClass('fly');
}, 2000);
};
flyplane();
$(".toggle-effects").on("click", function() {
$("#travel").toggle(0, flyplane);
}); //end of button click
.fly{
right: -50
bottom: +50
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hobbie-box">
<div class="circle-image">
<i id="travel" class="fa fa-plane"></i>
</div>
<div class="circle-text">
<p>Travel industry</p>
</div>
</div>
<input type="button" class="toggle-effects" value="click" />
You could just check for a var like this
$fly = $(".fly")
fly = true
flyplane = function(){
setInterval(function() {
if(fly){
$fly.animate({
right: '-=50',
bottom: '+=50'
}, 2000, function() {
$fly.removeAttr("style");
});
}
}, 2000);
};
$(".toggle-effects").on("click", function () {
fly = !fly
});
.fly{
width: 3px;
height: 3px;
position: absolute;
background-color: #00ff00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fly"></div>

How to Animate (slide) content adjacent to content with jquery toggle()

I am setting up a page which the user can hide the side bar if they wish. I am trying to use the jqeuryui to do this with the following js code
// TOGGLE JS
$(function () {
function runEffect() {
var options = {};
$("#effect").toggle('slide', options, 500);
};
$("#button").click(function () {
runEffect();
return false;
});
});
I have this working in a JSFiddle here http://jsfiddle.net/jwg4U/
However, when you look at the JSFiddle you will notice that my main content area which is a DIV called #content does not animate, it just jumps into place when I toggle the sidebar.
I would like the content div to also slide into place seamlessly and follow the toggle as it if it attached to it.
I have looked at jquery animate, but not sure how to implement this with the slide?
A Second part I am struggling with is how to change the button text when the sidebar is closed to say "Show Sidebar" - Weather it is open or closed right now it just says "Hide Sidebar"
Looking for some help
Thanks
See this updated fiddle : http://jsfiddle.net/jwg4U/23/
HTML:
<div id="container" style="width:800px">
<div id="header">
<h1>HEADER</h1>
</div>
<div class="toggler">
<div id="effect" class="ui-widget-content ui-corner-all">
<div id="menu" style="background-color:#FFD700;height:300px;width:100px;float:left;">
<h3>SIDEBAR</h3>
</div>
</div>
<div id="content" style="background-color:#EEEEEE;height:300px;">Main Content goes here</div>
</div>
Hide Sidebar
<div id="footer" style="background-color:#FFA500;clear:both;text-align:center;">
FOOTER</div>
</div>
​
JS:
// TOGGLE JS
$(function() {
var i = 0;
function runEffect() {
var options = {};
if (i === 0) {
i = 1;
$(".toggler").animate({
left: -100
}, {
duration: 500
});
}
else {
i = 0;
$(".toggler").animate({
left: 0
}, {
duration: 500
});
}
}
$("#button").click(function() {
if (i === 0) {
$(this).html("Show Sidebar");
}
else {
$(this).html("Hide Sidebar");
}
runEffect();
return false;
});
});
// TABS JS
$(function() {
$("#tabs").tabs();
});​
CSS:
.toggler {
float: left;
position: relative;
}
#button {
padding: .5em 1em;
text-decoration: none;
}
#effect {
position: relative;
float: left;
}
#content{
position: relative;
float: left;
width: 500px;
}
#button{
float: left;
clear: both;
}
#header{
background-color: #000;
color: #FFF;
}​
The jsfiddle for the complete answer : http://jsfiddle.net/jwg4U/22/
$('#effect').animate({
width: 'toggle',
height: 'toggle'
}, {
duration: 500,
specialEasing: {
width: 'linear',
height: 'linear'
},
complete: function() {
$("#content").animate(
{ left: '+=100px' },
60,
'easeInQuad',
function ()
{
if(isOpen)
{
isOpen=false;
$("#button").html('Show Sidebar');
}
else
{
isOpen=true;
$("#button").html('Hide Sidebar');
}
});
}
});

How to add a custom right-click menu to a webpage?

I want to add a custom right-click menu to my web application. Can this be done without using any pre-built libraries? If so, how to display a simple custom right-click menu which does not use a 3rd party JavaScript library?
I'm aiming for something like what Google Docs does. It lets users right-click and show the users their own menu.
NOTE:
I want to learn how to make my own versus using something somebody made already since most of the time, those 3rd party libraries are bloated with features whereas I only want features that I need so I want it to be completely hand-made by me.
Answering your question - use contextmenu event, like below:
if (document.addEventListener) {
document.addEventListener('contextmenu', function(e) {
alert("You've tried to open context menu"); //here you draw your own menu
e.preventDefault();
}, false);
} else {
document.attachEvent('oncontextmenu', function() {
alert("You've tried to open context menu");
window.event.returnValue = false;
});
}
<body>
Lorem ipsum...
</body>
But you should ask yourself, do you really want to overwrite default right-click behavior - it depends on application that you're developing.
JSFIDDLE
Was very useful for me. For the sake of people like me, expecting the drawing of menu, I put here the code I used to make the right-click menu:
$(document).ready(function() {
if ($("#test").addEventListener) {
$("#test").addEventListener('contextmenu', function(e) {
alert("You've tried to open context menu"); //here you draw your own menu
e.preventDefault();
}, false);
} else {
//document.getElementById("test").attachEvent('oncontextmenu', function() {
//$(".test").bind('contextmenu', function() {
$('body').on('contextmenu', 'a.test', function() {
//alert("contextmenu"+event);
document.getElementById("rmenu").className = "show";
document.getElementById("rmenu").style.top = mouseY(event) + 'px';
document.getElementById("rmenu").style.left = mouseX(event) + 'px';
window.event.returnValue = false;
});
}
});
// this is from another SO post...
$(document).bind("click", function(event) {
document.getElementById("rmenu").className = "hide";
});
function mouseX(evt) {
if (evt.pageX) {
return evt.pageX;
} else if (evt.clientX) {
return evt.clientX + (document.documentElement.scrollLeft ?
document.documentElement.scrollLeft :
document.body.scrollLeft);
} else {
return null;
}
}
function mouseY(evt) {
if (evt.pageY) {
return evt.pageY;
} else if (evt.clientY) {
return evt.clientY + (document.documentElement.scrollTop ?
document.documentElement.scrollTop :
document.body.scrollTop);
} else {
return null;
}
}
.show {
z-index: 1000;
position: absolute;
background-color: #C0C0C0;
border: 1px solid blue;
padding: 2px;
display: block;
margin: 0;
list-style-type: none;
list-style: none;
}
.hide {
display: none;
}
.show li {
list-style: none;
}
.show a {
border: 0 !important;
text-decoration: none;
}
.show a:hover {
text-decoration: underline !important;
}
<!-- jQuery should be at least version 1.7 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="contextmenu.js"></script>
<link rel="stylesheet" href="contextmenu.css" />
<div id="test1">
Google
Link 2
Link 3
Link 4
</div>
<!-- initially hidden right-click menu -->
<div class="hide" id="rmenu">
<ul>
<li>
Google
</li>
<li>
Localhost
</li>
<li>
C
</li>
</ul>
</div>
A combination of some nice CSS and some non-standard html tags with no external libraries can give a nice result (JSFiddle)
HTML
<menu id="ctxMenu">
<menu title="File">
<menu title="Save"></menu>
<menu title="Save As"></menu>
<menu title="Open"></menu>
</menu>
<menu title="Edit">
<menu title="Cut"></menu>
<menu title="Copy"></menu>
<menu title="Paste"></menu>
</menu>
</menu>
Note: the menu tag does not exist, I'm making it up (you can use anything)
CSS
#ctxMenu{
display:none;
z-index:100;
}
menu {
position:absolute;
display:block;
left:0px;
top:0px;
height:20px;
width:20px;
padding:0;
margin:0;
border:1px solid;
background-color:white;
font-weight:normal;
white-space:nowrap;
}
menu:hover{
background-color:#eef;
font-weight:bold;
}
menu:hover > menu{
display:block;
}
menu > menu{
display:none;
position:relative;
top:-20px;
left:100%;
width:55px;
}
menu[title]:before{
content:attr(title);
}
menu:not([title]):before{
content:"\2630";
}
The JavaScript is just for this example, I personally remove it for persistent menus on windows
var notepad = document.getElementById("notepad");
notepad.addEventListener("contextmenu",function(event){
event.preventDefault();
var ctxMenu = document.getElementById("ctxMenu");
ctxMenu.style.display = "block";
ctxMenu.style.left = (event.pageX - 10)+"px";
ctxMenu.style.top = (event.pageY - 10)+"px";
},false);
notepad.addEventListener("click",function(event){
var ctxMenu = document.getElementById("ctxMenu");
ctxMenu.style.display = "";
ctxMenu.style.left = "";
ctxMenu.style.top = "";
},false);
Also note, you can potentially modify menu > menu{left:100%;} to menu > menu{right:100%;} for a menu that expands from right to left. You would need to add a margin or something somewhere though
According to the answers here and on other 'flows, I've made a version that looks like the one of Google Chrome, with css3 transition.
JS Fiddle
Lets start easy, since we have the js above on this page, we can worry about the css and layout. The layout that we will be using is an <a> element with a <img> element or a font awesome icon (<i class="fa fa-flag"></i>) and a <span> to show the keyboard shortcuts. So this is the structure:
<a href="#" onclick="doSomething()">
<img src="path/to/image.gif" />
This is a menu option
<span>Ctrl + K</span>
</a>
We will put these in a div and show that div on the right-click. Let's style them like in Google Chrome, shall we?
#menu a {
display: block;
color: #555;
text-decoration: no[...]
Now we will add the code from the accepted answer, and get the X and Y value of the cursor. To do this, we will use e.clientX and e.clientY. We are using client, so the menu div has to be fixed.
var i = document.getElementById("menu").style;
if (document.addEventListener) {
document.addEventListener('contextmenu', function(e) {
var posX = e.clientX;
var posY = e.client[...]
And that is it! Just add the css transisions to fade in and out, and done!
var i = document.getElementById("menu").style;
if (document.addEventListener) {
document.addEventListener('contextmenu', function(e) {
var posX = e.clientX;
var posY = e.clientY;
menu(posX, posY);
e.preventDefault();
}, false);
document.addEventListener('click', function(e) {
i.opacity = "0";
setTimeout(function() {
i.visibility = "hidden";
}, 501);
}, false);
} else {
document.attachEvent('oncontextmenu', function(e) {
var posX = e.clientX;
var posY = e.clientY;
menu(posX, posY);
e.preventDefault();
});
document.attachEvent('onclick', function(e) {
i.opacity = "0";
setTimeout(function() {
i.visibility = "hidden";
}, 501);
});
}
function menu(x, y) {
i.top = y + "px";
i.left = x + "px";
i.visibility = "visible";
i.opacity = "1";
}
body {
background: white;
font-family: sans-serif;
color: #5e5e5e;
}
#menu {
visibility: hidden;
opacity: 0;
position: fixed;
background: #fff;
color: #555;
font-family: sans-serif;
font-size: 11px;
-webkit-transition: opacity .5s ease-in-out;
-moz-transition: opacity .5s ease-in-out;
-ms-transition: opacity .5s ease-in-out;
-o-transition: opacity .5s ease-in-out;
transition: opacity .5s ease-in-out;
-webkit-box-shadow: 2px 2px 2px 0px rgba(143, 144, 145, 1);
-moz-box-shadow: 2px 2px 2px 0px rgba(143, 144, 145, 1);
box-shadow: 2px 2px 2px 0px rgba(143, 144, 145, 1);
padding: 0px;
border: 1px solid #C6C6C6;
}
#menu a {
display: block;
color: #555;
text-decoration: none;
padding: 6px 8px 6px 30px;
width: 250px;
position: relative;
}
#menu a img,
#menu a i.fa {
height: 20px;
font-size: 17px;
width: 20px;
position: absolute;
left: 5px;
top: 2px;
}
#menu a span {
color: #BCB1B3;
float: right;
}
#menu a:hover {
color: #fff;
background: #3879D9;
}
#menu hr {
border: 1px solid #EBEBEB;
border-bottom: 0;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"/>
<h2>CSS3 and JAVASCRIPT custom menu.</h2>
<em>Stephan Stanisic | Lisence free</em>
<p>Right-click anywhere on this page to open the custom menu. Styled like the Google Chrome contextmenu. And yes, you can use <i class="fa fa-flag"></i>font-awesome</p>
<p style="font-size: small">
<b>Lisence</b>
<br /> "THE PIZZA-WARE LICENSE" (Revision 42):
<br /> You can do whatever you want with this stuff. If we meet some day, and you think this stuff is worth it, you can buy me a Pizza in return.
<br />
<a style="font-size:xx-small" href="https://github.com/KLVN/UrbanDictionary_API#license">https://github.com/KLVN/UrbanDictionary_API#license</a>
</p>
<br />
<br />
<small>(The white body background is just because I hate the light blue editor background on the result on jsfiddle)</small>
<div id="menu">
<a href="#">
<img src="http://puu.sh/nr60s/42df867bf3.png" /> AdBlock Plus <span>Ctrl + ?!</span>
</a>
<a href="#">
<img src="http://puu.sh/nr5Z6/4360098fc1.png" /> SNTX <span>Ctrl + ?!</span>
</a>
<hr />
<a href="#">
<i class="fa fa-fort-awesome"></i> Fort Awesome <span>Ctrl + ?!</span>
</a>
<a href="#">
<i class="fa fa-flag"></i> Font Awesome <span>Ctrl + ?!</span>
</a>
</div>
Simplest jump start function, create a context menu at the cursor position, that destroys itself on mouse leave.
oncontextmenu = (e) => {
e.preventDefault()
let menu = document.createElement("div")
menu.id = "ctxmenu"
menu.style = `top:${e.pageY-10}px;left:${e.pageX-40}px`
menu.onmouseleave = () => ctxmenu.outerHTML = ''
menu.innerHTML = "<p>Option1</p><p>Option2</p><p>Option3</p><p>Option4</p><p onclick='alert(`Thank you!`)'>Upvote</p>"
document.body.appendChild(menu)
}
#ctxmenu {
position: fixed;
background: ghostwhite;
color: black;
cursor: pointer;
border: 1px black solid
}
#ctxmenu > p {
padding: 0 1rem;
margin: 0
}
#ctxmenu > p:hover {
background: black;
color: ghostwhite
}
You could try simply blocking the context menu by adding the following to your body tag:
<body oncontextmenu="return false;">
This will block all access to the context menu (not just from the right mouse button but from the keyboard as well).
P.S. you can add this to any tag you want to disable the context menu on
for example:
<div class="mydiv" oncontextmenu="return false;">
Will disable the context menu in that particular div only
Pure JS and css solution for a truly dynamic right click context menu, albeit based on predefined naming conventions for the elements id, links etc.
jsfiddle
and the code you could copy paste into a single static html page :
var rgtClickContextMenu = document.getElementById('div-context-menu');
/** close the right click context menu on click anywhere else in the page*/
document.onclick = function(e) {
rgtClickContextMenu.style.display = 'none';
}
/**
present the right click context menu ONLY for the elements having the right class
by replacing the 0 or any digit after the "to-" string with the element id , which
triggered the event
*/
document.oncontextmenu = function(e) {
//alert(e.target.id)
var elmnt = e.target
if (elmnt.className.startsWith("cls-context-menu")) {
e.preventDefault();
var eid = elmnt.id.replace(/link-/, "")
rgtClickContextMenu.style.left = e.pageX + 'px'
rgtClickContextMenu.style.top = e.pageY + 'px'
rgtClickContextMenu.style.display = 'block'
var toRepl = "to=" + eid.toString()
rgtClickContextMenu.innerHTML = rgtClickContextMenu.innerHTML.replace(/to=\d+/g, toRepl)
//alert(rgtClickContextMenu.innerHTML.toString())
}
}
.cls-context-menu-link {
display: block;
padding: 20px;
background: #ECECEC;
}
.cls-context-menu {
position: absolute;
display: none;
}
.cls-context-menu ul,
#context-menu li {
list-style: none;
margin: 0;
padding: 0;
background: white;
}
.cls-context-menu {
border: solid 1px #CCC;
}
.cls-context-menu li {
border-bottom: solid 1px #CCC;
}
.cls-context-menu li:last-child {
border: none;
}
.cls-context-menu li a {
display: block;
padding: 5px 10px;
text-decoration: none;
color: blue;
}
.cls-context-menu li a:hover {
background: blue;
color: #FFF;
}
<!-- those are the links which should present the dynamic context menu -->
<a id="link-1" href="#" class="cls-context-menu-link">right click link-01</a>
<a id="link-2" href="#" class="cls-context-menu-link">right click link-02</a>
<!-- this is the context menu -->
<!-- note the string to=0 where the 0 is the digit to be replaced -->
<div id="div-context-menu" class="cls-context-menu">
<ul>
<li>link-to=0 -item-1 </li>
<li>link-to=0 -item-2 </li>
<li>link-to=0 -item-3 </li>
</ul>
</div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<head>
<title>Context menu - LabLogic.net</title>
</head>
<body>
<script language="javascript" type="text/javascript">
document.oncontextmenu=RightMouseDown;
document.onmousedown = mouseDown;
function mouseDown(e) {
if (e.which===3) {//righClick
alert("Right-click menu goes here");
}
}
function RightMouseDown() { return false; }
</script>
</body>
</html>
Tested and works in Opera 11.6, firefox 9.01, Internet Explorer 9 and chrome 17
Try this:
var cls = true;
var ops;
window.onload = function() {
document.querySelector(".container").addEventListener("mouseenter", function() {
cls = false;
});
document.querySelector(".container").addEventListener("mouseleave", function() {
cls = true;
});
ops = document.querySelectorAll(".container td");
for (let i = 0; i < ops.length; i++) {
ops[i].addEventListener("click", function() {
document.querySelector(".position").style.display = "none";
});
}
ops[0].addEventListener("click", function() {
setTimeout(function() {
/* YOUR FUNCTION */
alert("Alert 1!");
}, 50);
});
ops[1].addEventListener("click", function() {
setTimeout(function() {
/* YOUR FUNCTION */
alert("Alert 2!");
}, 50);
});
ops[2].addEventListener("click", function() {
setTimeout(function() {
/* YOUR FUNCTION */
alert("Alert 3!");
}, 50);
});
ops[3].addEventListener("click", function() {
setTimeout(function() {
/* YOUR FUNCTION */
alert("Alert 4!");
}, 50);
});
ops[4].addEventListener("click", function() {
setTimeout(function() {
/* YOUR FUNCTION */
alert("Alert 5!");
}, 50);
});
}
document.addEventListener("contextmenu", function() {
var e = window.event;
e.preventDefault();
document.querySelector(".container").style.padding = "0px";
var x = e.clientX;
var y = e.clientY;
var docX = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth || document.body.offsetWidth;
var docY = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight || document.body.offsetHeight;
var border = parseInt(getComputedStyle(document.querySelector(".container"), null).getPropertyValue('border-width'));
var objX = parseInt(getComputedStyle(document.querySelector(".container"), null).getPropertyValue('width')) + 2;
var objY = parseInt(getComputedStyle(document.querySelector(".container"), null).getPropertyValue('height')) + 2;
if (x + objX > docX) {
let diff = (x + objX) - docX;
x -= diff + border;
}
if (y + objY > docY) {
let diff = (y + objY) - docY;
y -= diff + border;
}
document.querySelector(".position").style.display = "block";
document.querySelector(".position").style.top = y + "px";
document.querySelector(".position").style.left = x + "px";
});
window.addEventListener("resize", function() {
document.querySelector(".position").style.display = "none";
});
document.addEventListener("click", function() {
if (cls) {
document.querySelector(".position").style.display = "none";
}
});
document.addEventListener("wheel", function() {
if (cls) {
document.querySelector(".position").style.display = "none";
static = false;
}
});
.position {
position: absolute;
width: 1px;
height: 1px;
z-index: 2;
display: none;
}
.container {
width: 220px;
height: auto;
border: 1px solid black;
background: rgb(245, 243, 243);
}
.container p {
height: 30px;
font-size: 18px;
font-family: arial;
width: 99%;
cursor: pointer;
display: flex;
justify-content: center;
align-items: center;
background: rgb(245, 243, 243);
color: black;
transition: 0.2s;
}
.container p:hover {
background: lightblue;
}
td {
font-family: arial;
font-size: 20px;
}
td:hover {
background: lightblue;
transition: 0.2s;
cursor: pointer;
}
<div class="position">
<div class="container" align="center">
<table style="text-align: left; width: 99%; margin-left: auto; margin-right: auto;" border="0" cellpadding="2" cellspacing="2">
<tbody>
<tr>
<td style="vertical-align: middle; text-align: center;">Option 1<br>
</td>
</tr>
<tr>
<td style="vertical-align: middle; text-align: center;">Option 2<br>
</td>
</tr>
<tr>
<td style="vertical-align: middle; text-align: center;">Option 3<br>
</td>
</tr>
<tr>
<td style="vertical-align: middle; text-align: center;">Option 4<br>
</td>
</tr>
<tr>
<td style="vertical-align: middle; text-align: center;">Option 5<br>
</td>
</tr>
</tbody>
</table>
</div>
</div>
Here is a very good tutorial on how to build a custom context menu with a full working code example (without JQuery and other libraries).
You can also find their demo code on GitHub.
They give a detailed step-by-step explanation that you can follow along to build your own right-click context menu (including html, css and javascript code) and summarize it at the end by giving the complete example code.
You can follow along easily and adapt it to your own needs. And there is no need for JQuery or other libraries.
This is how their example menu code looks like:
<nav id="context-menu" class="context-menu">
<ul class="context-menu__items">
<li class="context-menu__item">
<i class="fa fa-eye"></i> View Task
</li>
<li class="context-menu__item">
<i class="fa fa-edit"></i> Edit Task
</li>
<li class="context-menu__item">
<i class="fa fa-times"></i> Delete Task
</li>
</ul>
</nav>
A working example (task list) can be found on codepen.
I know this has already been answered, but I spent some time wrestling with the second answer to get the native context menu to disappear and have it show up where the user clicked.
HTML
<body>
<div id="test1">
Google
Link 2
Link 3
Link 4
</div>
<!-- initially hidden right-click menu -->
<div class="hide" id="rmenu">
<ul>
<li class="White">White</li>
<li>Green</li>
<li>Yellow</li>
<li>Orange</li>
<li>Red</li>
<li>Blue</li>
</ul>
</div>
</body>
CSS
.hide {
display: none;
}
#rmenu {
border: 1px solid black;
background-color: white;
}
#rmenu ul {
padding: 0;
list-style: none;
}
#rmenu li
{
list-style: none;
padding-left: 5px;
padding-right: 5px;
}
JavaScript
if (document.getElementById('test1').addEventListener) {
document.getElementById('test1').addEventListener('contextmenu', function(e) {
$("#rmenu").toggleClass("hide");
$("#rmenu").css(
{
position: "absolute",
top: e.pageY,
left: e.pageX
}
);
e.preventDefault();
}, false);
}
// this is from another SO post...
$(document).bind("click", function(event) {
document.getElementById("rmenu").className = "hide";
});
CodePen Example
Try This
$(function() {
var doubleClicked = false;
$(document).on("contextmenu", function (e) {
if(doubleClicked == false) {
e.preventDefault(); // To prevent the default context menu.
var windowHeight = $(window).height()/2;
var windowWidth = $(window).width()/2;
if(e.clientY > windowHeight && e.clientX <= windowWidth) {
$("#contextMenuContainer").css("left", e.clientX);
$("#contextMenuContainer").css("bottom", $(window).height()-e.clientY);
$("#contextMenuContainer").css("right", "auto");
$("#contextMenuContainer").css("top", "auto");
} else if(e.clientY > windowHeight && e.clientX > windowWidth) {
$("#contextMenuContainer").css("right", $(window).width()-e.clientX);
$("#contextMenuContainer").css("bottom", $(window).height()-e.clientY);
$("#contextMenuContainer").css("left", "auto");
$("#contextMenuContainer").css("top", "auto");
} else if(e.clientY <= windowHeight && e.clientX <= windowWidth) {
$("#contextMenuContainer").css("left", e.clientX);
$("#contextMenuContainer").css("top", e.clientY);
$("#contextMenuContainer").css("right", "auto");
$("#contextMenuContainer").css("bottom", "auto");
} else {
$("#contextMenuContainer").css("right", $(window).width()-e.clientX);
$("#contextMenuContainer").css("top", e.clientY);
$("#contextMenuContainer").css("left", "auto");
$("#contextMenuContainer").css("bottom", "auto");
}
$("#contextMenuContainer").fadeIn(500, FocusContextOut());
doubleClicked = true;
} else {
e.preventDefault();
doubleClicked = false;
$("#contextMenuContainer").fadeOut(500);
}
});
function FocusContextOut() {
$(document).on("click", function () {
doubleClicked = false;
$("#contextMenuContainer").fadeOut(500);
$(document).off("click");
});
}
});
http://jsfiddle.net/AkshayBandivadekar/zakn7Lwb/14/
You can do it with this code.
visit here for full tutorial with automatic edge detection http://www.voidtricks.com/custom-right-click-context-menu/
$(document).ready(function () {
$("html").on("contextmenu",function(e){
//prevent default context menu for right click
e.preventDefault();
var menu = $(".menu");
//hide menu if already shown
menu.hide();
//get x and y values of the click event
var pageX = e.pageX;
var pageY = e.pageY;
//position menu div near mouse cliked area
menu.css({top: pageY , left: pageX});
var mwidth = menu.width();
var mheight = menu.height();
var screenWidth = $(window).width();
var screenHeight = $(window).height();
//if window is scrolled
var scrTop = $(window).scrollTop();
//if the menu is close to right edge of the window
if(pageX+mwidth > screenWidth){
menu.css({left:pageX-mwidth});
}
//if the menu is close to bottom edge of the window
if(pageY+mheight > screenHeight+scrTop){
menu.css({top:pageY-mheight});
}
//finally show the menu
menu.show();
});
$("html").on("click", function(){
$(".menu").hide();
});
});
`
<script language="javascript" type="text/javascript">
document.oncontextmenu = RightMouseDown;
document.onmousedown = mouseDown;
function mouseDown(e) {
if (e.which==3) {//righClick
alert("Right-click menu goes here");
}
}
function RightMouseDown() {
return false;
}
</script>
</body>
</html>
A simple way you could do it is use onContextMenu to return a JavaScript function:
<input type="button" value="Example" onContextMenu="return RightClickFunction();">
<script>
function RightClickFunction() {
// Enter your code here;
return false;
}
</script>
And by entering return false; you will cancel out the context menu.
if you still want to display the context menu you can just remove the return false; line.
Tested and works in Opera 12.17, firefox 30, Internet Explorer 9 and chrome 26.0.1410.64
document.oncontextmenu =function( evt ){
alert("OK?");
return false;
}
For those looking for a very simple self-contained implementation of a custom context menu using bootstrap 5 and jQuery 3, here it is...
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<title>Custom Context Menu</title>
</head>
<style>
#context-menu {
position: absolute;
display: none;
}
</style>
<body>
<div class="container-fluid p-5">
<div class="row p-5">
<div class="col-4">
<span id="some-element" class="border border-2 border-primary p-5">Some element</span>
</div>
</div>
<div id="context-menu" class="dropdown clearfix">
<ul class="dropdown-menu" style="display:block;position:static;margin-bottom:5px;">
<li><a class="dropdown-item" href="#" data-value="copy">Copy</a></li>
<li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item" href="#" data-value="select-all">Select All</a></li>
</ul>
</div>
<script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
<script>
$('body').on('contextmenu', '#some-element', function(e) {
$('#context-menu').css({
display: "block",
left: e.pageX,
top: e.pageY
});
return false;
});
$('html').click(function() {
$('#context-menu').hide();
});
$("#context-menu li a").click(function(e){
console.log('in context-menu item, value = ' + $(this).data('value'));
});
</script>
</body>
</html>
Adapted from https://codepen.io/anirugu/pen/xjjxvG
<script>
function fun(){
document.getElementById('menu').style.display="block";
}
</script>
<div id="menu" style="display: none"> menu items</div>
<body oncontextmenu="fun();return false;">
What I'm doing up here
Create your own custom div menu and set the position: absolute and display:none in case.
Add to the page or element to be clicked the oncontextmenu event.
Cancel the default browser action with return false.
User js to invoke your own actions.
You should remember if you want to use the Firefox only solution, if you want to add it to the whole document you should add contextmenu="mymenu" to the <html> tag not to the body tag.
You should pay attention to this.
<html>
<head>
<style>
.rightclick {
/* YOUR CONTEXTMENU'S CSS */
visibility: hidden;
background-color: white;
border: 1px solid grey;
width: 200px;
height: 300px;
}
</style>
</head>
<body>
<div class="rightclick" id="ya">
<p onclick="alert('choc-a-late')">I like chocolate</p><br><p onclick="awe-so-me">I AM AWESOME</p>
</div>
<p>Right click to get sweet results!</p>
</body>
<script>
document.onclick = noClick;
document.oncontextmenu = rightClick;
function rightClick(e) {
e = e || window.event;
e.preventDefault();
document.getElementById("ya").style.visibility = "visible";
console.log("Context Menu v1.3.0 by IamGuest opened.");
}
function noClick() {
document.getElementById("ya").style.visibility = "hidden";
console.log("Context Menu v1.3.0 by IamGuest closed.");
}
</script>
<!-- Coded by IamGuest. Thank you for using this code! -->
</html>
You can tweak and modify this code to make a better looking, more efficient contextmenu. As for modifying an existing contextmenu, I'm not sure how to do that... Check out this fiddle for an organized point of view. Also, try clicking the items in my contextmenu. They should alert you a few awesome messages. If they don't work, try something more... complex.
I use something similar to the following jsfiddle
function onright(el, cb) {
//disable right click
document.body.oncontextmenu = 'return false';
el.addEventListener('contextmenu', function (e) { e.preventDefault(); return false });
el.addEventListener('mousedown', function (e) {
e = e || window.event;
if (~~(e.button) === 2) {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
return false;
}
});
// then bind Your cb
el.addEventListener('mousedown', function (e) {
e = e || window.event;
~~(e.button) === 2 && cb.call(el, e);
});
}
if You target older IE browsers you should anyway complete it with the ' attachEvent; case

Categories

Resources