Hassan Baig
Hassan Baig

Reputation: 15844

Using JQuery to run loading animation (error handling)

JQuery (JS) beginner here. I am creating a simple loading animation for a file upload form via JQuery. The objective is to show the animation once an Upload button is pressed and a file was chosen by the user. In case no file was chosen and solely Upload was pressed, do nothing.

Currently, relevant parts of my code are:

$(document).ready(function() {
 if ($('#p2').change(function())){
       if ($("#Btn2").bind("click", function(event))){
           $("#loader2").show();
           $("#spinner2").show();
           $("#Btn2").hide();
       }
   }
});

Looks straight forward enough but doesn't work (nothing happens). Perhaps I'm making a rookie mistake. Can someone help rectify this? Ask me for more code in case needed.

Upvotes: 1

Views: 33

Answers (2)

shahz
shahz

Reputation: 608

I would recommend using the following jQuery code which is shorter and simpler to understand for a beginner such as yourself.

$(document).ready(function() {
 $('#p1').change(function(){
        $('#Btn1').bind("click", function(event){
            $("#loader1").show();
            $("#spinner1").show();
            $("#Btn1").hide();
        })
    })

Not only is this code easier to understand for a beginner but it actually gets the job done i.e. you upload a file, click on the upload button and your loading animation will run and once the file is uploaded your animation will stop running and the upload button will disappear.

Upvotes: 1

guest271314
guest271314

Reputation: 1

Remove if, un-nest click event handler from within change event handler. At click at #Btn1 element check #p1 .files .length to determine if user has uploaded file objects

$(document).ready(function() {
  $("#p1").change(function(event) {
    // do stuff with files
  });
  $("#Btn1").on("click", function(event) {
    if ($("#p1")[0].files.length) {
      // user has upload files
      $("#loader1").show();
      $("#spinner1").show();
      $("#Btn1").hide();
    }
  })
});
#loader1,
#spinner1 {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<form>
  <input type="file" id="p1">
  <input type="button" value="upload" id="Btn1">
</form>
<div id="loader1">uploading</div>
<div id="spinner1">spinner</div>

Upvotes: 2

Related Questions