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.
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.
Share Improve this question edited Apr 23, 2018 at 19:35 Amin Shah Gilani asked Apr 23, 2018 at 19:20 Amin Shah GilaniAmin Shah Gilani 9,8967 gold badges44 silver badges85 bronze badges 5- 3 Why are you mixing jQuery and vanilla JS? – Andy Commented Apr 23, 2018 at 19:24
- 3 onclick, not onClick – paul Commented Apr 23, 2018 at 19:24
- Shouldn't it be $(document).ready()=> { on that first line there? looks like you got a syntax error with that extra "(" – Nancy Commented Apr 23, 2018 at 19:29
-
2
@Rexa nope,
.ready()
accepts a callback. See: learn.jquery./using-jquery-core/document-ready – Amin Shah Gilani Commented Apr 23, 2018 at 19:33 - @amingilani Ah, oops! I get it now! – Nancy Commented Apr 23, 2018 at 19:35
2 Answers
Reset to default 6You 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');
}
});