Having trouble with the preview feature when resizing images

Before trying to implement the JSFiddle was working correctly: http://jsfiddle.net/qa9m7t33/

However, after attempting to implement it, I encountered some issues: http://jsfiddle.net/z1k538sm/

While trying to resize an image, I realized that this example might not have been suitable for my situation as I am new to this. I suspect the issue lies with the variable:

var width = e.target.result.width(); // Current image width
var height = e.target.result.height(); // Current image height

I am also struggling with centering text in the upload field.

Here is the updated version of the Fiddle: http://jsfiddle.net/m5jLf259/

Answer №1

In order to resolve this issue, you can set the line-height using CSS for the specific element:

#file {
    line-height: 37px;
}

If you prefer to achieve this using jQuery, you can do the following:

$('#file').css('line-height', $('#file').height() + 'px');

Regarding the initial problem description, it seems a clear question was not provided.

Additional Tip: To address the initial concern, follow these steps:

var wrapper = $('<div/>').css({height:0,width:0,'overflow':'hidden'});
var fileInput = $(':file').wrap(wrapper);

fileInput.change(function(){
    readURL(this);
})

$('#file').click(function(){
    fileInput.click();
}).show();

function readURL(input) {
    $('#blah').hide();
    if (input.files && input.files[0]) {
        var goUpload = true;
        var uploadFile = input.files[0];
        if (!(/\.(gif|jpg|jpeg|tiff|png)$/i).test(uploadFile.name)) {
            $('#file').effect( "shake" );
            $('#file').text('You must select an image file only');
            setTimeout(function() { $('#file').text('Choose file');},5000);
            goUpload = false;
        }
        if (uploadFile.size > 2000000) { // 2mb
            //common.notifyError('Please upload a smaller image, max size is 2 MB');
            $('#file').text('Please upload a smaller image, max size is 2 MB');
            setTimeout(function() { $('#file').text('Choose file');},5000);
            goUpload = false;
        }
        if (goUpload) {
            $('#file').text("Uploading "+uploadFile.name);
            var reader = new FileReader();
            reader.onload = function (e) {
                var img = new Image;
                img.onload = function() {
                    var maxWidth = 100; 
                    var maxHeight = 100; 
                    var ratio = 0; 
                    var width = this.width; 
                    var height = this.height; 

                    if (width > maxWidth) {
                        ratio = maxWidth / width; 
                        $('#blah').css("width", maxWidth); 
                        $('#blah').css("height", height * ratio); 
                        height = height * ratio; 
                    }


                    if (height > maxHeight) {
                        ratio = maxHeight / height; 
                        $('#blah').css("height", maxHeight); 
                        $('#blah').css("width", width * ratio); 
                        width = width * ratio; 
                    }
                    $('#blah').attr('src', this.src).show();
                    $('#file').text(uploadFile.name);

                };
                img.src = reader.result;

            }
            reader.readAsDataURL(uploadFile);
        }
    }
}

It's advisable to avoid duplicate lines like:

 47           var width = uploadFile.width(); 
 48           var height = uploadFile.height(); 

since they negate the previous actions.

Additionally, utilize FileReader() in conjunction with creating an Image Object for optimal results.

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

A helpful tip on how to designate a specific color to the helperText in Material UI in order to emphasize

Is there a way to customize the color of helperText in material-UI for highlighting errors in a TextField? I've been struggling to change the color of helperText with no success. I attempted using MuiFormHelperText-root-406 to add CSS styles, but it ...

Javascript function fails to trigger when clicked

<body ng-app="starter"> <ion-pane> <ion-header-bar class="bar-dark"> <h1 class="title">AppifyLife</h1> </ion-header-bar> <ion-content> <center><div class="card" id="life"><h3>20< ...

The specified userID cannot be located within the array of objects

Trying to understand a tutorial on nodejs and expressjs that teaches how to implement user permissions on routes. However, I'm facing issues with a simple middle ware function designed to set the req.user as it keeps showing up as undefined. Below is ...

The touch event doesn't seem to be functioning properly on the div element, but it works perfectly on the window element

I have a dilemma that's been puzzling me lately. I'm trying to append a touchevent to a div, but my current method doesn't seem to be working. Here's what I've tried: $("#superContainer").bind('touchstart', function(even ...

What is the functionality of the CSS switch button?

I'm curious about how the cool turn on/off switch button actually works. Take a look at for reference. I'm interested in implementing a prevention check to confirm whether the user truly wants to switch the button. Here's a snippet of the ...

Should the article ID be sent to the ajax file, or should the ajax file retrieve the article ID directly? This dilemma arises in a

I am trying to pass the current article ID to an ajax file. The URL of the ajax file is something like www.web.com/plugins/system/ajax.php, so using JRequest::getInt(id) always returns 0 integer. However, in a non-ajax file, I can get the ID the same way. ...

Using Jquery to activate a vertical scrolling bar

Within my div, I have a tree view that extends beyond the size of the div, causing a vertical scroll bar to appear on the right side. When users click a button outside of the div, I want the page to scroll to a specific item within the div (which I know th ...

Every time I use Get for ajax calls, I keep getting hit with a frustrating

Initially, I was making a call to a [web method] using the POST method. However, since I need to receive data back, I attempted to switch to using the GET method instead. The previous implementation using POST was successful. Unfortunately, using GET resu ...

Issues with navigation menus in Bootstrap/Wordpress

My mobile drop-down menu is giving me some strange issues. When you toggle the button, the menu briefly appears just below the button before moving to its correct position. Sometimes it doesn't work at all, and clicking has no effect. You can witnes ...

Display a JSX component based on a specific condition

As a newcomer to React, I am currently working on the navigation portion of my Navbar.js using the react-router-dom useLocation hook. I have successfully obtained the active path that leads to views and now I want to display custom text when a user reaches ...

The NodeJS req.query is providing inaccurate information

When I send a JSON from the Client-Side to a NodeJS Server, it looks like this: $.ajax({ type: "POST", dataType: "jsonp", url: "www.xyz.com/save", data: { designation: "Software Developer", skills: [ "", "ASP.NET", "P ...

Troubleshooting Azure typescript function: Entry point for function cannot be determined

project structure: <root-directory> ├── README.md ├── dist ├── bin ├── dependencies ├── host.json ├── local.settings.json ├── node_modules ├── package-lock.json ├── package.json ├── sealwork ...

Tips for halting all YouTube videos in a Reactjs environment

I am currently working with React.js and using Next.js. I have implemented a "YouTube video slider" and now I am looking for a way to stop all videos when a button is clicked. Can anyone provide guidance on how to achieve this? Below is the code snippet ...

Building a like/dislike feature in Angular

Here is a snippet of code I have that includes like and dislike buttons with font-awesome icons: <ng-container *ngFor="let answer of question.answers"> <p class="answers">{{answer.text}} <i class="fa fa-hand-o-le ...

The calculation of Value Added Tax does not involve the use of jQuery

My form setup is as follows: <form method="post" action="" id="form-show"> <table class="table table-bordered table-striped table-hover" id='total' style="width:100%;"> ...

Troubleshooting AngularJS binding problem when using ngRepeat to handle Collapse and Expand Caret icon

I am experimenting with implementing collapsible and expandable panels within an ngRepeat loop. Here is my approach: <tbody ng-repeat="item in Items"> <tr data-toggle="collapse" class="accordion-toggle"> <td>{{item.name}}< ...

What is the best way to create a dynamic textbox or label within a specific div class?

I need assistance with my dynamic asp.net page where I am generating labels and text boxes in a form. Is there a way to ensure that these elements are generated within a specific div class? Below are the relevant code snippets: for (int i = 0; i < cou ...

Alignment of slider arrows in a CSS carousel with Bootstrap 4.1.1

Is there a way to position the carousel control arrows at the left and right ends of the screen in Bootstrap 4.1.1? I attempted the code below but it didn't yield the desired result. .carousel-control .icon-prev{ left: 5px } .carousel-control .icon ...

Two separate buttons in two distinct views that trigger the same function in AngularJS

I am currently working on a Single Page Application (SPA) that has two distinct views - one for subjects and another for students. In the subject view, there is a save button located in app/views/subject/subject.html: <button type="button" class="b ...

What is the most effective way to extract information from a .txt file and showcase a random line of it using HTML?

As a newbie in HTML, my knowledge is limited to finding a solution in C#. I am attempting to extract each line from a .txt file so that I can randomly display them when a button is clicked. Instead of using a typical submit button, I plan to create a custo ...