Tips on positioning div elements

I have successfully created a script that shows the preview of an uploaded image on the client-side along with the option to remove it.

However, I am facing an issue with the UI design as the position of the close icon is not aligned to the top-right corner.

Below you can find the code snippet and a JSfiddle link for testing purposes. To test it on JSfiddle, simply add an image using the browse button.

jQuery(function($) {
  $('div').on('click', '.closeDiv', function() {
    $(this).prev().remove();
    $(this).remove();
    $('#upload-file').val("");
  });

  var fileInput = document.getElementById("upload-file");

  fileInput.addEventListener("change", function(e) {

    var filesVAR = this.files;

    showThumbnail(filesVAR);

  }, false);



  function showThumbnail(files) {
    var file = files[0]

    var $thumbnail = $('#thumbnail').get(0);

    var $image = $("<img>", {
      class: "imgThumbnail"
    });
    var $pDiv = $("<div>", {
      class: "divThumbnail",
      style: "float: left"
    });
    var $div = $("<div>", {
      class: "closeDiv",
      style: "float: right"
    }).html('X');

    $pDiv.append($image, $div).appendTo($thumbnail);
    var reader = new FileReader()
    reader.onload = function(e) {
      $image[0].src = e.target.result;
    }
    var ret = reader.readAsDataURL(file);
    var canvas = document.createElement("canvas");
    ctx = canvas.getContext("2d");
    $image.on('load', function() {
      ctx.drawImage($image[0], 100, 100);
    })
  }
});
img {
  width: 30%;
  float: left;
  height: 100px;
  width: 100px;
}
.closeDiv {
  width: 20px;
  height: 21px;
  background-color: rgb(35, 179, 119);
  float: left;
  cursor: pointer;
  color: white;
  box-shadow: 2px 2px 7px rgb(74, 72, 72);
  text-align: center;
  margin: 5px;
}
.pDiv {
  float: left;
  width: 100%
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div id="thumbnail"></div>
<input type="file" id="upload-file" accept="image/*" />

http://jsfiddle.net/r0taz01L/11/

Answer №1

Make sure to include the following CSS styles:

 .divThumbnail {
position: relative;
}

Also, add the following styles for the close button:

.closeDiv {
    position: absolute;
    width: 20px;
    height: 21px;
    background-color: rgb(35, 179, 119);
    float: right;
    cursor: pointer;
    color: white;
    box-shadow: 2px 2px 7px rgb(74, 72, 72);
    text-align: center;
    margin: 5px;
    right:0px;
}

For a complete solution, you can check out this example on JSFiddle: http://jsfiddle.net/r0taz01L/12/

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

Using various conditions and operators to display or conceal HTML elements in React applications, particularly in NextJS

I am seeking ways to implement conditional logic in my React/Next.js web app to display different HTML elements. While I have managed to make it work with individual variable conditions, I am encountering difficulties when trying to show the same HTML if m ...

Having trouble retrieving an element's attribute using jQuery

I am facing an issue with the following HTML code: <img src="http://localhost:82/Clone//images/hosts/Kinx_9843a.jpg" data-name="/images/hosts/K_9843a.jpg" alt=""> I am attempting to achieve the following functionality: $('body').on(&apos ...

jQuery fails to generate correct HTML code

I am currently working on maintaining an older Rails 3 project that I need to update with new features, particularly adding responsiveness using Bootstrap 4. The end result I am aiming for can be viewed here: http://jsfiddle.net/k1zbe4o9/. It functions pe ...

Three fluid columns in a CSS flexible container

I need help with creating a fluid div container: width: 97%; min-height: 80px; -webkit-box-shadow: 1px 1px 5px 1px rgba(0,0,0,0.45); -moz-box-shadow: 1px 1px 5px 1px rgba(0,0,0,0.45); box-shadow: 1px 1px 5px 1px rgba(0,0,0,0.45); background: white; margin ...

Display JSON on the screen so it can be easily copied and pasted

I have a unique challenge where I need to output some Javascript code on the browser screen for easy transfer to another program. Currently, I am utilizing JSON.stringify() from the json2.js library. However, this method is not correctly escaping characte ...

Efficiently merging data from various AngularJS resources

I've encountered a recurring scenario while developing Angular apps, especially when utilizing a Drupal API. I'm seeking advice on best practices for handling this specific issue. Currently, I am working on an app that interacts with a Drupal AP ...

Tips for handling a promise that has not been fulfilled

Is there a way to return a promise and trigger its failure block right away? Check out this unconventional method: if (fail) { var q = $q.deferred(); $timeout(function() { q.reject("") }, 1); return q.promise; } else { return ...

Progress bar displaying as the script executes

Looking for ways to display a loading bar while a PHP script is running for 10 seconds, pulling in data and storing it in the database? Once the script is done, want to load the page that the user is on. Any suggestions on how to achieve this? Thank you! ...

Attempting to insert an element after the .load event has been triggered

I have been attempting to update the contents of ".myShop" after it's loaded from an external XML file, but without success. I believe my timing is correct, but I suspect that a loaded element may not be part of the DOM? Here's what I'm exp ...

Unable to scroll down an overlay window using Selenium with Python

When using Quora, I am trying to scroll to the bottom of the window that appears when I click on the "View upvoters" button in order to access all the names of those who have upvoted. However, the code for scrolling down a standard browser window doesn&apo ...

Is there a way to generate unique authentication numbers daily without the need to manually adjust any code

I am building a web application for commuters using vuejs and firebase. My goal is to implement the following feature: The employer provides the employee with a unique authentication code daily, which the employee (user) must enter when clicking the "go t ...

Triggering a click event on tags within a many-to-many field in Odoo 12

I've been attempting to create an event for tags within a many2many field using the following JavaScript code: var FieldMany2ManyTags = relationalField.FieldMany2ManyTags.include({ events: _.extend({}, FieldMany2ManyTags.prototype.events, { ...

Exploring ways to transfer a function variable between files in React

Currently, I am working on a quiz application and have the final score stored in a function in app.js. My goal is to generate a bar graph visualization of the user's results (e.g. 6 right, 4 wrong) based on this score. To achieve this, I created anoth ...

Retrieving the selected value from a dropdown menu before it is altered using vanilla JavaScript

I am trying to implement a feature where the previous value of a dropdown is captured when it is changed. Essentially, I need to compare the previous and current values of the dropdown and perform an action based on that information. For example, if Option ...

Retrieving values from multiple Select components in Material-UI is key

I have encountered an issue with my two MUI Select components on the page. I am attempting to set values based on the id of the Select component. Initially, when I check (id === "breed-select") in the console, it returns true, but shortly after ...

Tips for Organizing and Filtering Firebase's Realtime Database using Cloud Functions, Node.js, and Javascript to Create a Leaderboard for "Top Scores"

After numerous days of research and trial & error, I am still unable to make any progress. To test my function's logic, I created some test nodes in my Firebase Realtime database, resulting in the following file tree: https://i.sstatic.net/Ps7Mq.png ...

What is the best way to ensure the search box remains fixed in the top navigation bar while maintaining a fluid and responsive design?

I've been struggling as a novice programmer, and even with the help of more experienced programmers, we haven't been able to figure it out. I'm trying to integrate a search box into the top navigation that adjusts responsively to different ...

"Troubleshoot: Issue with React class component's setState not correctly updating

Hey there! I could really use some help with the issue I'm facing: So, I have a React class component that extends React.Component and it has a method that allows me to set its state whenever I want. I understand that passing a prop to the component ...

Problem encountered when closing a lightbox on ASP.net using C# during page load

Can you explain the events that are triggered when the ASP.NET page load event occurs? I am currently using a lightbox for some insertion tasks, and after the insertion is complete, I want the parent page to reload with the new value displayed in the gri ...

Searching for the prime numbers within an array and then saving them into a separate array using Javascript

I have been working on a program that aims to identify prime numbers within an array and store them separately. While the code seems to be functioning correctly overall, there is an issue where a non-prime number (33) is incorrectly labeled as prime due to ...