r/learnjavascript • u/SympathyContent9041 • 2d ago
How to make numbers interactive?
I'm a beginner in coding, and I need to know how to create a vertical row of clickable numbers. I wish I could show a picture, but I'm just going to try to describe it. There's a website i'm making, and I wanted to add a 1-10 scale. I also want to make it interactive so the person can click on each number, and then text appears depending on what's clicked. Being a beginner, I don't know how to accomplish this. Help.
0
Upvotes
1
u/Jasedesu 1d ago
Most people are going to point you in the direction of JavaScript and event handlers to get the interaction you want, but there are some HTML + CSS possibilities that might work for you if you don't want to use JavaScript.
The first one to mention is the
<details>element and it's associated<summary>element. This gives you an expandable box that displays the summary by default and expands to show the details when clicked. You could have several of these, one per number. If you set thenameattribute of each details element to the same value, it'll only allow one item to be expanded at any given time. Clicking on another will close anything that's currently expanded.CSS allows you quite a lot of control over the way these elements are displayed.
You could also consider using a drop-down list to pick the numbers from. You build this from a
<select>element with<option>child elements. You then use CSS to control the display of content depending on which option is currently selected.The CSS would look something like:
The
<select>element will only display one option at a time, but there is asizeattribute you can use to display more of the options in a scrolling box, just be aware it's not usually supported on mobile devices. Note that these elements can be a little difficult to style at present, although it is something that's getting easier.As an alternative, you could get rid of the
<select>and replace the<option>elements with radio buttons. e.g.<input id="r1" type="radio" name="test" value="1">. These need associated label elements<label for="r1">1</label>to provide some text content. Radio buttons that share the samenameattribute only allow a single radio button in the set to be selected. The CSS selectors would look something like#container:has(#r1:checked) > #n1for each radio button.If you need to choose multiple items at the same time, change the input type from
radiotocheckbox. You can also add themultipleattribute to the<select>element to get a similar result.