What is the best way to align text extracted from an API using JavaScript?

I'm currently exploring content generation through APIs, but I'm facing an issue where the text generated is not aligning properly within the container on the screen.

The main problem lies in getting the card to be centered on the screen with all of its text centered as well. However, the text generated by the API appears only on the left side of the card.

const jokeText = document.querySelector(".joke");

async function fetchJoke() {
  const response = await fetch("https://icanhazdadjoke.com", {
    headers: {
      Accept: 'application/json',
    },
  });

  const joke = response.json();
  return joke;
}

async function clickButton() {
  const {
    joke
  } = await fetchJoke();
  jokeText.innerText = joke;
}
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2d4f4242595e595f5c47120b151b">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<body class="container bg">
  <div class="card row border-primary text-center" style="width: 40rem;">
    <img src="../img/meme.jpg" class="card-img-top mx" alt="...">
    <div class="card-body">
      <h5 class="card-title">Best dad jokes!</h5>
      <div class="col-6 joke text-center"></div>
      <button class="col-6 btn btn-primary" onclick="clickButton()">Click for a new joke</button>
    </div>
  </div>

  <script src="api.js"></script>
</body>

Thank you in advance!

Aligning the generated API text in center

Answer №1

The content appears centered, but the presence of col-6 in the div element causes it to occupy 50% of the width, giving the impression that it is left-aligned. To correct this issue, you can either remove the col-6 class or adjust it using a breakpoint: More.

const jokeText = document.querySelector(".joke");

async function fetchJoke() {
  const response = await fetch("https://icanhazdadjoke.com", {
    headers: {
      Accept: 'application/json',
    },
  });

  const joke = response.json();
  return joke;
}

async function clickButton() {
  const {
    joke
  } = await fetchJoke();
  jokeText.innerText = joke;
}
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="83e1ececf7f0f7f1e2f3c3b6adb3adb1">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

<body class="container bg">
  <div class="card row border-primary text-center" style="width: 40rem;">
    <img src="../img/meme.jpg" class="card-img-top mx" alt="...">
    <div class="card-body">
      <h5 class="card-title">Best dad jokes!</h5>
      <div class="joke text-center"></div>
      <button class="col-6 btn btn-primary" onclick="clickButton()">Click for a new joke</button>
    </div>
  </div>

  <script src="api.js"></script>
</body>

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

AmplifyJS is throwing an error: TypeError - It seems like the property 'state' is undefined and cannot be read

I am currently working on integrating the steps outlined in the Amplify walkthrough with an Angular cli application. My app is a brand new Angular cli project following the mentioned guide. My objective is to utilize the standalone auth components a ...

Issue with THREE.SpriteCanvasMaterial functionality

This unique piece of code (inspired by this and this example): generateCircle = (ctx) -> position = 0.5 radius = 0.5 ctx.scale(0.05, -0.05) ctx.beginPath() ctx.arc(position, position, radius, 0, 2*Math.PI, fa ...

How can I adjust the font size of material-ui buttons while ensuring that they scale appropriately?

Having trouble adjusting the font sizes on Material-UI's RaisedButton for React and ensuring that the button scales properly along with it. <RaisedButton label={<span className="buttonText">Log in Here</span>} /> CSS: .buttonText ...

Ensure that selected options are unique across multiple selections

Could you help me with a question that involves matching pairs of words in both Russian and English? <div class="form-group" id="question4"> <label for="q4FirstSelectEN">4</label> <div class="row"> <div class="col-lg ...

Utilizing Internationalization in Socket.io

I currently utilize the i18n-2 package for Internationalization in my project by implementing it as follows: router.get('/route', function (req, res, next) { res.redirect('/route/?lang=' + req.i18n.getLocale()); }); Now, ...

Storing a Promise in a Variable in React

As a newcomer to JavaScript/React, I am finding it challenging to grasp the concept of using Promise and async. To illustrate, consider the API call getSimById in a JS file that returns a Promise: export function getSimById(simId) { return fetch(simsUrl ...

Navigating through cors in next.js

Currently, I have set up my front end using Netlify and my backend using Heroku with Next.js For the fetch request on the front end, here is an example: fetch(`https://backendname.herokuapp.com/data`, { method: 'POST', headers: { & ...

I encountered an issue with my shopping cart while using ReactJS

this is the App.js file import React from "react"; import ListProduct from "./listProduct"; import ListOrder from "./listOrder"; import pizza from "./pizza.jpg"; import './style.css' import { Container,Row,Col,Button } from 'react-boo ...

Nginx and Socket.io: Issues with client-server connection not functioning properly

Hello everyone! I am currently in the process of deploying my application, which utilizes React and NodeJs. However, I have encountered an issue with integrating Socket.io with Nginx. My approach involves editing the Nginx file using the command: sudo ...

JavaScript Popup Box Failing to Trigger

Snippet of Code: <form method="post" id="cp_ind_form"> // several input fields here... <input type="submit" name="update_submit" value="Update" /> <input type="submit" name="delete_submit" value="Delete" onclick="deleteConfi ...

Unable to replace default typography in MUI with custom typography theme on Next.js

In my Next.js React project, I am utilizing Material-UI (MUI) with a customized theme. Although the colors from the theme are being applied successfully, I am encountering difficulty in adjusting the default font sizes of H2 and H5 elements. Even though I ...

Retaining the Chosen Tab upon Page Reload in Bootstrap 5.1

Struggling to maintain the selected tab active after page refresh. It's worth noting that I'm using Bootstrap 5.1 and have tried various solutions found for different versions without success. <ul class="nav nav-pills mb-3" id=&q ...

The HTML textarea is not updating properly when using jQuery's keypress event

I am facing an issue with my forms on a webpage, each containing an html textarea: <textarea name="Comment" class="inputTextArea">Hello World!</textarea> There is a javascript event handler that automatically submits the fo ...

What is the best way to create a scrollable tbody in an HTML table using React?

In my current project, I am using React, Node, Express, and Postgres to fetch data from a database. The issue I'm facing involves creating a scrollable table within a div that spans the entire screen width. Initially, I had to apply display: block to ...

Generating a unique event triggered by element class change

Is it possible to create custom JavaScript events that are triggered when elements receive a specific class? I am trying to monitor all elements within a table and perform certain actions once a particular class is added to them. Can this be done, and if ...

Tips for waiting on image loading in canvas

My challenge involves interacting with the image loaded on a canvas. However, I am uncertain about how to handle waiting for the image to load before starting interactions with it in canvas tests. Using driver.sleep() is not a reliable solution. Here is ...

Sending an error from one asynchronous function to another

I have a complex system that utilizes async/await. My goal is to handle various types of errors from an async function within a single try/catch block. This function is called from another async function. Unfortunately, I've been unable to successfu ...

Tips for creating a personalized dialog box after logging in with React Admin based on the server's response

One of my requirements is to allow users to select a role during the login process. Once the user enters their username and password, the server will respond with the list of available roles. How can I implement a dialog where the user can choose a role fr ...

Ideal location to detect web browser and display or conceal a division

I am looking to display a div using either the ng-if or ng-show/hide directives if the user accesses the page through a specific browser, such as Chrome/Chromium. However, I am unsure of the optimal location to place this functionality. The JavaScript cod ...

Having issues with the jQuery toggle functionality

var resultsList = $("#test"); resultsList.text("Hello. This is jQuery!"); var tB = jQuery("#toggleButton"); tB.on("click", function() { resultsList.toggle(400); }); The syntax appears to be correct as there are no errors reported in the browser cons ...