Dictionary in a Webpage
Jul 03, 2015

I wanted to create in a webpage with text that had its meaning or translation embedded within, and a means to display them. Click on any of the underlined terms for a demo.

For each pair of key and its value, create markup as shown below

<span class='pair' 
      data-key='' 
      data-val='bring something into existence'>create</span>

Add the following JavaScript for implementing the action

var translateThis = function() {
    if (this.dataset.key === '') {
        this.dataset.key = this.innerHTML;
        this.innerHTML = this.dataset.val;
    }
    else {
        var tmp = this.dataset.key;
        this.dataset.key = this.innerHTML;
        this.innerHTML = tmp;
    }
}

window.onload = function() {
    var pairs = document.getElementsByClassName('pair');
    for (var i=0, j=pairs.length; i<j; i++) {
        pairs[i].onclick = translateThis;
    }
}

Optionally, style the term pairs

.pair {
    border-bottom: 1px dotted;
    cursor: pointer;
}

et voilà !

⬅︎ Click Once Measure Twice
➡︎ expressjs app with socket.io