CSS Change Color // Random Quote Project


I have a short Noob-like question. I wanted to change the color of the random quote when clicking on the respective button. However, the color seems to change at first but then changes back to the initial blue immediately afterwards. My question is: what is $(".quotation").css(“color”, num); doing here? Why does it switch back to blue? Thank you in advance for your help!

$(document).ready(function() {
  $("#getQuote").on("click", function(){
    var num = "#" + Math.random().toString(16).slice(2,8);
    $(".quotation").css("color", num);
	    type: 'GET',
	    url: 'https://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=jsonp&jsonp=?',
	    dataType: "JSONP", // data type expected from server
	    success: function(data) {
		    var html ="";
        var keys = Object.keys(data);
        html += '<div class="quote">';
            if(key == "quoteText"){
              html += '<div class="quotation">' + data[key] + '</div>';  
            } else if(key == "quoteAuthor"){
              html += '<div class="author">' + data[key] + '</div>';
          html += "</div>";
	    error: function() {
		      $("#output").html("Something went <strong> wrong </strong>. Terribly <strong>wrong</strong>.");
    }); //Ajax
  }); //Click-event
}); //Document-loading

I think it’s because you are changing the colour of the text before your API call—so the colour of the current quote changes when you press on the button, but once the data comes back and when your code has created new HTML to be parsed to #output, a new <div class="quotation"> is created, which inherts the default font colour (it looks like you’ve set it to blue).

If I’m not mistaken, all oyu need to do is to move the code for colour change to after $("#output").html(html);.

I hope that helps! (For future reference, it would usually be very helpful if you could just provide a link to your project or include all of the code.)

1 Like

Hi Honmanyau!

//EDIT: Works! Thanks!

Thank you again for your help!

CodePenProject Link

//EDIT: BTW, the background color doesn’t work either. Any idea? Merci!

You are welcome. :slight_smile:

I think it’s because of the CSS import at the beginning of your HTML—it appears that importing a stylesheet this way override your own CSS (in the CSS panel):

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">

Removing that and importing it under Settings > CSS > Add External Stylesheets/Pens seems to do the trick.

1 Like