Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change div background based on file chooser choice

I'm looking for a way to have a div background image change when the user chooses an image from a form input. As you can see below I have a input type of file. Once the user chooses the file they want I would like the div#imgHolder to change the background based on the file chosen. Any thoughts?

<div id="simpleDialog" style="width: 350px; height: 350px; display:none;" scrolltop="0">
  <br>  
  <div id="imgHolder" style="width:200px;height:200px;background-image: url(images/gray.png)"></div>
  <br>
  <form id="userForm" align="center">
    <fieldset>
      <legend>Artist Info</legend>
        <input type="file" name="artistImage" id="artistImage" style="border: none;float:left"><br><br>
        <label for="text" style="float:left">Enter URL:</label>
        <input type="text" name="website" id="website" value="" required="required">                
      </fieldset>
  </form>
  <input type="button" id="submit" value="Submit" /> 
  <input type="button" id="cancel" value="Cancel" /> 
</div>
like image 628
Matthew Lancaster Avatar asked Jun 13 '12 04:06

Matthew Lancaster


1 Answers

Since you tagged this html5, you understand that this is an advanced browser-feature.

What you're asking for will require the FileReader, available in most all modern browsers (even IE).

// Bind to the change event of our file input
$("input[name='myFileSelect']").on("change", function(){

    // Get a reference to the fileList
    var files = !!this.files ? this.files : [];

    // If no files were selected, or no FileReader support, return
    if ( !files.length || !window.FileReader ) return;

    // Only proceed if the selected file is an image
    if ( /^image/.test( files[0].type ) ) {

        // Create a new instance of the FileReader
        var reader = new FileReader();

        // Read the local file as a DataURL
        reader.readAsDataURL( files[0] );

        // When loaded, set image data as background of page
        reader.onloadend = function(){

            $("html").css("background-image", "url(" + this.result + ")");

        }

    }

});​

I just tested the above code in Internet Explorer 10, Chrome 19/21, Firefox 12/13, and Opera 11.64 and found that it worked with no problems.

Older browsers, which don't support the FileReader, will just remain silent. No images shown, no exceptions raised.

Fiddle: http://jsfiddle.net/jonathansampson/K3A9r/

like image 138
Sampson Avatar answered Sep 23 '22 10:09

Sampson