Display a preview window once the image has been chosen

I have created an image preview div to show the selected image's thumbnail. Everything was working fine so far. But now, I want this div to be hidden when the page initially loads and only become visible when a user selects an image to upload. Here is how I have set it up:

 <div class="fileinput fileinput-new" data-provides="fileinput">
 <div class="fileinput-preview thumbnail" data-trigger="fileinput" style="width: 200px; height: 150px; display:none"></div>  #This is the div for previewing images
 <div>
 <span class="btn btn-info btn-file">
 <span class="fileinput-new">Select image</span>
 <span class="fileinput-exists">Change</span>
 <input type="file" name=""></span>

Here is my jquery code (I am new to jquery):

<script type="text/javascript>
$(document).ready(function(){
    $(".btn btn-info btn-file").click(function(){
        $(".fileinput-preview thumbnail").show();
       });
});
</script>

jsFiddle http://jsfiddle.net/3717h5mg/1/

Unfortunately, this setup is not functioning as expected.

Answer №1

experience

$(document).ready(function(){
    $(".btn.btn-info.btn-file").change(function(){
         $(".fileinput-preview.thumbnail").display();
    });
});

IMPORTANT : Remember to include the dot(.) selector in the click event for $(".btn btn-info btn-file"), and also the thumbnail class

SEE DEMO

Answer №2

Display the thumbnail when a file is selected

$(document).ready(function(){
 $('input[type="file"]').change(function () {
     $(".fileinput-preview.thumbnail").show();
 });
});

Answer №3

It was mentioned by Bala and anspsmn that the solution lies in handling the 'onchange' event, addressing your question directly. However, for a simpler approach, you may consider using a Jquery plugin to achieve the same task more efficiently. I have personally created a Jquery plugin that can be easily tailored to suit your specific requirements. This plugin allows you to select images (or any file type), preview them, crop if necessary, and seamlessly upload them. Additionally, it offers features such as setting maximum file size in KB, drag and drop functionality, customizable buttons, and more.

For example:

$('#your-input-file').customFile({
   type : 'image',
   maxKBperFile : 500,
   maxFiles : 1
});

For further information and to download the plugin, please visit: Jquery Custom Input File

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

Rows that have been removed from an HTML table remain within the ReactDOM

After diving into JavaScript three months ago, I recently began learning React.js just two days back. While creating a simple TODO app, I noticed that when deleting a row, it disappears from the DOM but not from the React DOM. Can anyone shed some light ...

What is the way to create the appearance of a hand or arrow hovering over my "X" while I am closing out my Div using jQuery?

Hey there, I've got a handle on closing the div using a "p" tag in jQuery. The code snippet for that is provided below. However, I'm looking to change the cursor over the "X" to an arrow or hand symbol, similar to what you'd see with an "a" ...

Error: Issue with hook function call detected. Struggling to locate exact source in React JS

As I dive into React for the first time, I'm working on creating a sign-up form with multiple steps. Despite reading through the material-ui documentation and learning about ReactJS, I'm struggling to pinpoint where I've gone wrong. Here&ap ...

What could be causing certain items in my Bootstrap navbar to be hidden on mobile screens?

When I view my website on mobile devices, only the logo appears in the navbar, not the other elements. Can you help me troubleshoot this issue? NavBar HTML Code: .navbar-logo { width: 93.75px; height: 23.5px; margin-left: 10rem; } .navba ...

Choosing an option in Angular 2 based on a specific condition

My question is about a select element: <select id="position"> <option *ngFor='#contactType of contactTypes' [attr.value]='contactType.contactTypeId'> {{contactType.description}} </option> </select ...

Tips for creating a Discord bot that can respond to inquiries with varying responses

Lately, I've been working on a Discord bot that selects a random response from an array of replies. My goal is for it to display an error message if the question is unknown or if no arguments are provided after the command. I currently have some code ...

How can I create a tooltip function in JavaScript/jQuery that uses the "this" keyword?

JSFiddle link: http://jsfiddle.net/lustre/awpnd6L1/1/ I am curious if it's possible to create a JavaScript function that consolidates the mouseenter code for a "More Info" tooltip. Rather than copying the code multiple times, is there a way to stream ...

Tips for choosing an item within a div -> ul -> li using Selenium

I need help with a menu that displays a list on mouse hover, and I'm trying to click on "Logout". However, the code I've written so far is not giving me the desired result. This is the Java code I have: public void logout() throws Exception { ...

Apply a specific CSS class to a division depending on the currently active cookie

I have implemented cookies on specific pages using https://github.com/carhartl/jquery-cookie. Could someone guide me on how to apply a CSS class to an ID (e.g., adding class .red to #mouse if the cookie named "socks" is active)? For example: If there is ...

Troubleshooting the Issue with WordPress Image Customization Settings

I'm in the process of designing a Wordpress theme, but I've hit a roadblock. I'm utilizing the theme customize page to upload both a main logo and a mobile logo, which should then be displayed on the page. Initially, it was working for about ...

Issues with image uploads in Node.js database storage

Trying to update an image using the put method is resulting in a 'filename' undefined error. Interestingly, the image updates successfully when editing without changing the image. The code snippet below shows the implementation: app.put('/a ...

In JavaScript using Vue.js, you can compare various objects within an array and calculate the total sum of their values based on a shared

This task may pose a challenge for those new to programming, but seasoned developers should find it relatively simple. I've been searching for a solution without success so far, hence turning to this platform for help. Here's the scenario at han ...

What is the best way to stop form submission in AngularJS when submitting the form by pressing the enter key?

I have implemented validation on my form (which consists of only two fields) but I am struggling to figure out how to prevent it from being submitted with empty data. The current flow is as follows: Upon pressing the enter key, the student's name and ...

Deactivating the class from a button

On my website, I have 3 buttons that represent different product categories. The initial state of the page should load with the "All Products" button having an active class. However, when clicked, this active class should be removed from the "All Products" ...

Issue: Unable to locate 'path' in directory 'C:workdemo ode_modulesmime-types'

Encountering an error after updating from "react-scripts": "4.0.3" to "react-scripts": "5.0.1",. I need assistance with understanding why this error is occurring and how to resolve it... ERROR in ./node_modules/mime ...

Creating a dropdown menu with a blur effect using CSS

I attempted to match the opacity and blur effect of my dropdown menu with that of my navbar. While the opacity adjustment worked correctly, the blur effect did not apply as expected. I've heard that I need to utilize a pseudo-class to achieve this, b ...

The parameter value experiences an abrupt and immediate transformation

I recently created an electron app using Node.js and encountered a peculiar issue that I am unable to resolve: Below is the object that I passed as input: { lessons: [ name: "math", scores: [90, 96, 76], isEmpty: false ] } ...

Hamburger must be used in order for the menu to be displayed

Whenever I visit the site, the menu remains hidden. However, when I resize the page and use the hamburger icon, the menu appears as expected. Even after resizing the page back to its original size, the menu continues to be visible. Refreshing the sit ...

Unable to make cross-domain AJAX request with Sinatra - attempting to send JSON using jQuery's ajax function

Currently, my sinatra app on the server has the following configurations: before do headers 'Access-Control-Allow-Origin' => '*', 'Access-Control-Allow-Methods' => ['OPTIONS', 'GET', &apo ...

Is it possible to resize an image to fit within its parent div using only the parent div

Is there a way to ensure that an image inside a div resizes itself based on the dimensions of the div without distorting the ratio? <div class="w-50"> <img src="" class="w-full h-full image-cover"> </div> ...