Question

we have on our website professional book articles as like:

<h2>Article heading</h2>
<p>Text text text text text text[1] text text text text.</p>
<p>Text text text text text text text text text text.</p>
<p>Text text text[2] text text text text text text text.</p>
<p>Text text text text text text text text text text.</p>
<h3>Bibliography</h3>
<p>[1] NAME OF AUTHOR, Book, ISBN, etc.</p>
<p>[2] NAME OF ANOTHER AUTHOR, Book 2, ISBN, etc.</p>

that is stored in database (one table) and we can not change it in HTML output, only postprocessed in HTML template + JS.

We would like to acheave that after pageload it will be automatically appended the text from Bibliography section to corresponding the number in the text. Than show it with JS or CSS when onmouseover the number in text (that can we do). But we cannot find solution how make the search/append trick part.

Have someone solved some similar task? Or have some any suggestions or better the examples?

PS: The Biblography is every time prefacted with "<h3>Bibliography</h3>" and is located at bottom of the whole text. Every Book begins with "[number]".

Was it helpful?

Solution

Considering your restrictions and the severe lack of identifying elements in your HTML output, there is no really nice way to do this... still it is possible. You could try something like this:


First create an array of the Bibliography items:

var biblioArr = [];
var i = 1;
// Create array of bibliography items.
$("h3").nextAll("p").each(function(){ // Find each <p> after <h3>
    biblioArr[i] = $(this).html(); // Add <p> html to array
    i = i+1;
});

Now find the corresponding markers in the text and change the HTML:

i = 1;
// Add each array item to corresponding text as anchor titles.
$("h2").nextUntil("h3").each(function(){ // Find each <p> after <h2> until <h3>
    var textHtml = $(this).html(); // Grab the content of <p>
    if (textHtml.indexOf("["+i+"]") >= 0) { // If index found in this <p>
        textHtml = textHtml.replace("["+i+"]", "[<a href='#' class='biblio-anchor' title='"+biblioArr[i]+"'>"+i+"</a>]"); // Create new anchor
        $(this).html(textHtml); // Add new content
        i = i+1;
    }
});

Here is a working jsfiddle.


You can style the rollover/popup/title/tooltip however you wish.

Please note that this assumes that your bibliography items always appear in sequence (i.e. 2 always follows 1). Also note that this kind of thing is much better suited for server-side execution, the performance of jquery in these situations may not be too good.

Another alternative is to use a pre-existing plugin such as this one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top