Replacing certain words with links to definitions using Javascript

Posted by adharris on Stack Overflow See other posts from Stack Overflow or by adharris
Published on 2010-04-25T17:53:59Z Indexed on 2010/04/25 18:03 UTC
Read the original article Hit count: 182

Filed under:
|
|
|

I am trying to create a glossary system which will get a list of common words and their definitions via ajax, then replace any occurrence of that word in certain elements (those with the useGlossary class) with a link to the full definition and provide a short definition on mouse hover. The way I am doing it works, but for large pages it takes 30-40 seconds, during which the page hangs. I would like to either decrease the time it takes to do the replacement or make it so that the replacement is running in the background without hanging the page.

I am using jquery for most of the javascript, and Qtip for the mouse hover. Here is my existing slow code:

$(document).ready(function () {
    $.get("fetchGlossary.cfm", null, glossCallback, "json");
});

function glossCallback(data)
{

    $(".useGlossary").each(function() {
        var $this = $(this);
        for (var i in data)
        {

            $this.html($this.html().replace(new RegExp("\\b" + data[i].term + "\\b", "gi"), function(m) {return makeLink(m, data[i].def);}));
        }
        $this.find("a.glossary").qtip({ style: { name: 'blue', tip: true } })
    });
}

function makeLink(m, def)
{
    return "<a class='glossary glossary" + m.replace(/\s/gi, "").toUpperCase() + "' href='reference/glossary.cfm' title='" + def + "'>" + m + "</a>";
}

Thanks for any feedback/suggestions!

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery