Home > OS >  Generate text based on randomized CSS file
Generate text based on randomized CSS file

Time:02-01

My webpage has a random CSS function that's working fine:

<link rel="stylesheet" href="/css/<?php echo(mt_rand(1,7));?>.css" />

But I would like to have text display based on which CSS file is selected. Each one has a name associated with it, so for the "Copenhagen" CSS sheet I want it to display the text, "This stylesheet is called Copenhagen."

Right now I'm trying to output text based on the background-color of .skills-title, which for now is either black, white, or everything else ("Fail"). However it's not outputting anything at all. I think it's because the stylesheet is randomized so I can't call a specific stylesheet into the code.

var color = $('.skills-title').css('background-color');

if (color == 'rgb(255, 255, 255)') {
  document.write("Copenhagen");
} else if (color == 'rgb(0, 0, 0)') {
  document.write("Paris");
} else {
  document.write("Fail");
}

After playing around with a lot of different code for a few hours, I feel stuck.

CodePudding user response:

If you want to display text based on the name of the CSS file, you can try the following code. You can add a class to the HTML element with the CSS file name and then select the element with JavaScript and retrieve its class name to display the text.

var stylesheet = $('head link').attr('class');

if (stylesheet == 'copenhagen') {
  document.write("This stylesheet is called Copenhagen.");
} else if (stylesheet == 'paris') {
  document.write("This stylesheet is called Paris.");
} else {
  document.write("This stylesheet is not recognized.");
}
<html>
  <head>
    <link rel="stylesheet" href="copenhagen.css" >
  </head>
  <body>
    <div >Skills</div>
  </body>
</html>

CodePudding user response:

You could try to set an id or title to your Link tag, so you could get it in vanilla js as follow:

// supposing you created it like: <link id="mylink" title="mylinktitle" rel="stylesheet" href="/css/<?php echo(mt_rand(1,7));?>.css" />

let element = document.querySelector("link[title=mylinktitle]")

// or 

let element = document.getElementById("mylink");

With element object you could check anything and display the name you want.

Alternatively you could try to send the name in title and use an static id, so you get the element based on some id and display the title associated

  • Related