I'm relatively new to web development. I started learning JavaScript a few months ago and it's going well. I made this code for someone on fiverr, and it got the job done, but I know there's a more efficient way to write this without using a click handler for each element. There has to be a way to know which element is clicked and show the proper one without a separate click handler for each element.
Here's the Codepen link to the code.
HTML
<div>
<a href="#" id="item-1">Item 1</a>
<a href="#" id="item-2">Item 2</a>
<a href="#" id="item-3">Item 3</a>
<a href="#" id="item-4">Item 4</a>
</div>
<div class="item-container">
<div class="item-block" id="1">
<h1>Item 1</h1>
<p>This is Item 1 content</p>
</div>
<div class="item-block" id="2">
<h1>Item 2</h1>
<p>This is item 2 content</p>
</div>
<div class="item-block" id="3">
<h1>Item 3</h1>
<p>This is item 3 content</p>
</div>
<div class="item-block" id="4">
<h1>Item 4</h1>
<p>This is item 4 content</p>
</div>
</div>
CSS
.item-block {
display: none;
}
JS
$(document).ready(function() {
$('#1').show();
})
$('#item-1').click(function() {
$('.item-block').hide();
$('#1').show();
})
$('#item-2').click(function() {
$('.item-block').hide();
$('#2').show();
})
$('#item-3').click(function() {
$('.item-block').hide();
$('#3').show();
})
$('#item-4').click(function() {
$('.item-block').hide();
$('#4').show();
})