Skip to content

Instantly share code, notes, and snippets.

@arterm-sedov
Last active June 17, 2024 15:45
Show Gist options
  • Save arterm-sedov/b137b24592f5e79d39750463e7ffcd33 to your computer and use it in GitHub Desktop.
Save arterm-sedov/b137b24592f5e79d39750463e7ffcd33 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>Copy Header Anchor</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
</head>
<body>
<div class="section">
<h1 id="section1">Section 1</h1>
<p>This is some content for section 1.</p>
</div>
<div class="section">
<h2 id="section2">Section 2</h2>
<p>This is some content for section 2.</p>
</div>
<div class="section">
<h3 id="section3">Section 3</h3>
<p>This is some content for section 3.</p>
</div>
<style>
.section {
position: relative;
}
h1::after,
h2::after,
h3::after,
h4::after,
h5::after,
h6::after {
content: '\f0c1'; /* FontAwesome link icon */
font-family: 'Font Awesome 5 Free';
font-weight: 900;
display: none;
cursor: pointer;
margin-left: 10px;
}
h1:hover::after,
h2:hover::after,
h3:hover::after,
h4:hover::after,
h5:hover::after,
h6:hover::after {
display: inline;
}
.notification {
position: absolute;
top: 50%;
background: #007BFF;
color: white;
padding: 10px;
border-radius: 5px;
display: none;
}
</style>
<script>
// Select all headers
const headers = document.querySelectorAll('h1, h2, h3, h4, h5, h6');
headers.forEach(header => {
// Create a notification
const notification = document.createElement('div');
notification.className = 'notification';
notification.textContent = 'Header anchor copied to clipboard!';
// Add the notification to the section
header.parentNode.appendChild(notification);
// Add click event to the header
header.addEventListener('click', () => {
// Copy the text using Clipboard API
navigator.clipboard.writeText(window.location.href + '#' + header.id)
.then(() => {
// Show the notification
notification.style.display = 'block';
// Hide the notification after 2 seconds
setTimeout(() => {
notification.style.display = 'none';
}, 2000);
})
.catch(err => {
console.error('Could not copy text: ', err);
});
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment