0

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')
    });
};

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

1 Comment

You are correct, I found that but I also found one other thing. In the webpack config I needed to ensure I had called ".autoProvidejQuery()" or import jquery in my separate function which really tripped me up for a while. Would you mind adding this to your solution, I'll tick it anyway but it would be nice to have all of these answers in one place.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.