zaarr78 zaarr78 - 3 months ago 10
HTML Question

Custom placeholder in jquery

I'm trying to make a custom

placeholder
in
jquery
since I'm using a
contenteditable
attribute.But for some reasons I can remove the
placeholder
when I start typing text but it isn't working when I'm trying to remove the text.

HTML

<div class="FormDescriptionContainer">
<div class="FormDescriptionPlaceholder">Iam a placeholder</div>
<p class="FormDescription" contenteditable="true" ></p>
</div>


Jquery

$(".FormDescription").keydown(function(event) {
$(".FormDescriptionPlaceholder").css('display', 'none');
if($(".FormDescription").text().length<=0)
{
$(".FormDescriptionPlaceholder").css('display', 'block');
}

})

Answer

Use keyup/input event instead of keydown

As in keydown, value of comtenteditable is not updated when user has entered some content in input-element.

Refer onKeyPress Vs. onKeyUp and onKeyDown

$(".FormDescription").keyup(function(event) {
  $(".FormDescriptionPlaceholder").css('display', 'none');
  if ($(".FormDescription").text().length <= 0) {
    $(".FormDescriptionPlaceholder").css('display', 'block');
  }
})
.FormDescription {
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="FormDescriptionContainer">
  <div class="FormDescriptionPlaceholder">Iam a placeholder</div>
  <p class="FormDescription" contenteditable="true"></p>
</div>

Issue with keydown, check the current value printed in console,

$(".FormDescription").keydown(function(event) {
  console.log($(".FormDescription").text());
  $(".FormDescriptionPlaceholder").css('display', 'none');
  if ($(".FormDescription").text().length <= 0) {
    $(".FormDescriptionPlaceholder").css('display', 'block');
  }
})
.FormDescription {
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="FormDescriptionContainer">
  <div class="FormDescriptionPlaceholder">Iam a placeholder</div>
  <p class="FormDescription" contenteditable="true"></p>
</div>

IMO, going with input event and having keyup as fallback is better approach(considering browser support for input-event)

$(".FormDescription").on('input keyup', function(event) {
  $(".FormDescriptionPlaceholder").css('display', 'none');
  if ($(this).text().length === 0) { //length will never be less than 0
    $(".FormDescriptionPlaceholder").css('display', 'block');
  }
})
.FormDescription {
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="FormDescriptionContainer">
  <div class="FormDescriptionPlaceholder">Iam a placeholder</div>
  <p class="FormDescription" contenteditable="true"></p>
</div>