user11877626
user11877626

Reputation:

How to slide to particular HTML element using javascript?

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>

Upvotes: 0

Views: 167

Answers (2)

emiliano67
emiliano67

Reputation: 191

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>

Upvotes: 0

User863
User863

Reputation: 20039

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>

Upvotes: 1

Related Questions