Reputation: 199
I am having trouble changing the font-family of my text with jQuery.
My html:
<select id="message-font-selection" class="promo">
<option value="Oswald">Oswald</option>
<option value="Open Sans">Open Sans</option>
<option value="Montserrat">Montserrat</option>
<option value="Indie Flower">Indie Flower</option>
<option value="Poiret One">Poiret One</option>
</select>
<div class="middle-section">{{middle_msg}}</div>
My js:
$('#message-font-selection').change(function() {
$('.middle-section').css('font-family',$(this).val());
});
The problem is that I can only change the font once. However, when I try selecting a different font-family for the 2nd, 3rd, 4th, etc... time, the font no longer visibly changes. However, when I inspect the element, I can see that the font-family style for that text is indeed being changed... but those changes are not reflected on the screen... I have basically the same exact code for font-color and that seems to work just fine.
Upvotes: 0
Views: 870
Reputation: 1288
I have tested your code with little modification(Change on font name) and it's working fine.
<select id="message-font-selection" class="promo">
<option value="Oswald">Oswald</option>
<option value="fantasy">fantasy</option>
<option value="monospace">monospace</option>
<option value="cursive">cursive</option>
<option value="Poiret One">Poiret One</option>
</select>
<div class="middle-section">Test</div>
JS
$('#message-font-selection').change(function() {
$('.middle-section').css('font-family',$(this).val());
});
Upvotes: 0
Reputation: 680
Your issue is with the use of "this":
$(document).on('change', $('#message-font-selection'), function() {
alert('The value of $(this).val() is: ' + $(this).val() );
$('.middle-section').css('font-family',$('#message-font-selection').val());
});
As you can see, replacing "$(this).val()" with a reference to the actual element fixes the issue.
Also, by using $(document).on listener, you can listen for a change in the element even if it doesn't exist when the listener is registered.
Fiddle: https://jsfiddle.net/nebulousal/jvk0t2x8/
Upvotes: 1
Reputation: 1380
Please have a look at code,
it is working when i tried with the basic fonts which are available globally,
<select id="message-font-selection" class="promo">
<option value="arial">arial</option>
<option value="times new roman">times new roman</option>
<option value="calibri">calibri</option>
</select><br><br><br><br>
<div class="middle-section">This is test</div>
$('#message-font-selection').change(function() {
$('.middle-section').css('font-family',$(this).val());
});
Thanks
Upvotes: 0