Material Box

Material Box

WEB Design & Material Images

JavaScript - Right Click Event

JavaScript

This is a simple code example for implementing a right-click event in JavaScript.


In the HTML, we specify a <div> tag with the id 'target' as the target to click.

<div id="target">0</div>

In the CSS, we set the size for the click target and specify text properties to display the click count.
We also set the 'cursor: pointer' to change the mouse cursor to a hand on hover.

#target {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 10px;
	color: white;
	width: 250px;
	height: 250px;
	border-radius: 50%;
	text-align: center;
	cursor: pointer;
	user-select: none;
	transition: 1s;
	font-size: 40px;
	background: #3cb371;
}

We select the target element using querySelector() and implement the click event using addEventListener().

We use preventDefault() to prevent the browser from opening the default context menu. When clicked, we increment the number within the target by 1.

// Implement the right-click event
document.querySelector('#target').addEventListener('contextmenu', () => {
	// Prevent the default behavior
	event.preventDefault();
	// Increment the number inside the target by 1
	document.querySelector('#target').textContent++;
	console.log('click!');
});

JavaScript - Right Click Event

TitleJavaScript - Right Click Event

CategoryJavaScript

Created

Update

AuthorYousuke.U