Brendan
Brendan

Reputation: 35

Using jQuery to Change Font Family

I'm trying to figure out why this isn't working:

$(document).ready(function() {
   if (fontPreference === "MavenPro") {
       $("*").css('font-family', '"Maven Pro" !important');
   }
});

I have the necessary stylesheet that holds the font... am I missing something?

Upvotes: 2

Views: 4484

Answers (2)

Mohammed Fahsi
Mohammed Fahsi

Reputation: 41

The thing is that jQuery doesn't understand the !important attribute when using .css() but instead you can use .attr(). Like this:

$(document).ready(function() {
    $( "#selectionTest" ).change(function() {
        var fontPreference = $( "#selectionTest" ).val();
        $("body").attr('style', 'font-family:"'+fontPreference+'" !important');
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="testing">
    <p>This is the tekst that we will be testing on</p>
    <p style="color: red;">This p has inline styling</p>
    <select id="selectionTest">
        <option value="arial">arial</option>
        <option value="verdana">verdana</option>
        <option value="Comic Sans MS">comic sans</option>
        <option value="Mavenpro">Mavenpro</option>
    </select>
</div>

Upvotes: 4

Majid Fouladpour
Majid Fouladpour

Reputation: 30242

$(document).ready(function() {

  $("#setfont").click(function() {
    $("body").append("<style>* { font-family:  monospace!important;}</style>");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="javascript:void(0);" id="setfont">Set font</a>

<p>Some text</p>

Upvotes: 0

Related Questions