简体   繁体   中英

How to change font inside a javascript code

I am a newbie in programming. I have here my javascript code. Its working fine but I want a different style.

this code is a random quote generator.

<html>
<head>
<title>
Daily Quotes
</title>
</head>
<h1>Inspirational Quotes</h1>
<body>
        <script language="JavaScript">
    var quoteGroups=70;
    var quoteNum;
    var theQuote=new Array();
    theQuote[0]='Whenever you see a successful business, someone once made a courageous decision. - Peter Drucker';
    theQuote[1]='If you\'re not part of the solution, you\'re part of the problem. - African Proverb';
    theQuote[2]='When you confront a problem you begin to solve it. - Rudy Giuliani';
    theQuote[3]='I dream of painting and then I paint my dream. - Vincent Van Gogh';
    theQuote[4]='Be silent or let thy words be worth more than silence. - Pythagoras';
    theQuote[5]='The past cannot be changed. The future is yet in your power. - Mary Pickford';
    theQuote[6]='Anything\'s possible if you\'ve got enough nerve. - J.K. Rowling';

var quoteNum = Math.round(Math.random() * quoteGroups);
document.write(theQuote[quoteNum]);
</script>
<div>
<button style="background-color:lightgreen;width:230;height:70;border: none; font: bold 25px GreatVibes;" onclick="history.go(0)">Inspire Me More!</button>
    </div>
<div>

<button style="background-color:blue;width:200;height:70" onclick=>Share</button>

</div>
</body>
<img src="images/bg.jpg" id="bg" alt="">
</html>

For example, the above code will generate random quotes. Now how do i change the font family as a result of clicking the button from this code?

Thanks in advance.

Looking at this:

<button style="background-color:blue;width:200;height:70" onclick=>Share</button>

You have no function set to onclick. Do something like:

<button style="background-color:blue;width:200;height:70" onclick="changeFont(this, 'font name');">Share</button>

changeFont:

function changeFont(element, name) {
    element.style.fontFamily = name;
}

Some things to improve:

  • Don't use document.write , but instead reserve an element in your HTML that you will populate with the quote, assigning to textContent ;
  • Don't use round in your random generating expression, but floor , otherwise you risk to produce a value that is out of range
  • Don't use a separate variable for the number of quotes you have (which currently does not match the actual number), but use theQuote.length
  • Don't define long style values in your HTML, but use CSS classes instead
  • Don't reload the page at every click, but change the quote within the current page without navigating.

To dynamically set the font, you could reserve a few CSS classes to choose from, even randomly.

Here is how it could work:

 function displayQuote() { var theQuote= [ "Whenever you see a successful business, someone once made a courageous decision. - Peter Drucker", "If you're not part of the solution, you're part of the problem. - African Proverb", "When you confront a problem you begin to solve it. - Rudy Giuliani", "I dream of painting and then I paint my dream. - Vincent Van Gogh", "Be silent or let thy words be worth more than silence. - Pythagoras", "The past cannot be changed. The future is yet in your power. - Mary Pickford", "Anything's possible if you've got enough nerve. - JK Rowling" ]; var quoteNum = Math.floor(Math.random() * theQuote.length); var clsName = "special" + Math.floor(Math.random() * 3); // choose random font style quote.textContent = theQuote[quoteNum]; quote.className = clsName; } next.onclick = displayQuote; // execute on click displayQuote(); // execute on page load
 .shareButton { background-color:blue; width:200; height:70 } .inspireButton { background-color:lightgreen; width:230; height:70; border: none; font: bold 25px GreatVibes; } .special0 { font-family: Georgia; font-size: 24px; color: #444; } .special1 { font-family: Calibri; font-size: 32px; color: #844; } .special2 { font-family: Tahoma; font-size: 28px; color: #484; }
 <div id="quote"> </div> <div> <button id="next" class="inspireButton">Inspire Me More!</button> </div>

As you are new, it's best not to pick up bad habits which, unfortunately is easy to do because so much of the code out there is just copied and pasted by folks who don't know any better, so:

Try not to write inline styles or inline event handlers like this:

<button style="background-color:lightgreen;width:230;height:70;border: none; font: bold 25px GreatVibes;" onclick="history.go(0)">Inspire Me More!</button>

As you can see, it makes the code difficult to read as there are 3 languages in that one element!

Instead, separate your languages into their own sections, or even files.

With regard to CSS styles, it would be better to define CSS classes ahead of time and then just switch to the class you need, rather than write all that inline CSS.

You also have some errors in your code.

So, here's an updated version of your code that also changes the font. Make sure to review the comments for details.

 <html> <head> <title>Daily Quotes</title> <style> /* We'll separate the CSS into this section and prepare pre-made classes for styles. See how much cleaner this is, not only here but in the HTML as well? */ button { background-color:lightgreen; width:230;height:70; border: none; font: bold 25px GreatVibes; } .share { background-color:blue; width:200px; /* Don't forget to add the unit */ height:70px; /* Don't forget to add the unit */ } #output { /* Now, just the output area has its own style! */ font-family: fantasy; } </style> </head> <body> <!-- All your content must be between the opening and closing body tags. --> <h1>Inspirational Quotes</h1> <div> <button>Inspire Me More!</button> </div> <div> <button class="share">Share</button> <img src="images/bg.jpg" id="bg" alt=""> </div> <!-- Don't use document.write() to inject content into a page. Instead, prepare an element ahead of time that you will update later. --> <div id="output"></div> <!-- Place your script tags just before the closing of the body tag. That way, you can be sure that any HTML element you reference in the script has already been read into memory. --> <script> // First, get references to the HTML elements you'll want to work with: var btn = document.querySelector("button"); var out = document.getElementById("output"); // Then, set up your event handlers in JavaScript, not in HTML btn.addEventListener("click", getQuote); function getQuote(){ // Here's a simpler way to set up an array: var theQuotes= [ 'Whenever you see a successful business, someone once made a courageous decision. - Peter Drucker', 'If you\\'re not part of the solution, you\\'re part of the problem. - African Proverb', 'When you confront a problem you begin to solve it. - Rudy Giuliani', 'Dream of painting and then I paint my dream. - Vincent Van Gogh', 'Be silent or let thy words be worth more than silence. - Pythagoras', 'The past cannot be changed. The future is yet in your power. - Mary Pickford', 'Anything\\'s possible if you\\'ve got enough nerve. - JK Rowling' ]; // You only want your radom number to be from 0 to the amount of the quotes array -1 var quoteNum = Math.floor(Math.random() * theQuotes.length); // Now, just update the prexisting element: output.textContent = theQuotes[quoteNum]; } </script> </body> </html>

in short, here is working example:

 <body onload="generateRandomQuote()"> <h1>Inspirational Quotes</h1> <div id="quote-holder" style="font-family: sans-serif; color: red;"> </div> <div> <button style="background-color: lightgreen; width:230px; height:70px; border: none; font: bold 25px GreatVibes;" onclick="generateRandomQuote()">Inspire Me More!</button> </div> <button style="background-color: blue; width: 200px; height: 70px" onclick="">Share</button> <img src="images/bg.jpg" id="bg" alt=""> <script> var quoteHolder = document.getElementById('quote-holder'); var theQuote = [ 'Whenever you see a successful business, someone once made a courageous decision. - Peter Drucker', 'If you\\'re not part of the solution, you\\'re part of the problem. - African Proverb', 'When you confront a problem you begin to solve it. - Rudy Giuliani', 'I dream of painting and then I paint my dream. - Vincent Van Gogh', 'Be silent or let thy words be worth more than silence. - Pythagoras', 'The past cannot be changed. The future is yet in your power. - Mary Pickford', 'Anything\\'s possible if you\\'ve got enough nerve. - JK Rowling' ]; function generateRandomQuote() { var quoteIndex = Math.floor((Math.random() * theQuote.length)); quoteHolder.innerHTML = theQuote[ quoteIndex ]; } </script> </body>

  • in css you should define units, you had just numbers,
  • there shouldn't bee any h1 or images or any elements outside your body tag,
  • it's better to just append your desired content to some div, rather than refreshing the whole page,
  • ...

I see that you already have answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM