There are several ways to implement this, but if you want to specifically generate all of the data using JavaScript (for example, if you received data from an AJAX request to some API), you can get / create an object with key-value pairs corresponding to the words and their definitions respectively:
var dictionary = { first: '<h2>First</h2> Is the 1st definition.', second: '<h2>Second</h2> Is the 2nd definition.', third: '<h2>Third</h2> Is the 3rd definition.' };
Let's say you have the appropriate stylized markup to start with a shell consisting of two panels: one that will contain an unordered list of words, and the other that will contain the definition text:
<div id="words" class="panel"> <ul></ul> </div> <div id="definition" class="panel"></div>
Here you can iterate over each of the pairs in the dictionary object, where you then create HTML elements, assign click handlers and add them to the DOM for each:
// For each of the word/definition pairs.... $.each(dictionary, function(word, definition) { // Create a list item to hold the word var listItem = $('<li>').addClass('word').text(word); // Give the word item a click handler to display it definition when clicked listItem.click(function() { // Set the definition HTML to the current word definition $('#definition').html(definition); }); // Append it to the list of words in the DOM $('#words ul').append(listItem); });
Note that the click handler captures the definition in the context of the current dictionary iteration.
Here's a complete but minimal implementation of this method using jQuery with some explanatory comments:
$(function() {
.panel { display: inline-block; float: left; border-style: solid; border-width: medium; min-width: 200px; min-height: 250px; margin: 5px; padding: 5px; } .word.highlight { font-weight: bold; } .word { list-style-type: none; }
<div id="words" class="panel"> <ul></ul> </div> <div id="definition" class="panel"></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
source share