0

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.

Anandajoti
  • 73
  • 1
  • 9

2 Answers2

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.

http://jsfiddle.net/ekftprLt/2/

royhowie
  • 11,075
  • 14
  • 50
  • 67
Pedro Moreira
  • 965
  • 5
  • 8
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
  • Whatever floats your boat – mplungjan Nov 17 '14 at 05:30