Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

166
Views
How to make a JavaScript function more concise?

I'm new to StackOverflow and needed some help with the following JavaScript, jQuery question.

Is there a more concise way to code the following?:

jQuery(document).ready(function () {
$("#article1").click(function(){
    showarticleDescription(id=1);
})

$("#article2").click(function(){
    showarticleDescription(id=2);
})

$("#article3").click(function(){
    showarticleDescription(id=3);
})

$("#article4").click(function(){
    showarticleDescription(id=4);
})

$("#article5").click(function(){
    showarticleDescription(id=5);
})
})
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

We can use the starts with CSS selector:

$('[id^="article"]').click(function() {
  showarticleDescription(+this.id.substr(this.id.length - 1));
});

It'd be better though to apply a common class here (and possibly use a custom attribute). In the HTML you can do something like:

<div data-article="1" class="article">...</div>
<div data-article="2" class="article">...</div>
<div data-article="3" class="article">...</div>
$("article").click(function() {
  const article = +$(this).data("article");
  showarticleDescription(article);
});
about 4 years ago · Juan Pablo Isaza Report

0

Add classes and data attributes to your elements (rather than relying on ids) and use event delegation to capture the click events as they "bubble up" the DOM, and then call the function.

function showarticleDescription() {
  console.log($(this).data('id'))
}

$(document).ready(function () {
  $(document).on('click', '.article', showarticleDescription);
});
.article:hover { cursor: pointer; color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-id="1" class="article">One</div>
<div data-id="2" class="article">Two</div>
<div data-id="3" class="article">Three</div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!