JSFiddle - React, Tailwind, and code Playground
by sungsoonz
HTML
<h2 id="anchored-heading-01">H2 Anchored Heading 01</h2>
<h2 id="anchored-heading-02">H2 Anchored Heading 02</h2>
<h2>H2 Normal Heading</h2>
<h2 id="anchored-heading-03">H2 Anchored Heading 03</h2>
<h3 id="anchored-heading-03">H3 Anchored Heading 01</h3>
CSS
h2[id] {
cursor: pointer;
}
h2[id]:after {
content: "!!";
opacity: 0;
}
h2[id]:hover:after {
opacity: 1;
}
JavaScript
function copyLink(element) {
history.pushState("", document.title, window.location.pathname);
var hash = window.location.hash.replace('#', '');
if (hash != '') {
location.hash = '';
}
var url = window.location.href;
var $temp = $("<input>");
$("body").append($temp);
$temp.val(url + "#" + $(element).attr("id")).select();
document.execCommand("copy");
console.log($temp.val());
window.location.hash = $(element).attr("id");
$temp.remove();
}
var $headers = $('h2');
$headers.attr("id", function() {
return $(this)
.text() // get the h1 text
.trim() // remove spaces from start and the end
.toLowerCase() // optional
.replace(/\s/g, '_'); // convert all spaces to underscores
});
$(function() {
$("h2[id]").on("click", function() {
copyLink(this);
});
});