Skip to content

Instantly share code, notes, and snippets.

@dolphinotaku
Last active June 28, 2018 04:12
Show Gist options
  • Save dolphinotaku/32279ed872984141306fbc9a9373e52d to your computer and use it in GitHub Desktop.
Save dolphinotaku/32279ed872984141306fbc9a9373e52d to your computer and use it in GitHub Desktop.
jQuery – How to automatically create heading anchors for links
<!DOCTYPE html>
<html>
<head>
<title>How to automatically create heading anchors for links</title>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/cferdinandi/smooth-scroll@14/dist/smooth-scroll.polyfills.min.js"></script>
<style>
.anchorBtn {
margin-left: 15px;
}
</style>
</head>
<body>
<script>
$(document).ready(function() {
$("h1, h2, h3, h4, h5, h6").each(function(i) {
var heading = $(this);
// create anchor
var headingtext = heading.text().toLowerCase().trim().replace(/[\.,-\/#!?$%\^&\*;:{}=\-_`~()]/g,"");
heading.attr("id",headingtext );
heading.attr("name",headingtext );
// create anchor button
var anchorIcon = $("<i></i>", {
class: "fas fa-link fa-xs"
})
var anchor = $( "<a></a>", {
href: "#"+headingtext,
class: "anchorBtn data-scroll"
})
heading.append( anchor.append(anchorIcon) );
});
var scroll = new SmoothScroll('a[href*="#"]');
});
</script>
<h1>Heading A</h1>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<h1>Heading B</h1>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<h1>Heading C</h1>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
</body>
</html>
@dolphinotaku
Copy link
Author

version 1.0.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment