1

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);
})
})
4
  • Why in the world are you doing showarticleDescription(id=1) (or any other number)? While this isn't invalid syntax, this isn't Python either and there isn't any key value thing going on here; the closest thing you'll get are objects. Commented Mar 3, 2022 at 5:27
  • Well, I'm sorry. Just trying to learn here! Commented Mar 3, 2022 at 15:08
  • That's fine. Everyone makes mistakes when learning :P Commented Mar 3, 2022 at 18:14
  • Also I'm passing the id value to the function and after assigning it to the variable, I am also using it in the lines of code that follow. Hence, id=1. Commented Mar 3, 2022 at 19:38

2 Answers 2

1

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);
});
Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.