I have a simple image uploader with a ‘browse files’ button in the middle. I’m trying to hide this upload button once images have been selected so I can display the image thumbnails without the upload button crowding everything.
Here is what I have but it’s not working and i’m not sure what i’m missing (or if there’s a better way to do this altogether. I am open to a whole other method of doing this if there’s a better way, I just tried this because it seemed like a simple thing that should have done what I needed if I didn’t make a mistake. Any suggestions?
$(document).ready(function(){
if($('#thumbnail').length){
$('#submit').hide();}
});
I need this to always be "listening" for the images to show up because it could happen at any time. If it maters, this snippet is inside of a .js file…I wasn;t sure if that was my mistake or if that should have no effect on this. Ideally I’ll have an X on each image to remove the thumbnails and if all the images are removed then the upload button will appear again. I have no idea if what i’m attempting will do that as it is, or if I have to add a second bit to show it again.
Any help is appreciated. Thank you.
2
Answers
Edit:
As @Ruan Mendes pointed out in comment, it’d be much easier to hide the button in the same piece of code that load the image. But if you don’t have control over that code, MutationObserver is the only choice.
Also check this answer for tips about performance if your page is very large/complex.
You can use MutationObserver to monitor changes in HTML.
Start with a function that shows or hides the button depending on how many thumbnail images are visible…
Then you will need two event handler functions. One that fires when a thumbnail image loads, and another when it is removed. Both will call the toggleUploadButton function above.