Consider the set of codes I have:
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body style="color: black;">
<button id="button" onclick="start()" onfocusout="start()">Look Down</button>
<table>
<tr>
<td>
<a style="display: none;"; id="list" href="https://google.com/">Player-1</a>
</td>
</tr>
</table>
</body>
</html>
where my script file is:
function start(){
var a=document.getElementById("list").style;
if(a.display=="none") a.display="block";
else a.display="none";
}
function start() {
var a = document.getElementById("list").style;
if (a.display == "none") a.display = "block";
else a.display = "none";
}
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body style="color: black;">
<button id="button" onclick="start()" onfocusout="start()">Look Down</button>
<table>
<tr>
<td>
<a style="display: none;" ; id="list" href="https://google.com/">Player-1</a>
</td>
</tr>
</table>
</body>
</html>
Here, the button Look Down when pressed shows the link Player-1. But when I click the option Player-1, I lose the option as I have come out of focus of the button. As a result, I can’t go to the link I intend to go to. So, how can I fix this? I mean I want to click the link after pressing the button but don’t want to come out of the focus.
2
Answers
Behavior
<button>
,start()
is called and the<a>
is revealed, good 👍.<a>
, the<button>
loses it’s focus to<a>
which triggers a "focusout" event on<button>
thereby callingstart()
again which removes the<a>
, bad 👎.Solutions
Simply remove the
onfocusout
inline event handler (see Figure I and Example A).If you want
<a>
to disappear if anything but<button>
and<a>
is clicked, then you just want<a>
to disappear and not toggle between there and gone which is whatstart()
does. To get aforementioned behavior, delegate the "click" event by registering a common ancestor element and making the "click" event handler determine specific behavior for specific elements (see Example B and event delegation).Figure I
Example A
Layout Corrections
<html>
will have only a single<head>
and a single<body>
as direct children.<head>
proceeds<body>
.<meta>
,<title>
,<link>
, and<style>
are in the<head>
(preferably in that order).<script>
can be in the<head>
as well, but 99% of the time should reside within<body>
at the very bottom (in other words: as the last children of the<body>
right before the closing tag:</body>
)Example B
Event Handling
onclick
andonfocusout
have been removed from<button>
.NO JavaScript solution (only CSS)
If you solve this with JS funtions it will run on every click on the rest of the page. There’s no need of using so much processor power from the visitors.
This would be the approach without the use of JS (the link was inserted to a span so it could have a transition effect and delay that allows people to click it before it dissapears):