Dropdown box updates useful onscreen information
by azrizhaziq
HTML
<!-- Learn about this code on MDN: https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Live_Regions -->
<fieldset>
<legend>Planet information</legend>
<label for="planetsSelect">Planet:</label>
<select id="planetsSelect">
<option value="">Select a planet…</option>
<option value="mercury">Mercury</option>
<option value="venus">Venus</option>
<option value="earth">Earth</option>
<option value="mars">Mars</option>
</select>
<button id="renderPlanetInfoButton">Go</button>
</fieldset>
<div role="region" id="planetInfo">
<h2 id="planetTitle">No planet selected</h2>
<p id="planetDescription">Select a planet to view its description</p>
</div>
<p><small>Information courtesy <a href="https://en.wikipedia.org/wiki/Solar_System#Inner_Solar_System">Wikipedia</a></small></p>
JavaScript
const PLANETS_INFO = {
mercury: {
title: 'Mercury',
description: 'Mercury is the smallest and innermost planet in the Solar System. It is named after the Roman deity Mercury, the messenger to the gods.'
},
venus: {
title: "Venus",
description: 'Venus is the second planet from the Sun. It is named after the Roman goddess of love and beauty.'
},
earth: {
title: "Earth",
description: 'Earth is the third planet from the Sun and the only object in the Universe known to harbor life.'
},
mars: {
title: "Mars",
description: 'Mars is the fourth planet from the Sun and the second-smallest planet in the Solar System after Mercury. In English, Mars carries a name of the Roman god of war, and is often referred to as the "Red Planet".'
}
};
function renderPlanetInfo(planet) {
const planetTitle = document.querySelector('#planetTitle');
const planetDescription = document.querySelector('#planetDescription');
if (planet in PLANETS_INFO) {
planetTitle.textContent = PLANETS_INFO[planet].title;
planetDescription.textContent = PLANETS_INFO[planet].description;
} else {
planetTitle.textContent = 'No planet selected';
planetDescription.textContent = 'Select a planet to view its description';
}
}
const renderPlanetInfoButton = document.querySelector('#renderPlanetInfoButton');
renderPlanetInfoButton.addEventListener('click', event => {
const planetsSelect = document.querySelector('#planetsSelect');
const selectedPlanet = planetsSelect.options[planetsSelect.selectedIndex].value;
renderPlanetInfo(selectedPlanet);
});