Tips for customizing a button created dynamically using JavaScript

I have been attempting to insert a button using .js into my HTML code. The purpose of this button is to appear every time I click on another button (identified with the id "imageChoose") which displays a preview of an image. This new button, labeled as removeButton (id: removeBttn), serves as a delete button for removing the displayed image and subsequently disappearing. Here is the HTML code snippet:

 <div class="row fileinput-control">
            <img id="preview" src="default5.png" width="500px" height="360px" style="padding-left:15px;" onload="addDeleteBttn()"/>
            <br/>
            <input type="file" id="image" style="display: none;" />
            <a href="javascript:changeProfile()">
                <div class="file-btns">
                    <span class="btn btn-default btn-file" id="imageChoose">
                        <i title="Select Image" class="fa fileinput-new fa-file-image-o"></i></span></div>
            </a>        
            <a id="removeBttnFrame" href="javascript:removeImage()">    
            </a>

            </div>
        </div>

The following .js code adds the button along with some styling:

function addDeleteButton() {
    var removeButton = document.createElement("BUTTON");
    removeButton.title = "Remove";
    removeButton.innerHTML = '<i class="fa fa-trash-o"></i>'
    removeButton.class = "removeButtonClass";
    document.getElementById("removeBttnFrame").appendChild(removeButton);
}

.removeButtonClass {
    position: absolute;
    top: 91%;
    left: 22.7%;
    transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%);
    background-color: white;
    cursor: pointer;
    border-radius: 5px;
    color: black;
    text-align: center;
    border-color: lightgray;
    height: 50px ! important;
    width: 53px;
    border-radius: 4px;
    padding: 10x 17px;
    border-width: thin
}

Although the button appears as expected, it lacks the intended styling. Strangely, the .css formatting seems to be completely disregarded. As someone new to HTML, I am struggling to find a solution. I have explored similar inquiries on How to dynamically create CSS class in JavaScript and apply? and also here: How to style dynamically created elements with CSS. Despite these resources, the issue remains unresolved. How can I resolve this problem?

Answer №1

It is recommended to utilize removeBtn.className over removeBttn.class

Answer №2

Instead of toggling a class on the remove button to hide it from the DOM when clicked and show it again upon clicking "imageChoose," why not utilize a function attached to the "imageChoose" button to toggle a specific CSS class, such as "removeBttn"?

This can be achieved by implementing functions like the following:

function loadPreviewImage() {
  // Add your code here to display the preview image
  const previewImageDiv = document.querySelector('#preview-image');
  previewImageDiv.classList.remove('hide'); 
}

function removePreviewImage() {
  const previewImageDiv = document.querySelector('#preview-image');
  
  previewImageDiv.classList.toggle('hide');
}
#preview-image.hide {
  display: none;
}
#preview-image {
  display: block;
  width: 200px;
  position: relative;
}
#remove-button {
  position: absolute;
  right: 0;
} 
img {
  max-width: 200px;
}
<div class="row fileinput-control">
  <button id="image-choose" type="button" onclick="loadPreviewImage()">Load Preview</button>

  <div id="preview-image">
    <button id="remove-button" 
            type="button" 
            title="remove preview" 
            onclick="removePreviewImage()">x</button>
    <img src="https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fupload.wikimedia.org%2Fwikipedia%2Fcommons%2Fthumb%2F6%2F66%2FLagothrix_lagotricha4.JPG%2F1200px-Lagothrix_lagotricha4.JPG&f=1&nofb=1" alt="monkey" title="monkey" />
  </div>
</div>

Answer №3

If you want your javascript to function properly, consider implementing the following changes.

function addDeleteButton() {
    var deleteButton = document.createElement("BUTTON");
    deleteButton.title="Remove";
    deleteButton.innerHTML='<i class="fa fa-trash-o"></i>'
    var styleElement = document.createElement('style');
    styleElement.type = 'text/css';
    styleElement.innerHTML = '.deleteButtonClass  { position: absolute; top:91%;'
    +'left: 22.7%transform: translate(-50%, -50%);-ms-transform: translate(-50%, -50%);'
    +'background-color: white;cursor: pointer;border-radius: 5px;color: black;'
    +'text-align: center;border-color: lightgray;height: 50px ! important;'
    +'width: 53px;border-radius: 4px;padding: 10x 17px;border-width: thin}';
    document.head.appendChild(styleElement);
    deleteButton.className="deleteButtonClass";

    document.getElementById("deleteButtonFrame").appendChild(deleteButton);
}

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

The process of creating a functional search bar in Django

I created a search bar, but I am facing an issue where no titles appear until I start typing. Once I type in one title, all the titles suddenly appear. How can I fix this problem? index.html def index(request): query = request.GET.get('srh' ...

Beautifully collapsing inline-blocks using only CSS

My header features three inline-blocks within a container that is text-aligned center. The left block floats to the left, and the right block floats to the right, creating a visually appealing effect where the middle block's text remains centered on s ...

Capture the output information and utilize it in a separate function

There are two functions in the code snippet below: 1: add-new-widget", function(). This piece of code is used for inserting JSON data and retrieving the last inserted ID from a table. In this code, the ID is obtained. alert(response['id']) ...

Having trouble with ng-click not correctly updating values within ng-repeat

Here is the code snippet: <div ng-repeat="data in products"> <div class=edit ng-click="dataUI.showEdit = true; content = data;"> </div> <div ng-repeat="renew in data.renewed"> <div class=edit ng-click="dataUI ...

eliminate whitespace characters within a string

Here is a question that suggests an easy way to remove space characters in a string using R. However, I encountered an issue when trying to remove a space between two numbers (e.g. 11 846.4) while working with the following table: require(XML) require(RCur ...

Parameterized Azure Cosmos DB Stored Procedure

I am currently learning about Azure Cosmos Db, and I am in the process of developing a simple JavaScript stored procedure that will return a document if a specific Id is provided. However, when I run the stored procedure, I do not receive a "no docs foun ...

Retrieve the element (node) responsible for initiating the event

Is there a way to identify which element triggered the event currently being handled? In the following code snippet, event.target is only returning the innermost child node of #xScrollPane, with both event.currentTarget and event.fromElement being null. A ...

Embed a physical entity within another physical entity

On my webpage, I have 2 toggle buttons - "Leaderboard" and "MedalTally". The layout looks like this: https://i.sstatic.net/IohqA.png Here are the codes for the above page: *, *:before, *:after { box-sizing: border-box; } html { overflow-y: scrol ...

Displaying Child1 on hover in CSS is simple using the Parent > Child1:hover selector. But how can we display Child2 using

Is there a way to modify my CSS Combo Box to display the menu div when hovering over the button div instead of the dropdown div? I have a container div with a dropdown div containing a button and a hidden menu. Currently, the menu is displayed when hoveri ...

Incorporate the Vue JS response into the table component

I am attempting to append my response from Vue into a table but I am unable to do so and I don't know why. I can retrieve all the data from my database, I can see it in my web browser console, but my table remains empty. Below is my current code: Vu ...

What is the best way to transfer an id from JavaScript to Rails while utilizing ajax?

Is there a way to call a rail route and pass in an ID from javascript? I have recently started using rails routes within my application, even in js. The current code I am using is: # app/assets/javascript/verifying_link.js $.ajax({ url: "/verify_link/ ...

Implementing a pop-up notification at the center of the display for empty fields

I am currently working on a task that requires me to display a pop-up message at the top-middle of the screen stating "please fill in all fields before submitting". This custom box should be stylable using CSS. Although the solution seems simple, I am str ...

ReactJs: How useEffect is invoked before onClick function in NextJS

I am facing an issue with a button in my Next project. Here is the code for the button: <Button minWidth={'140px'} onClick={() => exec(scope)} >Save</Button> When this button is clicked, it triggers the following function: c ...

What is the best method for changing a prop in a different component?

I have a list of accounts in my page.js file and I need to access this list in another component that is also rendered within the page.js file: var accounts = []; ... <div className="main"> <LeftPanel accounts={accounts}/> </di ...

The vertexUv in three.js is currently undefined and needs to be

I'm currently facing an issue while trying to combine multiple meshes, one of which is created by inputting the vertices coordinates. This specific mesh is causing the following error: THREE.DirectGeometry.fromGeometry(): Undefined vertexUv 256 W ...

Downloading xml data in an Angular table is a straightforward process that can be achieved

I have a table displaying a list of data. Each row includes an option to download XML data. 0{ firstName: null id: "04674" lastName: null orderId: "TEM001" productId: "TEM" receiptPeriod: "2016-02-26" ...

Encountering a Vue syntax error following the binding of a session variable

Encountering a syntax error while attempting to bind a session variable as a prop of my Vue component. Scrutinizing my code did not reveal any mistakes, but perhaps another set of eyes may catch something. This is where I have registered my components: V ...

The 'data' variable is not defined in the React custom hook Pagination

I am currently working with an API that shows music categories on a browser, and I'm attempting to create a custom pagination hook. However, I keep encountering an error stating "object is not iterable." I am new to custom hooks and would appreciate a ...

Transmitting Filter Choices as an Object for Retrieving Multiple Values within an Angular Application

In my Angular application, I have a function that takes user selections for various filter types and sends a request to the API to retrieve filtered data based on those selections. Each filter type returns values in an array format, allowing users to selec ...

Ways to execute a JavaScript function upon a button click instead of during the page load completion

I searched on Google but couldn't find the answer, so I'm asking here for help. In the attached screenshot located at the end, when the user clicks on the download button, some backend actions are performed such as file transfer. Once the proces ...