Reputation: 657
I am building a fairly simple app using Symfony 4. I currently have Symfony loading Jquery and bootstrap and want to start to build my own triggers. So I've started to add my own bit of JS. Within this JS I need to detect if a certain button is clicked so my instinct is to use jQuery's on click function.
I am having real trouble getting this working. My additional code is being compiled by Webpack (via encore) but at no point does my event trigger, no matter what element I put it on. As far as I can see my additional Javascript functionality never gets called at all.
Any help appreciated. I'm by no means an ES6 expert so I may have something VERY wrong here.
assets/js/app.js
import '../css/app.scss';
import $ from 'jquery';
import 'bootstrap';
import './checkLoan'; ## This is my file
app/js/checkLoan.js
export default function() {
console.log('i got loaded');
$('#my-button').click(function (event) {
event.preventDefault();
console.log('I got clicked')
});
};
Upvotes: 0
Views: 343
Reputation: 1108
Hey your click listener is never triggered because you import it but you never call the function.
You could create your listener functions in a separate file like listener.js :
export default {
clickListener(){
console.log('i got loaded');
$('#my-button').click(function (event) {
event.preventDefault();
console.log('I got clicked')
});
}
};
And the trigger the functions in your main app.js once the page has finished loading :
import $ from 'jquery';
import listeners from "./listeners"
$(document).ready(function () {
listeners.clickListener();
...
});
EDIT: Also make sure the webpack.config.js file at the root of your project has the following line uncommented
.autoProvidejQuery()
Upvotes: 1