Material Box

Material Box

WEB Design & Material Images

JavaScript - Prevent link behavior for button tag

JavaScript

A method and simple code example to prevent link behavior for <button> tags in JavaScript using preventDefault().


The HTML has two button elements.\r\nButton A uses JavaScript's "preventDefault()" to prevent link behavior, while Button B specifies "type=\"button\"" in the HTML to prevent link behavior.

<button id="btn-a">Button A</button>
<button type="button" id="btn-b">Button B</button>

The click event of the buttons is implemented with addEventListener().

To prevent default link behavior, use event.preventDefault().

The code example logs to the console when the button click event executes.

// Event when button clicked
document.querySelector('#btn-a').addEventListener('click', () => {
	// Prevent default behavior
	event.preventDefault();

	console.log('click')
		
});

JavaScript - Prevent link behavior for button tag

TitleJavaScript - Prevent link behavior for button tag

CategoryJavaScript

Created

Update

AuthorYousuke.U