jQuery - Setting limits to number of appends

I am a beginner, working on a personal project, where I am trying to make a tally system for a darts game called 'Cricket'.

Please visit my code below:



$(document).ready(function() {
    var mark = $("<h1 class='mark'>I</h1>");
    if ($(".mark").length >= 3) return;

For each number there are a maximum 3 points(lines) a player can score. I managed to set a limit to the amount of lines I can append, however this applies to the whole application.

What I want is to be able to mark a maximum of three lines to each number (15 -> Bull), for each player.

Is there an easy fix I am missing, or am I approaching the problem in the wrong way?


Answers 1

  • how about this?

    $(document).ready(function() {
        if ($(this).children().length < 4)
          $(this).append("<h1 class='mark'>I</h1>");
    • first, $('h1').click(): this feels wrong/too generic to me. How easy is it to introduce another headline somewhere in the page and forget that there are click listeners attached to it.

      Adding the listener ti a class is way more specific, as you can name the class in a way that you don't use it anywhere else. And the only difference is, that you can now click the whole line, not just the number.

    • var mark = $("<h1 class='mark'>I</h1>");: no need to wrap that into a jquery element yourself, especialln not if you don't know wether it will be added or not. You can sinply pass the template to .append()

    • if(...) return; //else-code: I know this early out approach, and it is very useful to avoid nesting a lot of code into an else-block, but here we're talking about a single line. if..then feels more fluent (as in reading a sentence) than if..abort ... otherwise.

    This ain't critique about your apprach. As your code works, and it's only a few lines. It's rather a reflection how I'd set this up, and why.

Related Articles