I must generate numerous copies of my CSS class using JavaScript

My CSS includes a base class named "toast" that contains basic styling, along with a JavaScript function that generates different types of toasts based on user input. The function modifies the toast class by inserting icons and text as demonstrated below:

#toast {
        visibility: hidden;
        width: 200px;
        min-height: 40px;
        max-height: 100px;
        border-radius: 5px;
        //various other styling properties
        }

Here is the JavaScript code:

function showToast(type) {
    var label = null;
    var iconElement = null;
    var i = document.getElementById("toast")

    switch (type) {
        case 'success':
            i.style.border = 'solid 1px #007700';
            label = "SUCCESS";
            iconElement = "icons/success.png";
            break;
           //additional cases for other types
    }

    document.getElementById("title").innerHTML = label;
    document.getElementById("icon").src = iconElement;
    i.style.visibility = 'visible';
}

Currently, each time I call the function to create a new toast, it replaces the existing one. However, I want to be able to stack multiple toasts and display multiple feedback messages simultaneously. How can I create multiple instances of my CSS class so that they are not overwritten each time the constructor is called?

Answer №1

It seems like you've been assigning the ID "toast" to every element. This means that when you try to access the element using document.getElementById("toast"), you're just repeatedly selecting the first element with that ID.

To avoid this issue, consider giving your toast elements a class instead. Here's an example:

<div id="genericToast1" class="toast"></div>
<div id="successToast1" class="toast success"></div>
<div id="burntToast1" class="toast burnt"></div>

Then, in your CSS, you can style the toast elements based on their classes:

.toast 
{
    visibility: hidden;
    width: 200px;
    min-height: 40px;
    max-height: 100px;
    border-radius: 5px;
    /* Add more styling */
}

.toast.success
{
    /* Styling specific to success toasts */
}

.toast.burnt
{
    /* Styling specific to burnt toasts */
}

This way, you can style your elements without the need for JavaScript!

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 maintain the component's DOM state when navigating away and then returning in Angular?

After spending several days researching this issue, I find myself at a dead end. I thought I was dealing with a common scenario: A user navigates to a specific page, makes some changes (such as editing an input field, scrolling through grid data, or chang ...

Replacing the left styling using CSS

Struggling to adjust the position of a side panel that pops up when hovering over an option. This is the code I found in Chrome Developer Tools: <nav id= "side_nav" class= "sidebar-bg-color header-side-nav-scroll-show"> <ul ...

Having issues with the width not functioning correctly in my table cells

Here is a sample I'd like to share with you: link CODE HTML: <table class="table prospects-table"> <thead> <tr> <th width="200">Name</th> <th width="200">E ...

Using Express and Node.js to display a page populated with information

On my webpage, I currently have a list of Teams displayed as clickable links. When a link for a specific Team is clicked, the Key associated with that Team is extracted and sent to the /team/:key route to retrieve the respective data. If the data retrieval ...

What could be causing my CSS to not display properly on GitHub Pages?

Currently working on a web-based game project called Sweet Shoppe, and utilizing GitHub Pages for hosting. However, encountered an issue where the CSS does not seem to be functioning properly on GitHub Pages. Attempted placing the CSS file in the main rep ...

Guide to capturing mouse drag coordinates using JavaScript within a JSP page

My task is to record the starting coordinates (x,y) and ending coordinates (x,y) of a mouse event. For example, on an HTML page with an image, users should be able to select a specific area by dragging the mouse. Therefore, I need to capture the coordinat ...

Managing and updating arrays in VueJS2: Conditionally push new items and update only if their properties have changed

I am currently facing an issue with my form where each time a user updates a value in an input field, a new array element is created and added to the form results. I'm looking for a way to update the properties of the existing array element without cr ...

CSS - When using both display: flex and position: absolute, the anchor point is shifted

I have a flexbox element with three children. I want the second child to overlap the first child using absolute positioning, like this: Desired Outcome: https://i.stack.imgur.com/i479w.png It's important that the second child appears on top of the ...

using props as arguments for graphql mutation in react applications

Here is the structure of my code: interface MutationProps{ username: any, Mutation: any } const UseCustomMutation: React.FC<MutationProps> = (props: MutationProps) => { const [myFunction, {data, error}] = useMutation(props.Mutati ...

What is the best way to access external value in an Angular directive?

check out this plunker link. HTML: <body ng-app="app"> <h1>selectable</h1> <selectable text="link1" status="true"></selectable> <selectable text="link2" status="false"></selectable> <p> ...

Ways to retrieve the value of an Object that may have a key that is undefined

Is there a method similar to Angular's $parse service that can be used for accessing nested object properties? Consider an object structure like this: const obj = { items: [ { store: { type: '' } } ] }; Sce ...

What could be causing the background image on my element to not update?

I'm attempting to utilize a single background image that is 3 pixels wide and 89 pixels tall. Each vertical stripe of 1 pixel will serve as the background for a different div. I had presumed that adjusting the background-position by -1px 0 and specif ...

Chrome automatically scrolling back to the beginning of the page following a remote form submission

Rails Version: 5.2.2 Chrome Version: 78.0.3904.87 While testing my website on Chrome today, I encountered an issue where the page automatically scrolls to the top whenever an AJAX request is made. This problem only occurs in Chrome and not in other brows ...

Having trouble modifying a value in a form and submitting it to the following jsp page

I'm encountering an issue with changing the value in a hidden input element before submitting data to another JSP file (db.jsp) for processing. The value should be different depending on which button is clicked, but it always remains as the default va ...

How to effectively delete the class from a navigation list item

Looking for some inspiration? Check out the basic visuals for this question here. But let me break it down for you. This snippet shows the HTML & CSS behind a tabbed-carousel, with a condensed version for clarity: <style> #myCarousel-100 . ...

How do I retain the user's color choice using jQuery cookies for future visits?

I've created a jQuery color picker that allows users to save their color selection with just one click. You can see the color picker in action here: http://prntscr.com/7rnafa . To handle the saving of color selections, I'm using a helpful jQuery ...

Use JavaScript to upload a JSON file containing arrays into separate tabs

Looking for help with incorporating JSON data into an HTML template that features tabs and a gallery? Take a look at my setup below: <div class="tab"> <button class="tabLinks" onclick="openDiv(event, 'overview'); appendData()" id= ...

Having issues with ToggleClass and RemoveClass functionalities not functioning properly

As a novice in Jquery and CSS/scss, I've managed to create dynamic bootstrap cards for recording players. Each card consists of a music-container with control-play and vinyl elements. I aim to have multiple bootstrap cards generated based on the data ...

The vertical overflow from using Bootstrap grid extends into neighboring divs

There is quite a bit of code in this one, so I've decided to showcase it in a codepen. https://codepen.io/anon/pen/WMyQEJ Essentially, I'm utilizing @media queries to expand the #about div in order to accommodate my content that spills over into ...

In Javascript, assign default values to an array and update them with new values upon the click of a

My goal is to create a quiz that populates an array. Initially, the quiz is empty but I aim to assign it a default value. This serves as my question navigation: /** * * @param {int} question * @returns {QuizPart} ...