addEventListener to right click event - javascript

I would like to add event listener to a right click event, i know how to deal with a simple click:
document.getElementById("myBtn").addEventListener("mousedown", function(){ });
What about a right click event ?

Listen to the contextmenu event.

Just testing the click type using :
alert("You pressed button: " + event.button)

<!DOCTYPE html>
<html>
<head>
<style>
div { background: yellow; border: 1px solid black; padding: 10px; }
div {
background: yellow;
border: 1px solid black;
padding: 10px;
}
</style>
</head>
<body>
<div oncontextmenu="myFunction(event)">
<p>Right-click inside this box to see the context menu!
</div>
<script>
function myFunction(e) {
e.preventDefault();
//do something differant context menu
alert("You right-clicked inside the div!");
}
</script>
<!--if it helpful visit once http://topprojects.ml for more stuf-->
</body>
</html>

document.body.addEventListener("mousedown", event => {
if (event.button == 0) { // left click for mouse
doSomething;
else if (event.button == 1) { // right click for mouse
doAnotherThing;
else { // other buttons on the mouse
doOtherThings;
}
}

Related

How do I run queryCommandState for a certain div (and not the whole page)?

How do I detect if an item is bold, ONLY within my contenteditable div, and not when the user clicks anywhere else on the entire page?
Here's my JSFiddle with the code.
I'm trying to run document.queryCommandState("bold") but only for my contenteditable="true" div.
I've googled for a while and can't find anything. I've tried replacing/adding my div selector $(".text-editor") to the word document in a few different ways, which doesn't work. I feel like I'm missing something obvious. Thanks!
HTML:
<div contenteditable="true" class="text-editor">Content <b>editable</b>. Type here...</div>
<div class="normal-div">Content <b>not</b> editable.</div>
Click on the bold (and not bold) text in the two boxes. Result:
<div class="is-bold">The text your cursor's on is BOLD.</div>
<div class="is-not-bold">The text your cursor's on is NOT BOLD.</div>
<br>^^ I want this green result to only change when you're clicking inside the editable box.
CSS:
.text-editor {
border: 2px solid red;
margin-bottom: 10px;
}
.normal-div {
border: 2px solid blue;
margin-bottom: 10px;
}
.is-bold {
display: none;
color: green;
}
.is-not-bold {
display: none;
color: green;
}
.active {
display: block;
}
jQuery:
setInterval(function () {
var isItBold = document.queryCommandState("bold");
if (isItBold == true) {
$(".is-bold").addClass("active");
$(".is-not-bold").removeClass("active");
}
else {
$(".is-bold").removeClass("active");
$(".is-not-bold").addClass("active");
}
}, 100)
You can check if contenteditable is being focused first, before doing any of that.
var editable = $("[contenteditable]")
setInterval(function () {
if (!editable.is(":focus")) return
var isItBold = document.queryCommandState("bold");
if (isItBold == true) {
$(".is-bold").addClass("active");
$(".is-not-bold").removeClass("active");
}
else {
$(".is-bold").removeClass("active");
$(".is-not-bold").addClass("active");
}
}, 100)
Also setInterval is not necessary here. You can bind on click event for example.

fadeToggle on body click

I have this div which shows/hides with display:none/block by clicking on an id #cart. The div opens and closes by clicking on element with the id but I want to close the div on body click too. How can I do it please?
Code I am using is below:
jQuery("#cart").on("click", function() {
jQuery(".shopping-cart").fadeToggle( "fast");
});
jQuery("#cart, body").on("click", function() {
jQuery(".shopping-cart").fadeToggle("fast");
});
What you can do is add a listener to the entire window and check for clicks. When there is a click, we check which element has been clicked and check on whether it's the element. We repeat this for the parent element as well.
<!DOCTYPE html>
<html>
<head>
<script>
function checkClickOutsiteElement(clickedElement, elementToCheck){
var iterator = clickedElement;
while(true){
// The click was in the element.
if( iterator === elementToCheck )
return;
// Go to the parent.
if( !iterator.parentElement ){
alert('outside menu');
return;
}
iterator = iterator.parentElement;
}
}
window.addEventListener('click', function(event){
checkClickOutsiteElement(event.target, document.getElementById('menu'));
});
</script>
</head>
<body>
<div class="wrapper">
<div id="menu" style="width: 100px; height: 100px; background-color: red;"></div>
</div>
<div class="wrapper">
<div id="not_menu" style="width: 100px; height: 100px; background-color: green;"></div>
</div>
</body>
</html>
You probably want two separate functions, since your cart button should toggle both ways, but the body click handler should only toggle out.
Protip: on() isn't doing anything for you that click() wouldn't, the way you're using it. The latter is a bit cleaner.
jQuery("#cart").click(function() {
jQuery(".shopping-cart").fadeToggle("fast");
});
jQuery("body").click(function() {
jQuery(".shopping-cart").fadeOut("fast");
});
Protip 2: Easily and safely alias jQuery to $ like so:
jQuery(function($) { // document ready with dollar alias
$("#cart").click(function() {
...
});
I have this div which shows/hides with display:none/block by clicking
on an id #cart. The div opens and closes by clicking on element with
the id but I want to close the div on body click too.
In vanilla javascript, you can:
write a function to show / hide the div
add a click event listener to #cart
add a click event listener to body
Working Example:
// Grab #cart
const cart = document.getElementById('cart');
// Grab .myDiv
const myDiv = document.getElementsByClassName('div')[0];
// Function to toggle .myDiv
const toggleMyDiv = (e) => {
if (e.target === e.currentTarget) {
myDiv.dataset.display = (myDiv.dataset.display === 'show') ? 'hide' : 'show';
}
}
// Add Click Event Listener to #cart
cart.addEventListener('click', toggleMyDiv, false);
document.body.addEventListener('click', toggleMyDiv, false);
body,
#cart {
cursor: pointer;
}
div {
display: inline-block;
width: 100px;
height: 100px;
line-height: 100px;
text-align: center;
font-weight: bold;
}
#cart {
color: rgb(255, 255, 255);
background-color: rgb(255, 0, 0);
}
.div {
color: rgb(255, 0, 0);
background-color: rgb(255, 255, 0);
}
.div[data-display="show"] {
opacity: 1;
}
.div[data-display="hide"] {
opacity: 0;
}
<div id="cart">Cart</div>
<div class="div show" data-display="show">myDiv</div>

How to prevent removing "section" from <div contenteditable> when editing?

How to prevent a user from removing <section> inside <div contenteditable> editor during editing (at least by pressing "Delete"/"Backspace" keys)?
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
<style>
#editor {
width: 100%;
height: 300px;
border: 1px black solid;
}
#dont-remove-me-please{
width: 100%;
height: 100px;
border: 1px red dashed;
font-weight: bold;
user-select: none;
}
</style>
</head>
<body>
<div id="app"></div>
<div contenteditable="true" id="editor">
<div>hey guys!</div>
<div><strong>more text...</strong></div>
<section id="dont-remove-me-please" contenteditable="false">DONT' REMOVE ME!!!</section>
<div><br></div>
</div>
<script>
document.getElementById('editor').focus()
</script>
</body>
</html>
Thank You.
You can set contenteditable=false to children to prevent them from being editable.
However if you still want the children to be editable but the child dom elements shouldn't be removable I think you need to listen to backspace/delete events and see how these effect the dom and undo the changes if they remove dom nodes. Trying to figure this out myself
Edit: this is what I did
function onpaste(e: ClipboardEvent) {
e.preventDefault();
const selection = window.getSelection();
// Don't allow deleting nodes
if (selection.anchorNode.isSameNode(selection.focusNode)) {
// get text representation of clipboard
const text = e.clipboardData.getData("text/plain");
// insert text manually, but without new line characters as can't support <br/>s yet
document.execCommand("insertHTML", false, text.replace(/\n/g, ""));
}
}
function onkeydownInEditable(e: KeyboardEvent) {
if (e.key === "Enter") {
e.preventDefault();
}
if (e.key === "Backspace" || e.key === "Delete" || e.key === "Paste") {
const selection = window.getSelection();
// Don't allow deleting nodes
if (!selection.anchorNode.isSameNode(selection.focusNode))
e.preventDefault();
}
}
elementEditing.addEventListener("keydown", onkeydownInEditable);
elementEditing.addEventListener("paste", onpaste);
To achieve expected result, use below click event listener and add contenteditable attribute based on id
<script>
document.getElementById('editor').addEventListener('click', function(e) {
if(e.target.id !=="dont-remove-me-please"){
e.target.setAttribute("contentEditable", true);
}
}, false);
</script>
code sample - https://codesandbox.io/s/rypy7wkn5m
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
<style>
#editor {
width: 100%;
height: 300px;
border: 1px black solid;
}
#dont-remove-me-please{
width: 100%;
height: 100px;
border: 1px red dashed;
font-weight: bold;
user-select: none;
}
</style>
</head>
<body>
<div id="app"></div>
<div id="editor">
<div>hey guys!</div>
<div><strong>more text...</strong></div>
<section id="dont-remove-me-please" contenteditable="false">DONT' REMOVE ME!!!</section>
<div><br></div>
</div>
<script>
document.getElementById('editor').focus()
</script>
<script>
document.getElementById('editor').addEventListener('click', function(e) {
if(e.target.id !=="dont-remove-me-please"){
e.target.setAttribute("contentEditable", true);
}
}, false);
</script>
</body>
</html>

Check box not being changed as I would expect

I am trying to make a simple widget that allows the user to select either the check box OR the whole div to change its value. I have the following code:
$(document).ready(function() {
$(document).on("click", ".inputCheck", function(event) {
event.stopImmediatePropagation();
event.preventDefault();
$(this).closest(".outter").trigger("click");
});
$(document).on("click", ".outter", function(event) {
console.log("inside");
event.stopImmediatePropagation();
event.preventDefault();
var $checkBox = $(this).find("input");
$(this).removeClass("selected");
$checkBox.prop("checked", !$checkBox.prop("checked"));
if ($checkBox.prop("checked"))
$(this).addClass("selected");
});
});
.outter {
width: 100px;
height: 100px;
border-style: solid;
border-width: 1px;
}
.outter:hover,
.inputCheck:hover {
cursor: pointer;
}
<!DOCTYPE HTML>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div class="outter">
<input class="inputCheck" type="checkbox">
<div>This is a test</div>
</div>
</body>
</html>
It works as normal when the div is selected I.e. Checkbox changing values and a new class 'selected' being added to the .outter class. When the checkbox is selected I try to stop all defaults and propagation and then trigger the same code as selecting the div to change the class value. However the check box stays the same. Can someone please tell me why this isn't working and how to fix it?
Thanks
You don't need to stop propagation or anything. You can just check if the click was on the input or not, then change the input checked status like following. The click on the input will automatically be propagated to the parent div. You can check the click origin using event.target and make necessary actions.
$(document).ready(function() {
$(".outter").click(function(event) {
console.log('clicked');
var $checkBox = $(this).find("input");
$(this).removeClass("selected");
if (!$(event.target).is($checkBox)) {
$checkBox.prop("checked", !$checkBox.prop("checked"));
}
if ($checkBox.prop("checked"))
$(this).addClass("selected");
event.stopPropagation();
});
});
.outter {
width: 100px;
height: 100px;
border-style: solid;
border-width: 1px;
}
.outter:hover,
.inputCheck:hover {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="outter">
<input class="inputCheck" type="checkbox" />
<div id="testIt">This is a test</div>
</div>
$(document).ready(function() {
$(document).on("click", ".inputCheck", function(event) {
event.stopImmediatePropagation();
$(this).closest(".outter").trigger("click");
});
$(document).on("click", ".outter", function(event) {
console.log("inside");
event.stopImmediatePropagation();
var $checkBox = $(this).find("input");
if ($checkBox.prop("checked"))
$(this).addClass("selected");
else
$(this).removeClass("selected");
});
});
.outter {
width: 100px;
height: 100px;
border-style: solid;
border-width: 1px;
}
.outter:hover,
.inputCheck:hover {
cursor: pointer;
}
<!DOCTYPE HTML>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div class="outter">
<input class="inputCheck" type="checkbox">
<div>This is a test</div>
</div>
</body>
</html>

javascript how do i use the hover element on a div-element using a script with namespace?

In this code i change the color of my div while hovering the mouse over it. How can i achieve this without using style and instead put it in a script with namespace?
<html>
<head>
<title></title>
<style type="text/css">
.link-container {
border: 1px solid;
width: 50%;
height: 20px;
}
.link-container a {
display: block;
background: green;
height: 100%;
text-align: center;
}
.link-container a:hover {
background: red;
}
</style>
</head>
<body>
<div class="link-container">
<a>hover to change color</a>
</div>
</body>
</html>
You can use mouseover event of the element.
[].forEach.call(document.getElementsByClassName('link-container'),function(e){
e.addEventListener("mouseover", function(){
this.style.background='red'
});
});
EDIT:
You need mouseout event to remove the applied style.
[].forEach.call(document.getElementsByClassName('link-container'),function(e){
e.addEventListener("mouseover", function(){
this.style.background='red'
});
e.addEventListener("mouseout", function(){
this.style.background='inherit'
});
})
add eventListeners and have then fire functions in your namespace (say myApp)
var myApp = {
hover: function(event){
event.target.setAttribute("style", "background-color:red;")
},
out: function(event){
event.target.setAttribute("style", "background-color:green;")
}
}
var item = document.getElementById("btn");
item.addEventListener("mouseover", myApp.hover, false);
item.addEventListener("mouseout", myApp.out, false);
Plunker here

Categories

Resources