Align the image in the middle using JavaScript for Firebase

I am struggling to display the center of an image within a circle-shaped <img> tag with a border-radius of 50%. The issue arises when trying to display an image fetched from Firebase storage, rather than from a URL.

In attempt to solve this problem, I have experimented with JavaScript code that successfully centers the image when done as follows:

.box {
  height: 100px;
  width: 100px;
  overflow: hidden
}

.wh {
  height: 100%!important
}

.ww {
  width: 100%!important
}
<div class="box" style="border-radius:50%;">
  <img src="1.jpg" />
</div>
<input type="file" id="fileButton" /> <input type="submit" value="Upload" id="uploadButton" />

This produces the desired result:

https://i.sstatic.net/Jk2zV.png

However, when attempting to use the same image from Firebase, the outcome is different:

https://i.sstatic.net/m7efx.png

Here is the code snippet utilizing Firebase along with the necessary JavaScript for image centering (which was also used in the previously mentioned URL example):

var fileButton = document.getElementById('fileButton');
var uploadButton = document.getElementById('uploadButton');

// Adds an event listener to watch for changes in the file input
fileButton.addEventListener('change', function(e) {
  var file = e.target.files[0];
  
  // Creates a storage ref in firebase
  var storageRef = firebase.storage().ref('test/profilePic.jpg');

  console.log(file.height);

  // Listens for click on upload button 
  uploadButton.addEventListener('click', function(e) {
    storageRef.put(file).then(function() {
      window.open('profil.php?error=1', '_top');
    });
  });
});

var storage = firebase.storage();
var storageRef = storage.ref();
var spaceRef = storageRef.child('test/profilePic.jpg');

storageRef.child('test/profilePic.jpg').getDownloadURL().then(function(url) {

  var test = url;
  document.getElementById('profilePicture').src = test;

}).catch(function(error) {

});
...

.box {
  height: 100px;
  width: 100px;
  overflow: hidden
}

.wh {
  height: 100%!important
}

.ww {
  width: 100%!important
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box" style="border-radius:50%;">
  <img id="profilePicture" />
</div>
<input type="file" id="fileButton" /> <input type="submit" value="Upload" id="uploadButton" />

If you have any insights or solutions on how to resolve this issue, please let me know!

Answer №1

There might be a few issues at play here.

  1. You could be facing an asynchronous problem (such as setting styles in JavaScript before Firebase returns with the data).
  2. It's ideal to have your styling defined in CSS.
  3. Avoid using !important; instead, grasp and apply CSS specificity effectively.

If you set up your CSS properly, it will resolve these issues for you. I removed Firebase and unnecessary components to maintain clarity. The root cause seems to stem from either an asynchronous problem or improper CSS utilization. I'm demonstrating an async change utilizing setTimeout in JavaScript.

setTimeout(function(){
  document.getElementById("imageid").src="http://www.threeriversschools.org/pages/district-blog/image/section-image/soccer-194.jpg";
},3000);
.box{
height:100px;
width:100px;
overflow:hidden
}
.box img{
  width : 100%;
  height : 100%;
}
<div class="box" style="border-radius:50%;" >
<img id="imageid" src="http://cdn-mf1.heartyhosting.com/sites/mensfitness.com/files/styles/wide_videos/public/soccer-kick-goal-kickoff-1280.jpg?itok=z-E-ZQem" />
</div>

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

"Enhance Your Video Experience with a Personalized Play Button

Is it possible to customize the play icon for an embedded YouTube video? I came across a post discussing this topic: Can I change the play icon of embedded youtube videos? However, when trying to use something transparent as the new play button, the origin ...

Splitting two distinct dropdown menus in Bootstrap 4: A step-by-step guide

I recently came across a helpful tutorial on Bootstrap 4 by W3Schools (https://www.w3schools.com/bootstrap4/bootstrap_button_groups.asp) and was curious about how dropdown menus function. <div class="btn-group"> <button type="button" class="b ...

Nuxt js - Components are replicated on SSR pages

I have created a static page containing various components. When I navigate to this page from another page, everything displays correctly. However, when I directly land on the page, some components are duplicated and rendered again after the footer. Upon i ...

The function screen.getByText is not available in this context

My experience with jest and react-testing-library has been smooth for the most part, but I encountered some challenges when transitioning to the screen > getByText/etc testing method. Test describe('test the dashboard when loaded', () => { ...

Is it possible to make the li elements within my ul list display on multiple lines to be more responsive?

My credit card icons are contained within a ul. I have used the properties background-image and display:inline for the LIs, which display nicely on larger screens. Unfortunately, when viewed on mobile devices, the icons are cut off. My question is whether ...

Is it possible to convert an object and/or a nested array with objects into a JSON string without relying on JSON.stringify?

Struggling to generate a correct JSON string from an object without relying on JSON.stringify(). Presenting my current implementation below - var my_json_encode = function(input) { if(typeof(input) === "string"){ return '"'+input+&apo ...

Troubleshooting issues with jQuery getJson() in an ASP.NET MVC environment

I'm trying to utilize jQuery to make a simple call to my MVC controller. I've successfully tested the server side, as the controller correctly received the ajax call and returned the requested information. However, on the client side, the data is ...

Error encountered in SelectInput.js file of React MUI 4: line 340 - TypeError: Unable to access properties of undefined (specifically 'value')

An issue arises when an empty array is provided as the options. The error message: SelectInput.js:340 Uncaught TypeError: Cannot read properties of undefined (reading 'value') at SelectInput.js:340:1 at Array.map (<anonymous>) ...

Creating a custom table layout with JavaScript and jQuery

I've been grappling with a project for some time now, and I'm stuck on this particular issue. In my database, I have a table structured like this: ProjectName UserName SpentDays FirstProject User1 10 SecondProject User1 5 SecondProjec ...

Removing connected entries with pre middleware on mongoose

I currently have 3 different schemas: Building const BuildingSchema = mongoose.Schema({ address: { type: String, required: true }, numberOfFloors: { type: Number, default: 0 }, }); Apartment const RoomSchema = mongoose.Schema({ roomNumber: { type: ...

Edit the settings for the dual-axis line chart's parameters

After countless hours of scouring the Internet and numerous attempts, I have come to the decision to seek help by posting my issue on this forum. I must confess, I am not the best developer. My approach usually involves finding pre-existing code that I ca ...

Fixing Firefox Bug: How to Eliminate Non-Numeric Characters from "Number" Input Fields

Completing this task seems straightforward. I need to eliminate any non-numeric characters from an input field specified as type "number" in Firefox when a key is pressed. The code snippet provided: $("#field").on("keyup", function() { regex = /[\& ...

Adjust the size of a Div/Element in real-time using a randomly calculated number

Currently, I am working on a script that is designed to change the dimensions of a div element when a button on the page is clicked. The JavaScript function connected to this button should generate a random number between 1 and 1000, setting it as both the ...

Retrieve the ngModel's current value

One of the challenges I encountered is with a textarea and checkbox interaction. Specifically, once the checkbox is checked, I aim to have the value appear in the textarea. <div class="message-container"> <textarea *ngIf="mode === 1" ...

Tips for rendering the stencil as invisible and disabled while still allowing other features (such as rotating and flipping) to remain enabled within the react-advanced-cropper

I am facing a challenge where I need to hide and disable the stencil and overlay in react-advanced-cropper, while keeping all other features like rotation and flipping enabled. Is there a specific property in this library that allows me to disable the st ...

Retrieving information from a TableRow element within Material UI

In the latest version of Material UI, I am utilizing a Table component but struggling to figure out how to fetch data from a selected row. The Table component's documentation mentions an onRowSelection prop that provides only the RowNumber of the sel ...

When a key is pressed, apply a background color and fade out effect using JavaScript

Whenever the enter key is pressed, I want to make a red color appear briefly and then fade out quickly to create a blinking effect. I attempted adding a new class on Keypress that would transition the opacity to 0: function enterpressalert(e, text) { ...

Creating an interactive dropdown feature using AngularJS or Ionic framework

$scope.AllCities = window.localStorage.getItem['all_cities']; <div class="row"> <div class="col"> <div class="select-child" ng-options="citie.name for citie in AllCities" ng-model="data.city"> <label&g ...

Tips for positioning a Wordpress navigation bar to the right of a logo

My goal is to position the navigation bar next to the logo in my Wordpress theme using Underscores. I have successfully aligned the primary navigation and the logo as desired with the following CSS: .main-navigation { position: relative; float: ri ...

Overflow on flex layout causes line breaks

I am facing an issue with two divs in a flex container where I want them to be displayed on separate lines when they overflow .container { background: wheat; padding: 10px; width: 300px; display: flex; justify-content: space-betwee ...