Ways to add stylistic elements to variables using JavaScript

I'm currently working on an API and I've managed to get it up and running, but now I'd like to add some style to it.

I've been attempting to change the style for variables such as title, country, status, and summary but haven't had much success. Could you provide a hint on how to accomplish this? I've tried several approaches without any luck.

Thank you!

// Creating an empty object to hold the functionality of our app
var app = {};


// Create an init method that will contain all the code necessary for app initialization
app.init = function(){
    $('#subject').on('keyup', function(){
  var subject = $(this).val().toLowerCase();
  // Empty before we ask for results that were there so new results will show up
  $('#showresults').empty();
  app.getShow(subject);
});
};

// The getShow method will make an Ajax request to the API
app.getShow = function(query){
    $.ajax({
        url: 'http://api.tvmaze.com/search/shows?q=:query',
        method: 'GET',
        dataType: 'json',
        data: {
            ps: 20,
            q: query,
            format: 'json'
        },
        success: function(results){
            console.log(results);
            app.displayShow(results);
        },
        error: function(error){
            console.log(error);
        }
    });
};



// The displayShow method will inject our art pieces into the DOM
app.displayShow = function(ShowArray){
    // forEach is equivalent to a for loop in jQuery. It is used to loop over our array of shows
    ShowArray.forEach(function(showObject){
      // Set variables to hold the title, country, status, and summary of each show
        var title = showObject.show.name  ;
        var country = showObject.show.network.country.name;
        var status= showObject.show.status;
        var summary =  showObject.show.summary;
        // Add all elements into this div

        var showHtml = $('<div>').addClass('series').append(title + '<br>' + country + '<br>' + status + summary);
        $('#showresults').append(showHtml);
    });
};


$(function(){ // Short form of document.ready, which waits for all HTML documents to be loaded before running JS
    app.init();
});
<!-- CSS snippet code goes here -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>TV Show App</title>
  <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <header>
    <div class="container">
      <h1 id="page-title">TV Show App</h1>;

      <form>
        <label for="subject">Choose your show</label>
        <input name="subject" id="subject"></input>
        
      </form>

    </div>
  </header>

  <main>
    <div class="container" id="showresults"></div>
  </main>

  <script src="http://code.jquery.com/jquery-3.1.1.min.js"
          integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
          crossorigin="anonymous">
  </script>
  <script src="app.js"></script>
</body>
</html>

Answer №1

How about giving this a shot?

let newHtml = $('<div>').addClass('series')
.append('<span class="title-style">' +showTitle  +'</span>' 
+ '<br> <span class="country-style">' + showCountry +'</span>' 
+ '<br> <span class="status-style">' + showStatus + showSummary+'</span>');

Answer №2

To enhance the appearance of the variables, enclose the output in HTML elements, assign them a class or identifier, and then apply CSS styling.

In this example, I am enclosing the output text within span tags, but feel free to adjust based on your needs.

var showHtml = $('<div>').addClass('series').append('<span class="title">' + title + '</span>' + '<br>' + '<span class="country">' + country + '</span>' + '<br>' + '<span class="status">' + status  + '</span>' + '<span class="summary">' + summary  + '</span>');

Below is an example of CSS to style these elements:

.title {
  color: red;
}
.country {
  color: white;
}
.status {
  color: blue;
}
.summary {
  color: lemonchiffon;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

performing an action using vuex in a component's method

I am facing an issue where I am trying to dispatch an action and retrieve the values passed into an input field. When I directly dispatch an action on a button, everything works perfectly fine: <button type="button" @click="store.dispatc ...

Is there a way to utilize either css3 or css in order to change the icon displayed on a button

Currently, I am working on a button that contains a span element. I am interested in finding a way to change the background of the span when the button is clicked and have it remain changed. Is there a way to achieve this using CSS only? I am aware that ...

Download multiple Highcharts graphs on a single page

When using Highchart Export, I am currently able to download multiple graphs in a single page PDF. However, I would like the first graph to be on the first page and the second graph on the second page when saving as a PDF. You can find the code in the fol ...

Looking for guidance on implementing a Live Search feature using jQuery, AJAX, JSP/Servlet, MySQL, and JSON?

After conducting research, I have received varied responses regarding this topic. The table contains 2,000 records and is updated monthly with only a small number of new entries (5-10). The structure of the table is simple: id, name, data1, data2, data3 ...

What is the best way to showcase a specific column from a dataset using Vue.js and axios?

Hey there, I'm still getting the hang of all this and haven't quite mastered the jargon yet. Here's what I need help with: I managed to retrieve data from my SQL database using axios, and when I check in (f12) - network - preview, it shows: ...

Only the initial row can be removed via Ajax

I am facing an issue with my page that displays rows from a MySQL table. I am working on implementing an AJAX form to allow users to delete rows, but I am only able to delete the top row that is displayed. For some reason, clicking on any other row does no ...

What is the best way to add spacing between the fields within a Bootstrap 4 form row that spans across 2 rows when viewed on small displays?

Trying to create a bootstrap 4 form with fields in one row for larger screens and two rows for smaller screens. The attempt was made using the following code: <div class="form-group row"> <label class="col-sm-2 col-form-label">File:</lab ...

Creating realistic water reflections in WebGL with ThreeJS

I am currently experimenting with creating a realistic water surface in WebGL using Three.js. My initial approach involves starting with a simple mirror effect and then adding displacement to achieve basic ripple effects. Here's what I have learned s ...

Encountering an incorrect number of parameters for "undefined" during the deployment of a smart contract

I am facing an issue while attempting to deploy my first Voting contract on the testRPC. The error seems to arise from the arguments parameter in the code snippet below. When I tried passing an empty array, it gave an error stating "Got 0 expected 1!". Si ...

I am interested in invoking a function from a different component

I am facing an issue with my component AddPost.js where I am trying to use a method from machine.js. However, when I attempt to import AddPost into the machine.js file, it throws an error: Possible Unhandled Promise Rejection (id: 0): ReferenceError: addIn ...

Customizing TinyMCE's font style menu options

Our platform utilizes TinyMCE as in-place editors to allow users to make live edits to content. However, a challenge arises when using a dark background with light text, as TinyMCE defaults to using this text color rather than black. https://i.sstatic.net ...

The bottom border of the HTML header does not properly wrap around the Table of Contents (ToC), although the text within the header does. What steps

I have created a Table of Content (ToC) using a Div element and styled it with the following HTML and CSS: h3.articletitle { font-weight: bold; font-size: 30px; border-bottom: 1px solid #4F120B; } h4.articlesubtitle { font-weight: bold; ...

Login attempted with correct credentials resulted in an error

For the past 4 days, I've been struggling with a simple ajax login page that just doesn't seem to work. Even with valid email ID and name, it keeps showing 'invalid credentials'. I'm not sure what I'm doing wrong. Below is th ...

Error: Unable to access 'createInvite' property from undefined variable

Having trouble generating an invite to one of my guild's channels. Here is the code snippet I am using: const { Client } = require("discord.js"); const client = new Client({ intents: [] }); client.on("ready", async () => { ...

I am struggling to capture the user's input and display it on a webpage using HTML and JavaScript. Can you help me identify where I may be going wrong in this process?

Good day! I am fairly new to the programming world and have recently embarked on my first JavaScript project. I've chosen to create a simple budgeting app. However, I'm struggling with displaying user input on the page. Something seems off with ...

Are there any CSS3 selectors currently available or planned for matching partial attribute names?

By using [foo^="bar"], you can target nodes with the attribute foo that starts with the value bar. Is there a method to select nodes based on an attribute name that begins with a specific string? This would be useful for selecting all nodes with a data-* ...

Only if there is an update in the SQL database, I wish to refresh the div

I have created a voting system and I am facing an issue with the data updating. I have implemented a setInterval function in javascript to load the data every 2 seconds, but it's not working as expected. There are no errors shown, but the data is not ...

Encountering a glitch while iterating through function results in failure after the initial modification

I am facing some errors with the script provided below: var sections = ["#general_info", "#address_records", "#employment_history", "#driver_experience", "#military_experience", "#eeo_survey", &qu ...

Activate the next tab by clicking a button in ReactJS

I currently have a web page with 4 tabs, each containing different sets of data. Within the first tab, I have a button that should activate the next tab's content when clicked by the user. render(){ return ( <MuiThemeProvider> ...

Is there a way to implement a timeout for redirection or new pages opened on a different server?

Is there a way to redirect my page to another website, like google.com, or to open google.com as an additional page in the browser? In addition, is there a way to close any previously opened google pages (if opened as a new page) or return to my page (if ...