Yovav Yovav - 5 months ago 11
jQuery Question

How to add anchor jump tags to my headers using data tags?

I'm trying to make this more generic, not sure how to use the data tags...

My headers with < a > anchor tags looks like this:

<h4>Prohibited items<a class="anchor" id="prohibited-items" href="#prohibited-items" onclick="$('#prohibited-items').ScrollTo();"></a></h4>


I would like my < h4 > headers to look like this:

<h4 data-anchor="prohibited-items">Prohibited items</h4>


How can I inject anchor tags dynamically to all the < h4 > that contain the data-anchor tag?

UPDATE: this is what I ended up doing:

// Generate anchor tags by adding data-anchor data tag
// if data-anchor does not have a value the element text will be used to generate the anchor id
// for example: <h4 data-anchor>Sample title</h4> or <h4 data-anchor="custom-id">Sample title</h4>
$("[data-anchor]").each(function () {
var text = $(this).text();
var id = $(this).attr("data-anchor"); // Check if a custom id was provided
if (id != null && id.replace(/ /g, "") === "") {
id = text.replace(/[^\w\s]/gi, "-"); // Remove special characters
id = id.replace(/ /g, "-").toLowerCase(); // Replace spaces with "-"
}
// console.log("id = " + id + ", text = " + text);
$(this).attr("onclick", "$('#" + id + "').ScrollTo();"); // {offsetTop:70}
if (!$(this).hasClass("cursor-pointer"))
$(this).addClass("cursor-pointer");
$(this).html("<div class='anchor-space'>" + text + "</div><a " +
"class='anchor-marker no-print' " +
"id='" + id + "' " +
"href='#" + id + "' " +
"></a><span " +
"class='anchor-symbol no-print'" +
"></span>");
});


and

.anchor-marker {
top: -110px;
position: relative;
display: block;
}
.anchor-space {
margin-right: 30px;
}
.anchor-symbol {
float: right;
margin-top: -30px;
&:before {
font-family: "FontAwesome";
content: "\f13d"; // http://fontawesome.io/icon/anchor/
float: right;
}
}

Answer

Try the following

$('[data-anchor]').click(function(){
  var id = $(this).attr('data-anchor');
  $(id).scrollTo();
});

or:

$('[data-anchor]').each(function() {
  var text = $(this).text();
  var id =$(this).attr('data-anchor');
  $(this).html(text+'<a class="anchor" id="'+id.substring(1)+'" href="'id'" onclick="$('+id+').ScrollTo();"></a>')
});
Comments