I have webpack on a vanilla HTML5 page in my Rails app.
I've got the onClick
handler defined in Webpack with:
$(document).ready(()=> {
document.getElementById('add-card').onClick = () => {
$('.ui.modal').modal('show');
}
});
The button renders on the page as:
<a class="ui button" id="add-card">Click me</a>
Clicking it does nothing. However, within the console, I can see that the handler is defined:
document.getElementById('add-card').onClick
ƒ () {
$('.ui.modal').modal('show');
}
And when I execute it with document.getElementById('add-card').onClick()
, it works perfectly!
How do I get my onClick handler to fire when the element is clicked?
Edit: For the picky observers, I have jQuery installed and configured properly through Webpack.
You are mixing vanilla js and jquery. You can either do
$(document).ready(()=> {
document.getElementById('add-card').addEventListener('click', () => {
$('.ui.modal').modal('show');
})
});
or you can do
$(document).ready(()=> {
$('#add-card').on('click', () => {
$('.ui.modal').modal('show');
});
});
When you do document.getElementById('add-card')
you get back a Node, not a jQuery object, so there is no onClick (although there is onclick, but it's better to use addEventListener). If you do $('#add-card')
you get back a jQuery object, so you can use jQuery methods on it.
Replace onClick
by onclick
:
$(document).ready(()=> {
document.getElementById('add-card').onclick = () => {
$('.ui.modal').modal('show');
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.