Grow your CSS skills. Land your dream job.

Font change with javascript?

  • # March 4, 2013 at 5:27 pm

    Before I start spinning my wheels, I wanted to know if it was possible to change the font of already rendered text via javascript or jquery. I am very new to js and just wanted to make sure it was possible. For example, If I have a heading in styled in font called supercool.ttf, is it possible to change it to alsocool.ttf every five seconds or so?

    # March 4, 2013 at 5:32 pm

    Instead of changing the actual font source, you would just be changing the class of the element. Below is a super basic example of what I mean. Probably not the best way to do it, just showing you that it’s possible.

    CSS:

    .some-font { font-family: ‘something'; }
    .another-font { font-family: ‘something'; }

    HTML:

    Header

    jQuery:

    $(‘h1′).removeClass(‘some-font’).addClass(‘another-font’);

    # March 4, 2013 at 5:34 pm

    Yeah just like @TheDoc said, I would use classes and change them with JavaScript every 5 seconds using the `setInterval()` method.

    Here’s the API for the `setInterval()` method: https://developer.mozilla.org/en-US/docs/DOM/window.setInterval.

    # March 4, 2013 at 6:58 pm

    @matt_sanford,

    Like all these guys mentioned there’s a few ways. The example below is using setInterval along with toggleClass()

    http://codepen.io/johnmotyljr/pen/bFiCL

    # March 4, 2013 at 10:08 pm

    So if I were multiple classes would I need multiple functions? Or could I rope it all into one function with “for” and “while” statements?

    # March 4, 2013 at 11:24 pm

    @matt_sanford ,

    How many classes are you wanting to switch between?

    # March 5, 2013 at 12:00 am

    Doesn’t really matter the quantity now, I am trying to learn without getting it handed to me which I know isn’t all that possible in this situation seeing its specificity. I just want to know if it is possible/maybe a step in the right direction.

    # March 5, 2013 at 12:09 am

    @matt_sanford ,

    Well (this === LULZ) because i just came up with a really weird solution. I’ll post my codepen here in a minute when im done coding all these classes.

    # March 5, 2013 at 12:20 am

    And you still can use

    $(element).css(‘font-family’, ‘Tahoma’);

    There’s a lots of ways how can you change fonts/classes, ‘switch’, ‘loop’, etc.

    # March 5, 2013 at 12:30 am

    @matt_sanford :

    Here is the solution i came up with. I will comment what i did so you could easily understand.

    http://codepen.io/johnmotyljr/pen/EnCge

    # March 5, 2013 at 11:25 pm

    @matt_sanford :

    Hey, @CrocoDillon came up with a nice solution as well. You can check out his CodePen.

Viewing 11 posts - 1 through 11 (of 11 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".