"Looking for a quicker way to upload images without the hassle of a long input field? Learn how to use a glyphicon

Is there a way to use a symbol or glyphicon for uploading an image instead of having to use such a long input field? (Specifically for uploading a profile picture)

I'd like the ability to click on the glyphicon and choose an image from my computer. The current fiddle provided allows for choosing an image, but it requires the use of a lengthy input field.

My goal is to display the glyphicon when hovering over a mouse icon, which in turn hovers over a background image. How can this be achieved?

Below is the code I am currently using:

HTML:-

<input type='file' />
<img id="myImg" src="#" alt="your image" />

JS Code:

$(function () {
$(":file").change(function () {
    if (this.files && this.files[0]) {
        var reader = new FileReader();
        reader.onload = imageIsLoaded;
        reader.readAsDataURL(this.files[0]);
    }
});
});

function imageIsLoaded(e) {
    $('#myImg').attr('src', e.target.result);
};

Any suggestions would be greatly appreciated. [1]: http://jsfiddle.net/vacidesign/ja0tyj0f/

Answer №1

To customize a label to display an image and conceal the default upload button, you can follow these steps: That was the very first picture I came across and simply utilized it.

$(document).ready(function() {
  $(":file").change(function() {
    if (this.files && this.files[0]) {
      var reader = new FileReader();
      reader.onload = loadSelectedImage;
      reader.readAsDataURL(this.files[0]);
    }
  });
});

function loadSelectedImage(e) {
  $('#myImg').attr('src', e.target.result);
};
input[type="file"] {
  visibility: hidden;
  height: 0;
  width: 0;
}

input[type="file"]+label {
  display: inline-block;
  margin-right: 20px;
  height: 30px;
  width: 30px;
  background: url("//www.example.com/image.jpg") no-repeat;
  background-size: cover;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="imgUpload" type='file' />
<label for="imgUpload"></label>
<img id="myImg" src="#" alt="your image" />

Answer №2

A JavaScript function that allows users to upload images and display them on a webpage using jQuery.

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

Arrange elements in a vertical flow based on the height of the container

I am attempting to alter the direction of Elements to be vertical. Here is an example: By default, HTML elements are displayed horizontally like this:- #container { position: absolute; width: 400px; height: 200px; border: 1px solid gree ...

Is there a way to customize the scrollbar color based on the user's preference?

Instead of hardcoding the scrollbar color to red, I want to change it based on a color variable provided by the user. I believe there are two possible solutions to this issue: Is it possible to assign a variable to line 15 instead of a specific color lik ...

Having trouble getting a NodeJS sample app to start up because it can't locate the 'config' file?

I am currently delving into the world of Node.js and have been attempting to launch a sample application that I recently acquired from a git repository: https://github.com/madhums/node-express-mongoose-demo Despite diligently following all the provided i ...

Refresh Layers in Openlayers with LayerRedraw(), Rotate Features, and Manipulate Linestring Coordinates

TLDR: I am facing difficulties with my OpenLayers map. Specifically, I want to remove and add a layer called 'track', or find a way to plot a triangle based on one set of coordinates and a heading (see below). In my OpenLayers map, there is an i ...

What if a website refuses to be embedded in an <IFrame>? Is there a workaround to still embed it?

I'm trying to include a 'www.youtube.com' video using the IFrame tag in HTML, but unfortunately it's not allowing me to embed it. Is there a workaround or different method I can use to achieve this? ...

Executing two AJAX requests simultaneously with Django, AJAX, and jQuery in a single event

I believe I'm on the right track to getting this to work, but I could really use some assistance with the JQuery aspect. It seems that everything functions as expected after the second click onwards, but there is an issue with the functionality on the ...

I can't seem to find jquery, tether, and popper in npm bootstrap 4.0.0-beta.2. Where did

It's interesting that the javascript has been removed from the beta 2 version of Bootstrap 4. What could be the reason behind this decision? Isn't Bootstrap 4 dependent on jquery.js, tether.js, and popper.js? ...

Establishing a connection between JavaScript and MySQL within an HTML document

Recently, I started using node.js's node-mysql driver for MySQL and decided to write this piece of code: var mysql = require("mysql"); var connection = mysql.createConnection({ host : "localhost", user : "root", ...

Extracting and retrieving information from a complex data structure obtained through an API call

Struggling with this one. Can't seem to locate a similar situation after searching extensively... My goal is to determine the author of each collection associated with a user. I wrote a function to fetch data from an API for a specific user, in this ...

Implementing Jquery tabs into the code causes the vertical auto-scroll to smoothly glide beyond anchor points

I recently implemented a smooth autoscroll feature on my webpage using the CSS-Tricks code found here: http://css-tricks.com/snippets/jquery/smooth-scrolling/ Everything was working perfectly until I added jQuery tabs to display some of the content. Now, ...

Whenever I attempt to incorporate the 'var' keyword within a for loop alongside setTimeOut, I encounter unusual output

Here's the code snippet I'm working with: for (var i = 1; i <= 5; i++) { setTimeout(function () { console.log(i); }, 1000); } I'm confused about the output of this code. When I run it, I see the number 6 printed in the c ...

Optimizing web layouts to fit on a single page is the most effective

Struggling to create a print layout for my web page that seamlessly transitions from the digital realm to the physical world. Utilizing HTML and CSS has presented challenges in aligning the "digital" design with a "real printable" page due to uncertainties ...

Utilizing CSS to Display a Variety of Colors within a Text String

Is it possible to style different words in a sentence with various colors using only CSS, without using the span element? For instance, how can I make the word "Red" appear in red, "Blue" in blue, and "Green" in green within an h1 tag? ...

Error encountered when attempting to insert data into database due to incompatible data types

I am experiencing an issue with Vue multiselect. I am trying to save the id of selected options in a database, but it seems that I am encountering an error related to Array to string conversion. I have declared both site_id and administrator in fillables. ...

Using Vue.js: Passing an object from data() to a mounted() function

I'm facing an issue while attempting to pass the grid array to the createGridChart. An error message stating "grid is not defined" keeps popping up: “grid is not defined”. export default { data() { return { grid: [], } ...

Issue with MethodOverride PUT functionality

I am currently utilizing Node.js, Express, and MethodOverride in an attempt to update only one part of my user model using a form. User Model: var userSchema = new mongoose.Schema({ email: { type: String, unique: true, lowercase: true }, password: Str ...

Is there a way to trigger an alert once the google map has finished loading?

Is there a method to trigger a function once the Google map has finished loading? My website contains a Google map accessible through this link. The Google map on my site is powered by the Google API using the following URL: http://maps.googleapis.com/map ...

Having trouble resetting a checked checkbox label in Vuejs?

uncheck: function(checkedName) { this.checkedNames = this.checkedNames.filter(name => name !== checkedName); }, uncheckall: function(event) { this.checkedNames = []; }, checkedInput(event) { if (this.checkedNames.includes(event.targ ...

Failed verification of C-Lang in React-Hardware/Particle

Currently, I am utilizing React, React Hardware ([https://github.com/iamdustan/react-hardware/]), and Johnny-Five along with the Particle Photon. The error stack displayed below is what pops up when executing my lib/app.js file: # Fatal error in ../deps/v ...

Issue with jQuery mouseenter() function not meeting expectations

My goal is to create a div that changes its size when hovered over (using the mouseenter and mouseleave jQuery functions) and shows another div when clicked. However, I am experiencing inconsistent behavior with my jQuery code. Here is the code I am using: ...