Camelia
Camelia

Reputation: 93

how to change font size with a button in jquery that it is in "vw" instead of "px"

This works fine when the fonts are in "px" and texts increase and decrease properly but what if need fonts in "vw"?

$(".up").on("click", function() {

  var classname = $(this).parent().attr('id');
  var size = parseInt($(".txts").find('.' + classname).css('font-size'));
  console.clear()
  console.log("old size: "+size);
  if ((size + 2) <= 50) {
    size = size + 2;
    $(".txts").find('.' + classname).css('font-size', size);
  }
  console.log("new size: "+size);

});

$(".down").on("click", function() {
  if ((size - 2) >= 12) {
    $(this).siblings("h1").css("font-size", "-=2");
  }
});
body {
  margin: 20px;
}

.container {
  width: 500px;
  text-align: center;
}

h1 {
  height: 60px;
  padding: 0;
  margin: 0;
}

p {
  display: inline-block;
}

.font-size-label {
  margin-right: 20px;
}

#font-size {
  margin: 0 5px;
}

button {
  width: 30px;
  height: 30px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="txts">
  <h2 class="part1">Resize Me1</h2>
  <h2 class="part2">Resize Me2</h2>
</div>
<div class="container" id="part1">

  <p class="font-size-label">1</p>
  <button class="up">+</button>

  <button class="down">-</button>
</div>
<br><br>
<div class="container" id="part2">

  <p class="font-size-label">2</p>
  <button class="up">+</button>

  <button class="down">-</button>
</div>

could you please help me?

Upvotes: 1

Views: 215

Answers (1)

David
David

Reputation: 218847

You're setting the font-size value to just a number with no units:

size = size + 2;
$(".txts").find('.' + classname).css('font-size', size);

By default the browser is interpreting that as px. But you can specify any units you like:

size = size + 2;
$(".txts").find('.' + classname).css('font-size', size + 'vw');

or:

size = size + 2;
$(".txts").find('.' + classname).css('font-size', `${size}vw`);

Upvotes: 2

Related Questions