Skip to content

Instantly share code, notes, and snippets.

@ericfont
Created June 5, 2026 22:42
Show Gist options
  • Select an option

  • Save ericfont/6de2a632aca8ed51e11c036754f4d708 to your computer and use it in GitHub Desktop.

Select an option

Save ericfont/6de2a632aca8ed51e11c036754f4d708 to your computer and use it in GitHub Desktop.
anchor-test-javascript.html
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>How to trigger function from anchor tag</title>
<style>
</style>
</head>
<body>
<div class="box">
This is a text Box!
<a href="#a">Link1</a>
<a href="#b">Link2</a>
</div>
<button type="button">
<svg width="100%" height="100%" viewBox="0 0 20 20" fill="currentColor">
<circle cx="10" cy="10" r="5" />
</svg>
</button>
<script>
function changeColor(textcolor) {
document.querySelector('.box').style.color = textcolor;
}
// Function to run your specific logic
function handleAnchor() {
const hash = window.location.hash;
if (hash === '#a') {
console.log('Link1 loaded!');
changeColor('#00FF00')
} else if (hash === '#b') {
console.log('Link2 loaded!');
changeColor('#0000FF')
}
}
// Run on initial page load
window.addEventListener('load', handleAnchor);
// Run whenever the hash changes in the URL
window.addEventListener('hashchange', handleAnchor);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment