JSFiddle - React, Tailwind, and code Playground

by nathanlogan

HTML

<h2>Cities</h2>
<div id="cities"></div>

<h3>City Info</h3>
<div id="cityInfo"></div>

CSS

li {
    padding:0 10px 10px;
}
p {
    padding:10px;
    border:2px solid pink;
}

JavaScript

// data - an array of city objects
 var cities = [ 	{name: "Moscow", count: 12, content: "<p>Moscow</p>"}, 
		{name: "Amsterdam", count: 25, content: "<p>Amsterdam </p>"}, 
		{name: "Lisbon", count: 15, content: "<p>Lisbon </p>"}, 
		{name: "Berlin", count: 19, content: "<p>Berlin </p>"}, 
		{name: "Madrid", count: 25, content: "<p>Madrid </p>"} ];

// iterate through the data and render the template
// - since it's so basic, just doing it inline (could use it's own method)
// - a more complex app/page would require a more robust templating solution

var cityTemplate = '<ul>';
for (var i=0; i<cities.length; i++) {
    // since the easiest/best/fastest way to access a given value of an array is by index, set up the DOM element to easily provide that for us
    cityTemplate += '<li data-cityid="'+ i +'">'+ cities[i].name +'</li>';
}
cityTemplate += '</ul>';

// set up DOM
// - this could be modularized into it's own method, as well, but jQuery makes it so simple that it's overkill to do so

$('#cities')
    // add our cities to the DOM in one shot (only hit the DOM once)
    .append( cityTemplate )

    // set up the click listener to take advantage of event delegation
    .on( 'click', 'li', function() {
        // populate the cityInfo div with its corresponding array index data 
        $('#cityInfo').html( cities[ $(this).data('cityid') ].content );
    })
    
    // show the first one on load
    .find('li:first').click();