Categories : Javascript , JQuery

Hi, in this writing i will be explaining you how to attach on click event for the dynamically created element to the html page.

Why i cant add on click event to the dynamically added element like static elements?

Because when you run javascript code in the page starts, jquery tries to find element you add event to it. But it cant find element because you will create element dynamically so you need to reconnect your element wity your function.

In this code below you make a click event listener to all of your page and when this event trigers it uses some kind of filter for the selector (id , class , element name) you passed as second paramater. And then it runs the function that you passed as third argument to this jquery event function.

In the end of the day you catch all click elements but runs just for your filtered element(s).

$(document).on('click','#element',function(){
    alert('Clicked')
});

Full Example

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Element Visibility</title>
</head>

<body>
    
    <script>
        $(function () {
            // add element to the page dynamically
            $('body').append('<button id="element">Button</button>');

            // add on click listener for element
            $(document).on('click','#element',function(){
                alert('Clicked')
            });
        });
    </script>
</body>

</html>

Leave a Reply

Your email address will not be published. Required fields are marked *