I'm trying to simulate a click on an input tag, through the click on an anchor
tag, this way I can hide the input and wrap an image inside the anchor tag.
This works using the jQuery trigger function, but I can't make it work with just "plain" Javascript:
jQuery version:
let fake = $('.fake')
fake.click(function(e) {
e.preventDefault();
$('#user_avatar').trigger('click');
})
#user_avatar { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" name="file_field" id="user_avatar">
<a href="#" class="fake">
<img src="https://fthmb.tqn.com/65lNzIRNfZY4xY02D17b1RcGvso=/960x0/filters:no_upscale()/kitten-looking-at-camera-521981437-57d840213df78c583374be3b.jpg" width="320" height="240">
</a>
The JavaScript version using new Event
and dispatchEvent
:
let fake = document.querySelector('.fake');
fake.addEventListener('click', function(e) {
e.preventDefault();
console.log('testing');
let clickEvent = new Event('click');
document.getElementById('user_avatar').dispatchEvent(clickEvent)
})
#user_avatar { display: none; }
<input type="file" name="file_field" id="user_avatar">
<a href="#" class="fake">
<img src="https://fthmb.tqn.com/65lNzIRNfZY4xY02D17b1RcGvso=/960x0/filters:no_upscale()/kitten-looking-at-camera-521981437-57d840213df78c583374be3b.jpg" width="320" height="240">
</a>
The console.log is rendered, but the event isn't being dispatched, what am I doing wrong?
Use:
document.getElementById('user_avatar').click();
Tested and it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With