A step-by-step guide on utilizing img src to navigate and upload images

I would like to hide the input type='file' element with id "imgInp" that accepts image files from users. Instead, I want them to use an img tag to select images when they click on a specific img tag. How can this be achieved using jQuery?

Here is the current output for reference: http://jsfiddle.net/LvsYc/3135/

$(document).ready(function() {
    var currentSrc = $('#Picture').attr('src');
    if(currentSrc==null || currentSrc==""){        
        $('#Picture').attr('src','http://i38.photobucket.com/albums/e149/eloginko/profile_male_large_zpseedb2954.jpg');
    }


    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#Picture').attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }

    $("#imgInp").change(function(){
        readURL(this);
    });

});

Answer №1

If you want to achieve this effect with CSS, one way is to hide the opacity for the file input element and position it on top of the image like this:

#form1 {position:relative}
#imgInp {position:absolute;opacity:0;height:100%;top:0;cursor:pointer}

Keep in mind that different browsers may display this differently. You can see a demo here: http://jsfiddle.net/LvsYc/3138/

Answer №2

Follow these steps to achieve it:

DEMO

CSS

#imageInput { display:none;}

Javascript

$("#Picture").on('click', function() {$("#imageInput").trigger('click')})

Answer №3

To conceal the input control, you can follow these steps:

<input type='file' id="imgInp" accept="image/*" hidden="hidden" />

Next, style the image to have a link-like cursor using CSS:

#Picture {
    width: 120px;
    height: 120px;
    cursor: pointer;
}

Lastly, add an event listener to the picture element to trigger a click on the hidden input control:

$("#Picture").click(function () {
    $("#imgInp").click();
});

http://jsfiddle.net/LvsYc/3138/

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

Is there a way for me to know when ng-options has completed updating the DOM?

I am currently working on integrating the jQuery multiselect plugin using a directive within my application. Here is the select element: <select multiple ng-model="data.partyIds" ng-options="party.id as party.name for party in parties ...

Implementing visibility toggles for objects in three.js using a graphical user interface

I am interested in controlling the visibility of objects in my scene through a button on a GUI. The following function currently hides/shows objects individually: g3white.traverse(function(child){child.visible = true;}); g3black.traverse(function(child){ ...

What are some clever ways to handle the transition of the display property?

While transitions for the display property may not work, I am exploring alternatives. I attempted using the visibility property but it didn't quite fit my needs. In my current setup, different text is displayed when hovering over an anchor tag by sett ...

Is there a way to showcase an epub format book using only HTML5, CSS, and jQuery?

Can ePub format books be displayed in a web browser using only HTML5, CSS, and jQuery? I would appreciate any suggestions on how to accomplish this. Additionally, it needs to be responsive so that it can work on iPad. While I am aware of this requirement, ...

XPaths are used to verify the accuracy and relevance of text content

Here's a snippet of HTML I need help with: HTML Code: <a id="pINumber" href="csf.ajax?et=p.preparationinsurance">PASS170XX</a> XPATH to identify the above element //*[@id="pINumber"] I am looking to create an XPATH that checks for the ...

Each time I refresh the page, the user data disappears and I have to login

Hello there, I am currently utilizing Express for backend authentication and these are the sign in functions/controllers implemented on the front end. export const signInUser = async credentials => { console.log('this is for the signInUser&apos ...

The split() function returns a string that remains unaltered and intact, without any

I am attempting to separate this string: 120,00 m² into two distinct parts like this: 120 m² This is the code I have been using: var test = jQuery('#wpsight-listing-details-3 .span4:nth-child(4) .listing-details-value').html(); var pa ...

Using JQUERY to toggle classes conditionally

$('.showall').css("cursor","pointer").click(function() { $('.value-container').toggle(); $('.dim-header').toggleClass($('.dim-header').toggleClass() == 'dim-header' ? 'dim-header active' : & ...

Uncover information by utilizing Scrapy to scrape data from websites with infinite scrolling via

Currently, I am a novice in both python and scrapy. I am seeking assistance as I aim to extract a product listing from a website. However, the site has a "view more" products feature at the end which triggers an ajax request for text/html, loading another ...

Confirm the validity of decimal numbers with a precision of up to x digits beyond the decimal

Seeking to develop a Regular Expression Validation that satisfies the following criteria: a) Decimal numbers with up to 3 decimal places greater than zero b) Positive or negative non-zero numbers with up to 3 decimal places The mentioned items prefixed ...

The Express.js application functions properly on a local environment, but encounters issues when deployed on Heroku

Currently, I am experiencing an issue with deploying a music visualizer that I created. It seems to work perfectly in all scenarios except when I click on a song to play from the search bar, where I keep encountering a '503 (Service Unavailable)' ...

Challenges Arising from Using Django ORM with AJAX

Hey there! I need some help with Django ORM and ajax requests related to the select_related function. Let me explain what I'm trying to do. I have a query like this: prod_serv = Product_service.objects.select_related() This query involves joining 3 ...

Can jQuery be used to change the functionality of a submit button, such as toggling between show, hide, and submit options?

I am having trouble toggling a button to either submit a form on click or reveal an input field, depending on whether the user clicks outside the input field to hide/collapse it. The issue arises when the user dismisses the input field and the submit butto ...

What causes a modal dialog box to load with a single button click, even if there are multiple identical buttons present? How can this issue be resolved?

I have implemented a Datatables table within a view that contains buttons triggering a modal dialog. The buttons are only visible when a certain condition is met (specifically, when the image path is not null), and this conditional logic resides within the ...

How can I retrieve the offset top of a td element in relation to its parent tr element?

Here is some sample dummy HTML code: <table> <body> <tr> <td id="cell" style="height: 1000px; width: 200px;"></td> </tr> </body> </table> I am looking to attach a click event ...

Error message "After the upgrade to Angular 15, the property 'selectedIndex' is not recognized in the type 'AppComponent'."

My Ionic 6 app with capacitor has been updated in the package.json file. These are the changes: "dependencies": { "@angular/common": "^15.1.0", "@angular/core": "^15.1.0", "@angular/forms": "^15.1.0", "@angular/platform-browser": "^15.1. ...

Issue with error handling in Node and MongoDB when using Express, Mongoose, and the 'mongoose-unique-validator' plugin

I am facing an issue with the 'mongoose-unique-validator' plugin when trying to handle Mongo ValidationError in my custom error handler. Despite other errors being handled correctly, this specific one is not triggering the desired response from m ...

What is the best way to interpret a line break within a string variable in TypeScript?

Realtime Data base contains data with \n to indicate a new paragraph. However, when this data is retrieved and stored in a String variable, the website fails to interpret the \n as a paragraph break: https://i.stack.imgur.com/tKcjf.png This is ...

Tips for accessing a variable through request.query

When I made a call to getContents() in my client-side code: $.getJSon("/getContents", function(room){ theRoom=$("#roomName").val();//textarea's value ... }); I am now trying to figure out how to retrieve theRoom variable in getContents(), which is ...

Tips on restricting dates to be equal to or earlier:

I have written a code to determine if two given dates are equal or not. The code should allow for the current date to be smaller than or equal to the provided date, but it should not allow for it to be greater. var date = '10-11-2015'; var toda ...