Home > Back-end >  Need Advice in Javascript - New font family for every div
Need Advice in Javascript - New font family for every div

Time:12-26

I'm making a post site, but I'm trying to make each post have it's own individual font family.

You can see here with the cursive font, it is assigning it properly, but to all of a class. I need to break each post into it's own individual iteration.

Since I am doing it on load, i can't seem to grab their Id's or Attributes easily and put them into an array.

my current solution is something like this, full code below The randfontlist doesn't return a normal object, it returns something I've never seen before, like the entire post or something. Does anyone have a smart solution to iterate through the

items with .randfont tag? Thank you

randfontlist = $('.randfont').toArray()
randfont_idlist = $('.randfont').attr("id").toArray()
$(`.randfont`)[i].addClass(random)

enter image description here

.html

{% for poopfact in poopfacts %}
 <div >
        <div >
          <p>{{ poopfact.date }} </p>
          <p  id="{{poopfact.id}}">{{ poopfact.fact }}</p>
          <p> {{ poopfact.author }}</p>
        </div>

.script

$( document ).ready( function() {
          
          $('.randfont').load(randomizeFonts()) 
          
          function randomizeFonts() {
            let fonts = ['caveat', 'indieflower', 'nanum', 'pacifico', 'pmarker', 'tangerine'];
            const randfonts = $('.randfont')
            for (let i = 0; i < randfonts.length; i  ) {
              var random = fonts[Math.floor(Math.random() * fonts.length)];
              //get the ids of those items and put it into another array
              $(`.randfont`).addClass(random)
              }
          }

CodePudding user response:

Assuming every font name in the fonts array has its equivalent CSS class to set the font-family...

$( document ).ready( function() {
  const fonts = ['caveat', 'indieflower', 'nanum', 'pacifico', 'pmarker', 'tangerine'];
  
  $('.randfont').each(function(index, element){
    $(element).addClass(fonts[Math.floor(Math.random() * fonts.length)])
  }) 
}
  • Related