JQuery game, element disappear when in contact with another element issue - javascript

I am creating a game with jquery, the meaning of the game is that you should , with one element ( a bucket in this case "#spelare" ) catch other elements ".food" that are falling down from above. How can i make so that when the falling elements touch the (bucket), they disappear, and you get 1 score?
Thanks in advance for all help i can get!
Here is the code I have atm:
body{
text-align: center;
background-color:black;
}
#spelplan{
width: 1000px;
height:610px;
position:absolute;
margin-left:460px;
box-shadow: inset 0px 0px 50px;
background-color: green;
}
#spelare{
width:110px;
height: 12vh;
position: relative;
top:53.4vh;
background-image:url(hink.png);
background-size:cover;
}
.food{
width:50px;
height:50px;
position:absolute;
background-image:url(vattendroppe.png);
background-size:cover;
display:block;
}
p{
position:relative;
font-family: 'Electrolize', sans-serif;
}
#poäng{
color:white;
bottom:17vh;
right:45%;
}
#liv{
color:white;
bottom:18vh;
right:46.5%;
}
.fa-heart{
color:red;
bottom:21.5vh;
right:43.5%;
position:relative;
}
#info{
color:white;
font-family: 'Electrolize', sans-serif;
margin-top:68vh;
}
<!DOCTYPE html>
<html>
<head>
<title>Jquery Spel</title>
<meta charset="utf-8">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link href="https://fonts.googleapis.com/css?family=Electrolize" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).keydown(function(e){
if (e.keyCode ==39 && $("#spelare").css("left") < '880px')
$("#spelare").animate({left: '+=20px'}, 0);
else if (e.keyCode ==37 && $("#spelare").css("left") > '0px')
$("#spelare").animate({left: '-=20px'}, 0);
});
setInterval(spawnFood,2000);
setInterval(fall, 0);
});
function spawnFood(){
var spelplanWidth = $('#spelplan').width();
var randPosX = Math.floor((Math.random()*spelplanWidth));
var element = $("<div class='food'></div>").css('left',randPosX).css('bottom', '446px');
$("#spelplan").append(element);
}
function fall(){
var elementFall = $(".food").animate({top: '+=20px'}, 500);
$("#spelplan").append(elementFall);
}
</script>
</head>
<body>
<h2 style="color:white">JQUERY SPEL</h2>
<div id="spelplan">
<div id="spelare"> </div>
<div class="food"> </div>
<p id="poäng"> Poäng: </p>
<p id="liv"> Liv: </p>
<i class="fa fa-heart" aria-hidden="true"></i>
</div>
<div id="info">
<h1> Instruktioner: </h1>
<p> Spelet går ut på att du med hjälp av hinken och piltangenterna ska fånga alla vattendroppar! <br/> Du måste hålla ut i 40 sekunder, missa tre vattendroppar så förlorar du! </p>
</div>
</body>
</html>

You have to constently compare each falling element position versus the bucket position.
A nice place for it is in your fall() function.
Have a look!
CodePen
$(document).ready(function(){
var score=0;
var fails=0;
//Bucket movement
$(document).keydown(function(e){
//console.log(e.which);
// if left or right keyboard arrow
if (e.keyCode ==39 && $("#spelare").css("left") < '880px')
$("#spelare").animate({left: '+=20px'}, 0);
else if (e.keyCode ==37 && $("#spelare").css("left") > '0px')
$("#spelare").animate({left: '-=20px'}, 0);
});
// Game init
var spanfoodInterval = setInterval(spawnFood,2000);
var fallInterval = setInterval(fall, 0);
// Water append
function spawnFood(){
var spelplanWidth = $('#spelplan').width();
var randPosX = Math.floor((Math.random()*spelplanWidth));
var element = $("<div class='food'></div>").css('left',randPosX).css('bottom', '446px');
$("#spelplan").append(element);
}
// dropping object animation
function fall(){
var elementFall = $(".food").animate({top: '+=20px'}, 500);
//$("#spelplan").append(elementFall);
$(".food").each(function(){
if( typeof($(this)) !="undefined" && typeof($("#spelare"))!="undefined" ){
// item position
var thisPosition = $(this).position();
var thisWidth = $(this).width();
// Bucket position and width
var bucketPosition = $("#spelare").position();
var bucketWidth = $("#spelare").width();
var bucketHeight = $("#spelare").height();
// If object and bucket at same position
if( thisPosition.top >= bucketPosition.top
&& thisPosition.left >= bucketPosition.left
&& thisPosition.left <= bucketPosition.left + bucketWidth ){
$(this).remove();
score++;
//console.log(score);
// Update the score display
$("#score").html(score);
}
// Food not catched...
if( thisPosition.top >= bucketPosition.top + bucketHeight){
$(this).remove();
fails++;
//console.log("FAILS: "+fails);
}
// if more than 3 miss => Game over.
if(fails>3){
$("#failMsg").show();
$("#spelare").remove();
$(".food").remove();
clearInterval(spanfoodInterval);
clearInterval(fallInterval);
}
}
});
}
}); // ready
body{
text-align: center;
background-color:black;
}
#spelplan{
width: 1000px;
height:610px;
position:absolute;
margin-left:460px;
box-shadow: inset 0px 0px 50px;
background-color: green;
}
#spelare{
width:110px;
height: 12vh;
position: relative;
top:53.4vh;
background-image:url(https://placehold.it/350x150); /* hink.png); */
background-size:cover;
}
.food{
width:50px;
height:50px;
position:absolute;
background-image:url(https://placehold.it/350x150); /* vattendroppe.png); */
background-size:cover;
display:block;
}
p{
position:relative;
font-family: 'Electrolize', sans-serif;
}
#failMsg{
position:fixed;
top:50%;
left:50%;
transform:translate(50% 50%);
color:white;
font-size:4em;
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://fonts.googleapis.com/css?family=Electrolize" rel="stylesheet">
<h2 style="color:white">jQuery GAMES - Your score: <span id="score">0</span></h2><!-- JQUERY SPEL</h2-->
<div id="spelplan">
<div id="spelare"> </div>
<div class="food"> </div>
<p id="poäng"> Poäng: </p>
<p id="liv"> Liv: </p>
<i class="fa fa-heart" aria-hidden="true"></i>
</div>
<div id="info">
<h1> Instructions: </h1>
<p> The game is that you are using the bucket and the arrow keys to catch all the drops of water! <br/> You have to hold out for 40 seconds, missing three water drops, you lose! </p>
</div>
<div id="failMsg">Game over!</div>

Related

Making clone to swap to html elements with hammer.js

I'm trying to make swap between two divs, I mean, change one by other preserving events and everything.
Both have hammer events to detect swipe. When I make a swap elements in my project, they lost hammer events, but preserve other events like click.
To illustrate the behaviour I made this:
$(document).ready(function(){
$("#obj2").each(function(){
var $this = $(this);
var h = new Hammer(this);
h.get("swipe").set({ direction: Hammer.DIRECTION_ALL, threshold: 1, velocity:0.1 });
h.on("swipe",function(ev){
$this.text(ev.angle.toFixed(2));
});
});
$("#obj1").click(function(){
alert("this works");
});
$("#makeClone").click(function(){
$("#obj2").text("3. swipe again :(");
var aux = $("#obj2").clone(true);
$("#container2").html($("#container1").clone(true));
$("#container1").html(aux);
});
});
div.obj,#makeClone{
display:inline-block;
box-sizing:border-box;
width:300px;
height:150px;
text-align:center;
border-radius:10px;
background:#f44336;
font:18px/150px "Lato";
color:white;
margin-bottom:5px;
cursor:pointer;
}
#obj2{
background:#4caf50;
}
#makeClone{
background:#666;
height:50px;
font:12px/50px "hack";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.min.js"></script>
<script src="https://raw.githubusercontent.com/hammerjs/jquery.hammer.js/master/jquery.hammer.js"></script>
<div id="container1">
<div id="obj1" class="obj">click</div>
</div>
<div id="container2">
<div id="obj2" class="obj">1.swipe on me!</div>
</div>
<br><br>
<div id="makeClone">2.change with clone</div>
Do not clone your objects. Use .append instead of .html.
$(document).ready(function() {
$("#obj2").each(function() {
var $this = $(this);
var h = new Hammer(this);
h.get("swipe").set({
direction: Hammer.DIRECTION_ALL,
threshold: 1,
velocity: 0.1
});
h.on("swipe", function(ev) {
$this.text(ev.angle.toFixed(2));
});
});
$("#obj1").click(function() {
alert("this works");
});
$("#makeClone").click(function() {
$("#obj2").text("3. swipe again :(");
var d1 = $("#container1>div");
var d2 = $("#container2>div");
$("#container2").append(d1);
$("#container1").append(d2);
});
});
div.obj,
#makeClone {
display: inline-block;
box-sizing: border-box;
width: 300px;
height: 150px;
text-align: center;
border-radius: 10px;
background: #f44336;
font: 18px/150px "Lato";
color: white;
margin-bottom: 5px;
cursor: pointer;
}
#obj2 {
background: #4caf50;
}
#makeClone {
background: #666;
height: 50px;
font: 12px/50px "hack";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.min.js"></script>
<script src="https://raw.githubusercontent.com/hammerjs/jquery.hammer.js/master/jquery.hammer.js"></script>
<div id="container1">
<div id="obj1" class="obj">click</div>
</div>
<div id="container2">
<div id="obj2" class="obj">1.swipe on me!</div>
</div>
<br><br>
<div id="makeClone">2.change with clone</div>

CSS positioning / need idea's

Guy's I'm a bit stick on this project. Trying to create a Google Calander page. Giving a function an array of objects each object having 2 properties, start and end, print the following to the screen.
I'm almost done.... this is what I have so far
I'm stock on the positioning. If I should make the inner div's absolute or relative. Because when I make them relative, they drop down to much, if I make the absolute, then having trouble aligning them correctly.
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Title</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<div class="wrapper">
<div id="canv" class="canvas">
<!-- <div class="event">
<h1>Sample Item</h1>
<p>Sample location</p>
</div> -->
</div>
<div class="time">
<p>9:00 <span class="am">AM</span></p>
<p class="thirty">9:30</p>
<p>10:00 <span class="am">AM</span></p>
<p class="thirty">10:30</p>
<p>11:00 <span class="am">AM</span></p>
<p class="thirty">11:30</p>
<p>12:00 <span class="am">PM</span></p>
<p class="thirty">12:30</p>
<p>1:00 <span class="am">PM</span></p>
<p class="thirty">1:30</p>
<p>2:00 <span class="am">PM</span></p>
<p class="thirty">2:30</p>
<p>3:00 <span class="am">PM</span></p>
<p class="thirty">3:30</p>
<p>4:00 <span class="am">PM</span></p>
<p class="thirty">4:30</p>
<p>5:00 <span class="am">PM</span></p>
<p class="thirty">5:30</p>
<p>6:00 <span class="am">PM</span></p>
<p class="thirty">6:30</p>
<p>7:00 <span class="am">PM</span></p>
<p class="thirty">7:30</p>
<p>8:00 <span class="am">PM</span></p>
<p class="thirty">8:30</p>
<p>9:00 <span class="am">PM</span></p>
</div>
</div>
</div>
<script>
var events = [
{start: 30, end: 150},
{start: 540, end: 600},
{start: 560, end: 620},
{start: 610, end: 670}
];
var canvas = document.getElementById("canv");
var totalElem = 0;
var totalTop = 0;
var total = events.forEach(function(event, index){
var testArr = events;
var test = testArr.length - index;
if(index > 0 && test >=2 ){
totalElem++
}
})
function layOutDay(event){
var newArr = event;
event.forEach(function(event, index){
var env = document.createElement("div"),
h1 = document.createElement("h1"),
p = document.createElement("p"),
sampleItem = document.createTextNode("Sample Item"),
sampleLocation = document.createTextNode("Sample Location");
p.appendChild(sampleLocation);
h1.appendChild(sampleItem);
env.className = "event";
env.setAttribute('id', index)
env.appendChild(h1);
env.appendChild(p);
canvas.appendChild(env);
//conversion
//totalTop = keeping track of start of each event
var pixelsStart = (event.start * .86);
pixelsEnd = ((event.end - event.start) * .86);
totalTop += pixelsEnd;
console.log(totalTop, 'test');
env.style.top = pixelsStart + "px";
env.style.height = pixelsEnd + "px";
// check start collide with previous event
var test = newArr.length - index;
if(index > 0 && test >=2 ){
var start = event.start,
end = event.end,
check = newArr[index+1].start;
function between(check, start, end) {
return check >= start && check <= end;
}
if (between(check, start, end)) {
var newWidth = (96/totalElem)
env.style.width = newWidth + "%";
}
}
}) // end of loop
// correct placement
// 1. If 2 or more events - done
// 2. Grab values then check range
// 3. if within same range then run logic to divide with evently
// 4. else place elements as is
// var newArr = document.getElementsByClassName("event");
// if(newArr.length > 1){
// var start = obj.start;
// var end = obj.end;
// var check = checkObj.start
// var check = function between(check, start, end) {
// return check >= start && check <= end;
// }
// if (check(600, 560, 620)) {
// console.log('true')
// }
// }
}
layOutDay(events);
</script>
</body>
</html>
css
body {
font-size: 40px;
}
.wrapper {
position: relative;
}
.canvas {
background-color: #ECECEC;
border-left: 2px solid #ABABAB;
height: 620px;
width: 720px;
float: right;
margin-right: 300px;
margin-left: 10px;
position: relative;
}
p {
font-size: 12px;
font-family: Arial, Helvetica, sans-serif;
margin-bottom: 13px;
margin-bottom: 13px;
}
.am {
font-size: 10px;
color: #ADADAD;
}
.thirty {
font-size: 10px;
color: #ADADAD;
}
.wrapper {
width: 1100px;
}
.time {
text-align: right;
position: relative;
}
.event {
background-color: #ffffff;
border: 1px solid #D9D9D9;
border-left: 3px solid #63AF8F;
width: 96%;
margin-left: 10px;
margin-right: 0px;
position: relative;
float: right;
top: 28px;
height: 52px;
overflow: hidden;
}
.event h1 {
font-family: Arial, Helvetica, sans-serif;
font-size: 14px;
color: #63AF8F;
padding: 0;
padding-top: 5px;
padding-left: 5px;
margin: 0px;
}
.event p {
padding: 0;
padding-left: 5px;
margin: 0px;
color: #ADADAD;
}
/*# sourceMappingURL=../maps/style.css.map */
I believe the position relative is fine, you need to check your 'top' and 'height' calculations based on start and end positions.
Also, adjust margin positions to align properly.
And can use wrapper div and give some padding there.

Singular hover will not work

var totalMoney = 0;
var clickMultiplier = 1;
var incomeSecond = 0;
var totalVirus = 0;
var totalTrojan = 0;
var totalWorm = 0;
var totalServer = 0;
function totalMoneyText() {
totalMoney = totalMoney + 1 * clickMultiplier;
}
setInterval(function() {
totalMoney = incomeSecond + totalMoney;
incomeSecond = (totalWorm) + (totalTrojan * 2) + (totalVirus);
}, 1000);
setInterval(function() {
updateText();
}, 100);
setInterval(function() {
totalTrojan = totalTrojan * 1.001;
totalWorm = totalWorm * 1.01;
}, 5000);
function updateText() {
document.getElementById("totalMoney").innerHTML = totalMoney.toLocaleString("en-US", {
style: "currency",
currency: "USD",
maximumFractionDigits: 0
});
document.getElementById("buyablenum1").innerHTML = Math.round(totalVirus * 1000) / 1000;
document.getElementById("buyablenum2").innerHTML = Math.round(totalTrojan * 1000) / 1000;
document.getElementById("buyablenum3").innerHTML = Math.round(totalWorm * 1000) / 1000;
}
function buyable1() {
if (totalMoney > 49) {
totalMoney = totalMoney - 50;
totalVirus = totalVirus + 1;
} else {
window.alert("You don't have enough to buy that!")
}
}
function buyable2() {
if (totalMoney > 149) {
totalMoney = totalMoney - 150;
totalTrojan = totalTrojan + 1;
} else {
window.alert("You don't have enough to buy that!")
}
}
function buyable3() {
if (totalMoney > 499) {
totalMoney = totalMoney - 500;
totalWorm = totalWorm + 1;
} else {
window.alert("You don't have enough to buy that!")
}
}
function buyable4() {
if (totalMoney > 99) {
totalMoney = totalMoney - 100;
totalServer = totalServer + 1;
} else {
window.alert("You don't have enough to buy that!")
}
}
#font-face{
font-family:HackingT;
src:url(assets/HackingTrashed-Regular.ttf);
}
#font-face{
font-family:Currency;
src:url(assets/Currency.ttf);
}
#font-face{
font-family:Hacker;
src:url(assets/Hacker.tff);
}
body,
html {
overflow-x:hidden;
overflow-y:hidden;
}
html {
background:url(assets/background.png) no-repeat center center fixed;
-webkit-background-size:cover;
-moz-background-size:cover;
-o-background-size:cover;
background-size:cover;
}
head {} body {} #meme {
color:transparent;
}
.globalcontainer {
position:relative;
margin:0% 0;
min-height:100vh;
}
.buyablecontainer {
position:relative;
z-index:2;
}
.clickablecontainer {
margin:26.5% auto;
position:relative;
z-index:2;
}
#Money {
font-size:50px;
color:whitesmoke;
text-align:center;
font-family:"HackingT";
text-shadow:1px 1px grey;
margin:0 auto;
}
#totalMoney {
font-size:40px;
color:whitesmoke;
text-align:center;
font-family:"Currency";
letter-spacing:3px;
text-shadow:1px 1px grey;
margin:0 auto;
}
.column {
position:absolute;
}
.buyImg {
width:15%;
border:2px grey solid;
}
.noselect {
-webkit-touch-callout:none;
-webkit-user-select:none;
-khtml-user-select:none;
-moz-user-select:none;
-ms-user-select:none;
user-select:none;
cursor:default;
}
#imgComputer {
width:15%;
}
.clickable {
-webkit-touch-callout:none;
-webkit-user-select:none;
-khtml-user-select:none;
-moz-user-select:none;
-ms-user-select:none;
user-select:none;
cursor:default;
-webkit-user-drag:auto | element | none;
-moz-user-select:none | text | all | element -ms-user-select:none | text | all | element
}
.number {
color:snow;
padding:1px;
}
#buyImg:active {} .buyable1 {
position:relative;
}
.tooltip {
position:absolute;
margin:0% 1%;
padding:14% 44%;
border:4px grey solid;
background-color:black;
background-blend-mode:difference;
}
.tooltipheader {
font-family:"Hacker";
color:forestgreen;
position:absolute;
display:inline;
top:-10%;
left:0;
}
.tooltiptext {
color:forestgreen;
position:absolute;
font-family:"Hacker";
display:inline;
text-align:center;
font-size:15px;
left:0%;
top:50%
}
.tooltipincome {
position:absolute;
font-size:20px;
left:5%;
margin:-13% 24%;
font-family:"Hacker";
color:forestgreen;
}
#tooltip1 {
display:none;
}
#tooltip2 {
display:none;
}
#tooltip3 {
display:none;
}
#tooltip4 {
display:none;
}
#virus:hover~#tooltip1 {
display:inline;
}
#trojan:hover~#tooltip2 {
display:inline;
}
#worm:hover~#tooltip3 {
display:inline;
}
#server:hover~tooltip4 {
display:inline;
}
#server {
width:25%;
padding:1%;
}
<!DOCTYPE html>
<html>
<head>
<title>Hacker Clicker</title>
<link rel=stylesheet type="text/css" href="styles.css" />
<script type="text/javascript" src="scripts.js"></script>
<script src="http://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</head>
<body class=noselect>
<div class=globalcontainer>
<div class="header">
<a id=meme href="https://www.youtube.com/watch?v=dQw4w9WgXcQ">Click me</a>
<h1 class=noselect id=Money>Money</h1>
<h1 class=noselect id=t otalMoney>$0</h1>
</div>
<!-- Numbers and Buyables -->
<div class="container buyablecontainer noselect">
<div class="column">
<div class="buyable1">
<h2 class=number id=buyablenum1>0</h2>
<img draggable="false" id=virus onclick="buyable1()" class=buyImg src="assets/virus.png" />
<div id=tooltip1 class=tooltip>
<h1 class=tooltipheader>"Virus"</h1>
<h2 class=tooltipincome>Income: $1 per second Price:50</h2>
<p class=tooltiptext>A virus tries to infect anyone and everyone that it can, it's usually used as a way to collect revunue through email spam, aswell to fuck your life up.</p>
</div>
</div>
<div class="buyable2">
<h2 class=number id=buyablenum2>0</h2>
<img draggable="false" id=trojan onclick="buyable2()" class=buyImg src="assets/trojan.png" />
<div id=tooltip2 class=tooltip>
<h1 class=tooltipheader>"Trojan"</h1>
<h2 class=tooltipincome>Income:$2 per second 0.01% replication Price:150</h2>
<p class=tooltiptext>A trojan creates a backdoor to your computer and gives confidential or personal information to the creator.</p>
</div>
</div>
<div class="buyable3">
<h2 class=number id=buyablenum3>0</h2>
<img draggable="false" id=worm onclick="buyable3()" class=buyImg src="assets/worm.png" />
<div id=tooltip3 class=tooltip>
<h1 class=tooltipheader>"Worm"</h1>
<h2 class=tooltipincome>Income:$1 per second 1% replication Price:500</h2>
<p class=tooltiptext>A worm self replicates through the interwebs and lives inside everyone which it is allowed. They are used to do any ill-biddings that the creator wants.</p>
</div>
</div>
<div class="buyable4">
<h2 class=number id=buyablenum4>0</h2>
<img draggable="false" id=server onclick="buyable4()" class=buyImg src="assets/server.png" />
<div id=tooltip4 class=tooltip>
<h1 class=tooltipheader>"Server"</h1>
<h2 class=tooltipincome>Income:$0 +2 on click Price:100</h2>
<p class=tooltiptext>The more servers you got, the more you can hack. Get it foo?</p>
</div>
</div>
</div>
</div>
<div class=clickablecontainer align="center">
<img draggable="false" onclick="totalMoneyText()" id=imgComputer class=clickable src="assets/hacking.gif" />
</div>
</div>
</body>
</html>
Jsfiddle
What's supposed to show up
I apologize in advance for not being able to see the images, but if you try to hover over the 4 icons to the left they work except the last one, hopefully it isn't a simple mistake as I started HTML CSS and Javascript 2 days ago, but it is entirely possible and I'm sorry if that's the case :p.
Also, I'm having a hard time with CSS positioning things exactly where I want them, for example if I want to have an image in the center no matter what ever is around it how do I do that?
Any tips?
Typo in CSS.
#server:hover~tooltip4 {
should read
#server:hover~#tooltip4 {
Many refactoring possibilities here - happy learning!

clone div implementation doesn't work

I have a working javascript to clone a div and not move the other divs in the same line. But when I try to implement it in html it is not possible to close the maximized div.
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
<script type="text/javascript" src="java_test.js"></script>
<link href="max_css.css" rel="stylesheet" />
</head>
<body>
<div id="box1" class="kaesten" onclick="changeSize('box1', 600, 600)">test1</div>
<div id="box2" class="kaesten" onclick="changeSize('box2', 600, 600)">test2</div>
<div id="box3" class="kaesten" onclick="changeSize('box3', 600, 600)">test3</div>
<div id="box4" class="kaesten" onclick="changeSize('box4', 600, 600)">test4</div>
<div id="dummy" class="absoluteclass" onclick="changeSize('dummy', 600, 600)" ></div>
</body>
function changeSize(id, weight, height){
var elem = document.getElementById(id);
var currentAbsoluteElem = document.getElementById('dummy');
var text = elem.innerHTML;
currentAbsoluteElem.innerHTML = text;
currentAbsoluteElem.setAttribute('style','display:block');
/*Extra styling neeed to be done here*/
}
var elems = document.getElementsByClassName('kaesten');
for(var i = 0; i < elems.length; i++){
elems[i].onclick = function(){
changeSize(this.id, 600, 600);
}
}
var absoluteCl = document.getElementsByClassName('absoluteclass');
absoluteCl[0].onclick = function(){
console.log(document.getElementsByClassName('absoluteclass'))
document.getElementsByClassName('absoluteclass')[0].setAttribute('style','display:none');
}
.kaesten{
width:240px;
height:300px;
background-color:darkgrey;
background-position:center;
background-repeat:no-repeat;
text-shadow:0px 0px 3px #000;
border: 5px solid #F0F8ff;
vertical-align:top;
text-shadow: 3px 3px 4px #777;
float:left;
margin-left:30px;
}
.absoluteclass{
position:absolute;
background-color:darkgrey;
width:600px;
height:600px;
left:calc(30%);
display:none;
}
<div id="box1" class="kaesten">test1</div>
<div id="box2" class="kaesten">test2</div>
<div id="box3" class="kaesten">test3</div>
<div id="box4" class="kaesten">test4</div>
<div id="dummy" class="absoluteclass"></div>
Question: How can I implement the JavaScript function into my HTML to make the big div close by onclick?
you can modify your changeSize function like this.
function changeSize(id, weight, height){
var currentAbsoluteElem = document.getElementById('dummy');
if(id == null && weight == null && height == null){
currentAbsoluteElem.setAttribute('style','display:none');
}else{
var elem = document.getElementById(id);
var text = elem.innerHTML;
currentAbsoluteElem.innerHTML = text;
currentAbsoluteElem.setAttribute('style','display:block');
/*Extra styling neeed to be done here*/
}
}
and in your html
<div id="dummy" class="absoluteclass" onclick="changeSize()" ></div>
I hope this is what you want.

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