Reputation: 6040
I am trying to write some code to change the size of text dynamically with a slider but it's not working.
$('input').on('change', function() {
var v = $(this).val();
$('.userText p').css('font-size', v + 'em')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="range" min="1.2" max="2.6" step=".2" id="slider" />
<div class="userText">
<p>Some text that should dynamically change size</p>
</div>
Can anyone offer any advice here please?
Upvotes: 3
Views: 3916
Reputation: 21351
Just add input
as an event as well because change
only fires when the mouse is released. I also added smaller steps and a start value of min for better usability.
document.querySelector('input').addEventListener('input', e => document.querySelector('p').style.fontSize = e.target.value + 'em');
<input type="range" value="1.2" min="1.2" max="2.6" step=".0002" id="slider" />
<p>Some text that should dynamically change size.</p>
For more information on differences across different browsers see onchange event on input type=range is not triggering in Firefox while dragging.
jQuery:
$('input').on('input', e => $('p').css('font-size', $(e.target).val() + 'em'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="range" value="1.2" min="1.2" max="2.6" step=".0002" id="slider" />
<p>Some text that should dynamically change size.</p>
Upvotes: 5
Reputation: 7303
Your demo works just fine. However the new value get's applied once you release the slider.
If you want to update the value instantly, use the input
event instead of the change
event:
$('input').on('input', function() {
var v = $(this).val();
$('p').css('font-size', v + 'em')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="range" min="1.2" max="2.6" step=".2" id="slider" />
<p>Some text that should dynamically change size</p>
The difference is, input
occurs, when the value is changed through the user interface.
change
on the other hand is fired, when the state of the element has changed.
Upvotes: 1
Reputation: 12891
The onchange event will fire as soon as you release the mouse button. What you want here is the oninput event which will fire as soon as you move the slider.
$('input').on('input', function() {
var v = $(this).val();
$('p').css('font-size', v + 'em')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="range" min="1.2" max="2.6" step=".2" id="slider" />
<p>Some text that should dynamically change size</p>
Upvotes: 8