JQuery click event not Working Issue Solved

  234 views   5 months ago jQuery

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.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]