JQuery on click for dynamically added elements – why it is not working?

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>

JQuery detect when element is visible on screen – viewport

Whay we made in this code ? Line by line js code?

Check if element is visible in viewport using jquery library in javascript :

Ready to Use FULL Code

function detect_visibility(){
    
    var top_of_element = $(".element").offset().top;
    var bottom_of_element = $(".element").offset().top + $(".element").outerHeight();
    var bottom_of_screen = $(window).scrollTop() + $(window).innerHeight();
    var top_of_screen = $(window).scrollTop();

    if ((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
       // Element is visible write your codes here
       // You can add animation or other codes here
    } else {
        // the element is not visible, do something else
    }

}

// detect when element gets visible on scroll
$(window).scroll(function() {
    detect_visibility();
});

// detect when screen opens for first time
detect_visibility();

detect_visibility ()

With this function i wrote you above you can detect if element inside secreen viewport. It calculates based on offset and element height. You can use this to implement lazyload or animations.

You can add animaton classes in the // Element is visible section of detect_visibility function

Element Top Offset

var top_of_element = $(".element").offset().top;

In this line of code we get offset of element that we want to know if it is visibile.

Element Bottom Offset

var bottom_of_element = $(".element").offset().top + $(".element").outerHeight();

In this line of code we get bottom offset of element

Window Bottom Offset and Top Offset

var bottom_of_screen = $(window).scrollTop() + $(window).innerHeight();
var top_of_screen = $(window).scrollTop();

In the first line we get window screen’s bottom offset

In the second line we get windows screen’s top offset

Final : Calculate to detect if element is visible and shown on screen of user

if ((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
   // Element is visible write your codes here
   // You can add animation or other codes here
} else {
   // the element is not visible, do something else
}