Search

JQuery click event not Working Issue Solved

post-title

JQuery is simple Javascript which makes Javascript event and animation easy and fast. But sometimes it makes harder when attaching event with element, mostly click events.

Sometimes when everything is right, your code is correct, you have also loaded JQuery libraby before. stil click event not work. No errors shows in console. It happens with almost every new developer when initially working with JQuery.

For example, if you dynamically create elements with the class name class-name you need to bind the event to a parent which already exists. This is called event delegation and works as followed. The event should be attached to a static parent element that should be already exist when page loaded, for example document, body or your wrapper.

This is how to handle event in that cases.

$(document).on(eventName, selector, function() {
    // script to be run on event...
});

For example, if you want to add click event on btn class which was added after page loaded.

$(document).on('click', '.btn', function() {
    // do something here
});

or 

$('body').on('click', '.btn', function() {
    // do something here
});

I hope it will help you.