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

Sending POST parameters via Jquery POST from a Java Servlet to Javascript

My JavaScript code initiates a POST request on my Servlet. $.post("RecipeServlet", { r_id: r_id, }, function(data, status){ var foo = data.foo; var bar = data.bar; }); Now, the Servlet is expected to work with the received r_id and then send ...

How to extract words from a dynamic router.pathname in NextJS when only the filename is displayed instead of the full path?

I'm keeping this example as straightforward as possible, but I can add more details if needed to solve the issue Currently, I am working with dynamic routes in nextJS. My application fetches data from Twitter based on the keywords entered into the dy ...

Ensure that a group of checkboxes is mandatory

I currently have a series of checkboxes set up like so: <label>What is your preferred movie genre?</label> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="genre1" name="genre" ...

Preventing Vue.js SPA from accessing cached version when JWT expires: the solution

I'm encountering an issue with my Vue.js / Express application that I can't seem to resolve. Here's how the process unfolds: An unauthenticated user logs into the app and is presented with the login page. Once successfully authenticated, t ...

Can an action be activated when the mouse comes to a halt?

Currently, I am having trouble triggering an event when a user stops moving their mouse over a div element. The current event is set up to show and follow another element along with the mouse movement, but I want it to only display when the mouse stops mov ...

What is causing the jQuery functions to not be executed in sequence?

Whenever I click the Start button, my function is supposed to run a cycle for 10 iterations. Each iteration generates a number between 1 and 7, which then triggers a series of functions on different objects. The problem is that these functions are not runn ...

Tips for capturing and storing video with HTML5 WebRTC

Before reading the description, make sure to run the code snippet first. This will provide you with a better understanding of the structure. In the 2nd video element, I am trying to record, play, and save video. The issue I'm encountering is that the ...

Select2 Bootstrap - Preselecting Options

I am currently utilizing Bootstrap Multiselect but I am encountering some difficulties setting the default value for the multiselect as per the documentation provided. Inside a function, I have tried the following: $("#selector").multiselect("select", ["V ...

PHP object representing a datetime in JSON format

How can I convert a JSON datetime object sent to JavaScript into a JavaScript datetime object? The PHP return is: "date": { "lastErrors": { "warning_count":0, "warnings":[], "error_count":0, "errors":[] }, "timezone": { "nam ...

Issue with JavaScript ScrollTop

Simply put, I am trying to determine the total scroll size for a text area in a unit that scrollTop can align with. However, I am at a loss on how to do so. I've tried scrollHeight and various other methods without success. Any advice or suggestions ...

How can I execute a task following a callback function in node.js?

Is there a way to run console.log only after the callback function has finished executing? var convertFile = require('convert-file'); var source, options; source = 'Document.pdf'; options = '-f pdf -t txt -o ./Text.txt'; ca ...

Customizing Bootstrap Navigation: Creating Space Between Menu Items

I've configured my Bootstrap navigation with a dropdown toggle for "Coverage". I'm looking to decrease the spacing between each list item (li) under this dropdown. What CSS setting should I use to achieve this? Interestingly, when I apply float: ...

What is the best way to eliminate duplicate values from an Array in ReactJS?

Hi there, I'm new to JavaScript and React. I need some help with a project I found on the React blog. I want to try solving it in my own way. This is the content of todoList.js: const todoList = [ {category: 'Sporting Goods', price: &a ...

Encountering a surprising token error while running a node.js application with a classic example

I downloaded node.js from its official website and followed the instructions provided here. I attempted to run the example code snippet from the "JavaScript - The Good Parts" textbook: var myObject = { value: 0; increment: function (inc) { this.value ...

Showing a numerical value in the bottom-right corner alongside a backdrop of an image

I am attempting to create a container that measures 26x26 pixels and showcases a number at the bottom right corner of this container. Furthermore, I want to include a 24x24 picture as the background of the container. The code I have written so far is disp ...

Bootstrap UI Tab presents an obstacle for Google Map functionality

When utilizing the Bootstrap Tabset to include a Bootstrap slider, Google Map, and other pages, I encountered an issue where the slider functions perfectly but the Google Map does not work as expected. Interestingly, the map works perfectly in street view ...

Dealing with issues regarding the rendering of events in FullCalendar when utilizing the .getJSON() method from

I'm facing some difficulties when trying to render an event in the month view of FullCalendar. Below is the code snippet that makes a .getJSON call from the razor page, followed by the JsonResult returned by the controller and the object displayed in ...

Ways to insert text inside a border

I'm struggling to figure out how to insert text within a border. Can someone guide me on how to accomplish this? Is there a way to place text in the center of a border? I have included a screenshot for reference. ...

Apply CSS styling to the shadow root

In my preact project, I am creating a Shadow DOM and injecting a style element into the Shadow root using the following code: import style from "./layout/main.css"; loader(window, defaultConfig, window.document.currentScript, (el, config) => ...

Upon triggering a GET request to the URL "http://localhost:3000/search", a "404 (Not Found)" error response was received. Interestingly

Can Someone assist me please? I'm having trouble creating a website similar to YouTube and encountering the following error: GET http://localhost:3000/search 404 (Not Found) Uncaught (in promise) Error: Request failed with status code 404 at createEr ...