Horje

How to add a JavaScript when the anchor part has been changed

Click the button to change the anchor part of the current URL to #part5
index.html
Example: HTML
<!DOCTYPE html>
<html>
<body onhashchange="myFunction()">

<p>Click the button to change the anchor part of the current URL to #part5</p>

<button onclick="changePart()">Try it</button>

<p id="demo"></p>

<script>
// Using the location.hash property to change the anchor part
function changePart() {
  location.hash = "part5";
  let x = "The anchor part is now: " + location.hash;
  document.getElementById("demo").innerHTML = x;
}

// Alert some text if there has been changes to the anchor part
function myFunction() {
  alert("The anchor part has changed!");
}
</script>

</body>
</html>

Output should be:

How to add a JavaScript when the anchor part has been changed



Single Articles
How to add a JavaScript when the anchor part has been changedWindow Event Attributes


Related Articles
What is HTML onafterprint Event Attribute Window Event Attributes
What is HTML onbeforeprint Event Attribute Window Event Attributes
What is HTML onbeforeunload Event Attribute Window Event Attributes
What is HTML onerror Event Attribute Window Event Attributes
What is HTML onhashchange Event Attribute Window Event Attributes
What is HTML onload Event Attribute Window Event Attributes
What is HTML onoffline Event Attribute Window Event Attributes

Type:
Html
Category:
Web Tutorial
Sub Category:
Window Event Attributes
Uploaded by:
Admin