I have a site with thousands of htm documents on them. Sometimes I need to send someone to a specific paragraph to read. What I am looking for is a jquery plugin which simply adds ids to all the paragraphs, making them linkable, so we could send them to: http://www.demo.com/index.html#p_10 for instance.
Asked
Active
Viewed 107 times
0
-
You can use jquery each to add attributes but the problem will be that it will add the attributes after the url is read. – kleinohad Nov 16 '14 at 07:07
-
And why would that be a problem? – mplungjan Nov 16 '14 at 07:10
-
Why a plugin? I would suggest writing a small snippet that loops over the required `p` elements and adds an `id` attribute to them. – Vikram Deshmukh Nov 16 '14 at 07:11
2 Answers
1
I think what you want is just a simple code like this
jQuery(document).ready(function() {
jQuery('p').each(function(index, value) {
value.id = '_p' + index;
});
$('html, body').animate({
scrollTop: $(window.location.hash).offset().top
}, 500);
});
Here is an example that also displays the id set.

royhowie
- 11,075
- 14
- 50
- 67

Pedro Moreira
- 965
- 5
- 8
-
-
-
1You're right, it won't scroll unless you click on the browser URL field and press enter. Added a scroll animation to scroll to the paragraph, thank you for your comment. – Pedro Moreira Nov 16 '14 at 07:23
-
Brilliant, does the job perfectly, thank you Pedro and everyone else so much. – Anandajoti Nov 16 '14 at 07:31
-
Please see my update which does not modify the DOM and would be WAY faster than the above – mplungjan Nov 16 '14 at 09:55
1
Why a plugin? And no need for an ID
This should work if you insert a script into the page or into an existing external script
NOTE: This does NOT modify the DOM in any way and is WAY faster than an .each
$(function() {
var pIndexPos = location.hash.indexOf("p_");
if (pIndexPos!=-1) {
var pIndex = parseInt(location.hash.substring(pIndexPos+2),10)+1; // 1based for nth
var offsetTop = $("p:nth-child("+pIndex+")").offset().top-20; // - height of item
$('html, body').animate({
scrollTop: offsetTop
},500);
}
});

mplungjan
- 169,008
- 28
- 173
- 236
-
Dear mplungjan, thanks for the reply, and I'm sure this will be the answer for someone, but for myself I need to see exactly where to direct someone, so I do in fact need the ID. – Anandajoti Nov 16 '14 at 10:21
-
What will make the IDs visible to you? Unless you insert §1, §2 or something into the HTML of each paragraph, there will be no difference on the page. – mplungjan Nov 16 '14 at 10:53
-
Hi mplungjan, I can easily inspect the element and grab the ID, which saves me counting paras, etc. – Anandajoti Nov 16 '14 at 22:20
-