Provide alternative styling through css in instances where the Google Books API does not provide an image

How can I modify the CSS code to display the author and title of a book when there is no image available from the Google Books API?

Currently, users see a custom image linked here, but it's not clear what it represents without the name and author information.

const extractThumbnail = ({ imageLinks }) => {
const DEFAULT_THUMBNAIL = "https://www.bindly.pl/static/images/logo.svg";
if (!imageLinks || !imageLinks.thumbnail) {
    return DEFAULT_THUMBNAIL;
}
return imageLinks.thumbnail.replace("http://", "https://");};

Instead of return DEFAULT_THUMBNAIL;, I want to remove the image and apply the following CSS:

document.querySelector("div.book-info ").style.display = "inline-flex;";
document.querySelector("h3.book-title").style.fontsize = "32px";

However, these changes don't seem to be working...

Any suggestions? Here's the entire code snippet:

let bookContainer = document.querySelector(".search");
let searchBooks = document.getElementById("search-box");
const getBooks = async(book) => {
    const response = await fetch(
        `https://www.googleapis.com/books/v1/volumes?q=${book}&langRestrict=pl&printType=books`
    );
    const data = await response.json();
    return data;
};

const extractThumbnail = ({ imageLinks }) => {
    const DEFAULT_THUMBNAIL = "https://www.bindly.pl/static/images/logo.svg";
    if (!imageLinks || !imageLinks.thumbnail) {
        return DEFAULT_THUMBNAIL;
    }
    return imageLinks.thumbnail.replace("http://", "https://");
};

const drawChartBook = async(subject, startIndex = 0) => {
    let cbookContainer = document.querySelector(`.${subject}`);
    cbookContainer.innerHTML = `<div class='prompt'><div class="loader"></div></div>`;
    const cdata = await getBooks(
        `subject:${subject}&startIndex=${startIndex}&maxResults=3`
    );
    if (cdata.error) {
        cbookContainer.innerHTML = `<div class='prompt'></div>`;
    } else if (cdata.totalItems == 0) {
        cbookContainer.innerHTML = `<div class='prompt'></div>`;
    } else if (cdata.totalItems == undefined) {
        cbookContainer.innerHTML = `<div class='prompt'>ツ Ups, chyba masz problem z internetem!</div>`;
    } else if (!cdata.items || cdata.items.length == 0) {
        cbookContainer.innerHTML = `<div class='prompt'>ツ Niestety, nie ma więcej wyników!</div>`;
    } else {
        cbookContainer.innerHTML = cdata.items;
        cbookContainer.innerHTML = cdata.items
            .map(
                ({ volumeInfo }) =>
                `<div class='book' style='background: linear-gradient(` +
                getRandomColor() +
                `, rgba(0, 0, 0, 0));'><a href='https://www.bindly.pl/${volumeInfo.authors}/${volumeInfo.title}' target='_blank'><img class='thumbnail' src='` +
                extractThumbnail(volumeInfo) +
                `' alt='cover'></a><div class='book-info'><h3 class='book-title'><a href='https://www.bindly.pl/${volumeInfo.authors}/${volumeInfo.title}' target='_blank'>${volumeInfo.title}</a></h3><div class='book-authors' onclick='updateFilter(this,"author");'>${volumeInfo.authors}</div></div></div>`
            )
            .join("");
        document.querySelector(".search-box").style.background = "#f00;";

    }
};

Answer №1

The issue arises when you attempt to set the style properties using:

document.querySelector("div.book-info").style.display = "inline-flex;";
document.querySelector("h3.book-title").style.fontsize = "32px";

[By the way, there are syntax errors present here - such as the ; before the " in the first line and fontSize should be written in camel case. Nevertheless, these mistakes aren't causing your problem assuming that this code is being called within the extractThumbnail function.]

The elements you are trying to access have not been added to the DOM yet - they haven't even been included in the string that you are constructing to eventually place into the document.

One potential solution is to create strings within the extractThumbnail function which can later be appended to the HTML being constructed. For instance, you could have a string representing the entire thumbnail img element - and if there's no thumbnail, make that string null. Create additional strings for styles like 'display: inline-flex;' and font-size. Then insert them into the HTML string gradually while calling the extractThumbnail function beforehand.

If the extractThumbnail function is utilized elsewhere, consider creating a separate version specific to this scenario with a distinct name to prevent interference with other parts of the code.

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

Is it possible to securely share login details on the internet?

I'm currently brainstorming different ways to securely display FTP, database, and hosting information for website projects on my project management site. One potential solution I'm considering is encrypting the passwords and developing an applica ...

How can I modify the color scheme of radio buttons to include a variety of different hues?

Is there a way to customize the colors of my radio buttons with three different options? I want numbers 1, 2, and 3 to be red, number 4 to be orange, and number 5 to be green... Here is the code I am using: /* Option 1 */ input[type='radio'] { ...

Transform an array into an object with assigned key names

How can we transform the following array: [2019,2020,2021] into the format: { 0: {year:2019}, 1: {year:2020}, 2: {year:2021} } ...

JavaScript: Adding up whole numbers--- Reference Error: Undefined

I'm having trouble with my code because it's saying that "t1" is not defined, even though it's the name of my text box. I tried making the variable global by declaring it outside the function, but it didn't solve the issue. Interestingl ...

Having trouble with the functionality of a simple jQuery toggle menu on mobile?

I am experiencing an issue with a simple toggle menu that utilizes jQuery's on: tap feature, but it is not functioning as expected: <nav id="mobile-nav"> <ul> <li>Item 1</li> <li>Item 2</li> ...

Tips on using constructor functions and the new keyword in Typescript

This is a demonstration taken from the MDN documentation showcasing the usage of the new keyword function Car(make, model, year) { this.make = make; this.model = model; this.year = year; } const car1 = new Car('Eagle', 'Talon TSi&apos ...

What is the best way to enhance an object using a class in ES6?

In an effort to improve the clarity of my ES6 class definition, my current code looks like this: class SomeClass { constructor({a, b, c, d, e}) { this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; // additional code here ...

Encountering a "Parsing error: Unexpected token, expected ";" " when developing a React application with the provided code

I am currently working on developing a React application, and I have encountered an issue in my app.js file regarding the render function. Despite being new to JavaScript, I am unable to figure out why this error is occurring. Apologies if it is due to a s ...

Executing Python code through a website using PHP - is there a way to deactivate the button once it has been clicked?

Can you assist with the following issue? <?php if(isset($_POST['MEASURE'])) { shell_exec("sudo python /var/www/html/lab/mkdir.py"); } ?> Here is the HTML part: <form method="post" > <input type="submi ...

Using Reactjs to automatically populate text into a React-Select Input field

I have implemented react-select in my project. Sometimes, I encounter the need to update my react-select input field without directly interacting with it (such as injecting text into it). However, I am unable to find a proper way to achieve this based on ...

Having trouble obtaining data from the database and showing it on the webpage

I am encountering an issue with displaying content from a database named resources and a table within it also named resources. The code snippet causing trouble is as follows: mysql_connect('localhost', 'username', 'password', ...

Closing the React Material UI drawer with nested list items upon clickingORClicking on nested list

Currently, I am encountering an issue with my React project that utilizes Material-UI. The problem arises when I incorporate nested list items within the drawer component. Previously, everything was functioning smoothly until the addition of these nested i ...

Ajax - Retrieving data from a different webpage

My index.php contains the following HTML: <div id="showDetails"> </div> <div id="showList"> </div> And this Ajax function is also in index.php: function ...

How can I generate a dummy JSON response using Backbone Fetch?

Exploring Backbone and looking for a way to simulate the response of a .fetch() call within a model without using a testing library or connecting to an external service. If the setting in the model is this.options.mock === true, I'd like to use an in ...

Customizing the CSS of the TinyMCE editor within a React application

Incorporating TinyMCE 5 into my React project has been an interesting challenge. I'm looking to personalize the editor by adjusting elements like borders and adding box shadows to the toolbar. Despite attempting to add CSS through the content_css prop ...

The Angular2 view is failing to display updated data from a shared service

I've been struggling to show data from my shared service, but it's not displaying. Can someone please help me out? I've been stuck on this for the past few days. I've tried NgZone and ChangeDetectorRef, but they haven't worked for ...

Can a string variable be passed as a file in a command line argument?

Running a command line child process to convert a local file to another format is something I need help with. Here's how it works: >myFileConversion localfile.txt convertedfile.bin This command will convert localfile.txt to the required format an ...

Setting up multiple versions of npm application

Can I have multiple versions of npm installed for different projects on Windows 10, or are npm installations always global? I attempted to install different versions using https://github.com/marcelklehr/nodist, but it only affected the node version and no ...

Establishing connections between HTML and CSS files

After writing my html and css code, I noticed that the files are not linking properly. Despite checking for errors, I couldn't find any issues within the codes. Here is a snippet of my html file: <!DOCTYPE html> <html lang="en" dir= ...

Please input a number that falls within a specified range

I need help with two text inputs that are connected v-model to a ref object. I also have two other refs, minimum (100) and maximum(1000). My goal is to allow users to input values within the range of the minimum and maximum values provided. If the value en ...