Search code examples
javascriptjqueryhtmlcsspositioning

Struggling with positioning a div element created with jQuery


I have two different textareas with two different maxlenghts. The character count of each textarea will only show up once one of the textareas is on focus, i.e. the character count of both textareas will not show at the same time. The code works fine. However, I am struggling with the styling of the counter as it is created as followed aiming to work:

$counter = $("<div class='counter'/>");

As it is not in the HTML code, I am not being able to style it properly with absolute positioning and so on. If I do create the counter element in the HTML and call it's class in jQuery both counters show at the same time and right next to one another which is not what I am aiming for. I was wondering if you guys could help me.

I would like to set the counter in the right bottom corner of its respective textbox.

$(function() {

  $.fn.textCounter = function() {
  //for each
  return this.each(function(index) {
    //console.log("LocktonAsset"+index);
    var $this = $(this),
      maxLength = $this.prop("maxlength"),
      $counter = $("<div class='counter'/>");


    console.log(maxLength);
    $this.parent().after($counter);

    $this.on("focus", function() {
      $counter.addClass("visible");
    });

    $this.on("blur", function() {
      $counter.removeClass("visible");
    });

    $this.on("keyup", function() {
      var val = $this.val(),
          currentLength = val.length,
      remaining =
          (maxLength - currentLength),
        safePercent = maxLength * 80 / 100;

      $counter.text(remaining);

      var color = currentLength <= safePercent ? "blue" : "red";
      $counter.css("color", color);
    }); //end keyup
  }); //end each
}; //end textcounter


  $("textarea").textCounter();
});

.textbox {
  display: inline-block;
}

.textbox {
  background-color: pink;
  > textarea {
    width: 200px;
    height: 50px;
    padding: 10px;
  }
}

.counter {
  display: none;
  font-size: 10px;
  background-color: yellow;
}
.counter.visible {
  display: inline-block;
}

form {
  input {
    margin-top: 20px;
  }
}
<div class="container">
  <div class="wrapper">

    <!-- First textarea -->
    <div class="textbox">
      <textarea maxlength="50" placeholder="Write something..."></textarea>
    </div>

    <!-- Second textarea -->
    <div class="textbox">
      <textarea maxlength="100" placeholder="Write something..."></textarea>
    </div>

    <form>
      <input type="text" maxlength="10">
    </form>

  </div>
</div>

If you find it easier, here's my CodePen: https://codepen.io/fergos2/pen/bGGrqbr


Solution

  • I updated your code here https://codepen.io/ggrigorov/pen/MWWvRaX

    I made one small change to place the counter inside the textbox. And updated the styles so it can be positioned relative to the textbox.

    There can be other implementations, but this should work.

    Let me know if it doesn't.