How to set focus and slide down to the html when button is clicked. How to slide to particular HTML element using javascript?
p:focus, p:active { color: green; } p { min-height: 250px; }
<body> <input type="button" onclick="getfocus()" value="Get focus"> <input type="button" onclick="losefocus()" value="Lose focus"> <p>Click the buttons to give focus and/or remove focus from the link above.</p> <p>Click the buttons to give focus and/or remove focus from the link above.</p> <p>Click the buttons to give focus and/or remove focus from the link above.</p> <p id="myAnchor">Click the buttons to give focus and/or remove focus from the link above.</p> <script> function getfocus() { document.getElementById("myAnchor").focus(); } function losefocus() { document.getElementById("myAnchor").blur(); } </script> </body>
Adding tabindex="0"
to p#myAnchor
solves the issue
tabindex="0"
means that the element should be focusable in sequential keyboard navigation, after any positive tabindex values and its order is defined by the document's source order.
function getfocus() { document.getElementById("myAnchor").focus(); } function losefocus() { document.getElementById("myAnchor").blur(); }
p:focus, p:active { color: green; } p { min-height: 200px; }
<input type="button" onclick="getfocus()" value="Get focus"> <input type="button" onclick="losefocus()" value="Lose focus"> <p>Click the buttons to give focus and/or remove focus from the link above.</p> <p>Click the buttons to give focus and/or remove focus from the link above.</p> <p>Click the buttons to give focus and/or remove focus from the link above.</p> <p tabindex="0" id="myAnchor">Click the buttons to give focus and/or remove focus from the link above.</p>
If by get focus you mean get there:
function getfocus() {
document.getElementById("myAnchor").scrollIntoView();
}
and if by loose focus if you mean going back to the top:
function looseFocus(){
window.scrollTo(0, 0);
}
but <p>
is not focusable. If you really want focus you need an anchor <p><a id="myAnchor" href="#">Click the buttons to give focus and/or remove focus from the link above.</a></p>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.