I need to know how can I disable a button when I hover over it, and then enable it when I'm not.
I've tried javascript, to disable it when the mouse coordinates were just so, but it didn't work.
Here's my code so far:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>This is a button</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<button type="button">Press Me</button>
<script src="script.js"></script>
</body>
</html>
This is for a joke, but I want it done quickly.
Thanks, Enlighten Me
PS: I'm new to StackOverflow, so please give any pointers to posts and such.
CodePudding user response:
Setup enter/leave event listeners on your button...
https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseenter_event https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseleave_event
CodePudding user response:
#joke-btn:hover{
display:none
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>This is a button</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<button id="joke-btn"type="button">Press Me</button>
<script src="script.js"></script>
</body>
</html>
CodePudding user response:
use this
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>This is a button</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<button type="button" id="hbtn">Press Me</button>
</body>
<script>
document.getElementById('hbtn').addEventListener('mouseenter',(event)=>{
event.target.disabled=true;
});
</script>
</html>
Hope this helps
CodePudding user response:
With JavaScript, you could add event listeners for the onmouseenter
and onmouseleave
DOM events and change the disabled
property value of the button
HTML element.
For example, in your case, a simple code solution (not the only possible one), would be something like:
const button = document.querySelector("button");
button.addEventListener("mouseenter", () => {
button.disabled = true;
});
button.addEventListener("mouseleave", () => {
button.disabled = false;
});
CodePudding user response:
I think the simplest option here is to just do it with css. However this doesn't actually disable the button, just the mouse click event, so you can still click the button when it is selected by using the return key:
Assign a class to your button (you can call it anything you want):
<button type="button">Press Me</button>
And in your CSS file disable mouse clicks:
.myButton:hover {
pointer-events: none;
}