Home > OS >  How to make a JavaScript function more concise?
How to make a JavaScript function more concise?

Time:03-03

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);
})
})

CodePudding user response:

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" >...</div>
<div data-article="2" >...</div>
<div data-article="3" >...</div>
$("article").click(function() {
  const article =  $(this).data("article");
  showarticleDescription(article);
});

CodePudding user response:

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" >One</div>
<div data-id="2" >Two</div>
<div data-id="3" >Three</div>

  • Related