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>

How to detect when element is visible on screen with Javascript

When user comes to the page you may want to show them animation and if element is in the bottom of page, you need to wait untill element is visible on screen to run your animation. With this ready to use function you can add this functionality all elements on screen. Also i have a youtube video that explains how i wrote this function.

Ready to use full JS code

function gc_detect_visibility(query,custom_funtion){

    let calculator = function(query,custom_funtion){
        
        let element = document.querySelector(query);

        let element_top_offset = element.offsetTop;
        let element_bottom_offset = element.offsetHeight + element_top_offset;

        let screen_top_offset = window.scrollY;
        let screen_bottom_offset = screen_top_offset + window.innerHeight;

        if(element_top_offset > screen_top_offset && screen_bottom_offset > element_bottom_offset){
            custom_funtion(element);
        }
    } 

    calculator(query,custom_funtion);

    document.addEventListener('scroll',calculator.bind(null,query,custom_funtion));
}

Example usage

<!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>Detect Visibility</title>
</head>

<body>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box" id="element"></div>
    <div class="box"></div>
    <div class="box"></div>
    <style>
        .box {
            width: 250px;
            height: 250px;
            background-color: blue;
            margin-bottom: 20px;
        }

        #element {
            background-color: red;
        }
    </style>
    <script>
        function gc_detect_visibility(query,custom_funtion){

            let calculator = function(query,custom_funtion){
                
                let element = document.querySelector(query);

                let element_top_offset = element.offsetTop;
                let element_bottom_offset = element.offsetHeight + element_top_offset;

                let screen_top_offset = window.scrollY;
                let screen_bottom_offset = screen_top_offset + window.innerHeight;

                if(element_top_offset > screen_top_offset && screen_bottom_offset > element_bottom_offset){
                    custom_funtion(element);
                }
            } 

            calculator(query,custom_funtion);

            document.addEventListener('scroll',calculator.bind(null,query,custom_funtion));
        }

        gc_detect_visibility('#element',function(element){
            console.log('element is visible');
        });

    </script>

</body>

</html>

Js detect element when visible on viewport

To do that as you can see in the video and the code i share with you above. We need to calculate if element is visible on screen by finding element top offset and screen top offset. If element top offset is higer than screen top offset and if element bottom offset is lower than screen bottom offset it makes element is visible on screen.

                let element_top_offset = element.offsetTop;
                let element_bottom_offset = element.offsetHeight + element_top_offset;

                let screen_top_offset = window.scrollY;
                let screen_bottom_offset = screen_top_offset + window.innerHeight;

                if(element_top_offset > screen_top_offset && screen_bottom_offset > element_bottom_offset){
                    custom_funtion(element);
                }

In the this part of the code we gave this functionality to the function.

Also we need to add this function into the scroll event also we need to add any element query selector into it. That is why we create another function for that in the fist lines of the function.

We created “calculator” function to add this functionality to scroll event. That makes our code run every scroll behavior. Also we bind our custom function to run when element is visible on screen or viewport.

With this approach you can add any functionality to your code. Change the calculation based on your situation and solve your problem with that.

Javascript check if element is visible on screen – check viewport

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

Check if element is visible in viewport using javascript library in javascript and add scroll event to detect when element is in screen:

Video and new version of this writing is here : https://gokhancelebi.net/how-to-detect-when-element-is-visible-on-screen-with-javascript/

Ready to Use FULL Code

// detect when element gets visible on scroll
    window.addEventListener("scroll", detect_visibility);

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

    function detect_visibility() {

        var element = document.getElementById("element");

        var top_of_element = element.offsetTop;
        var bottom_of_element = element.offsetTop + element.offsetHeight + element.style.marginTop;
        var bottom_of_screen = window.scrollY + window.innerHeight;
        var top_of_screen = window.scrollY;

        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
            alert("element is visible")
        } else {
            // the element is not visible, do something else
            alert("element is not visible")
        }

    }

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.

If you want to check if div is visible on screen use “getElemgetElementsByClassName()” or “getElementById” for div class or id

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

Element Top Offset

   var top_of_element = element.offsetTop;

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.offsetTop + element.offsetHeight + element.style.marginTop;

In this line of code we get bottom offset of element

Window Bottom Offset and Top Offset

var bottom_of_screen = window.scrollY + window.innerHeight;
var top_of_screen = window.scrollY;

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
      alert("element is visible")
} else {
      // the element is not visible, do something else
      alert("element is not visible")
 }

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
}

Javascript Süreli ve Süresiz Sayfa Yönlendirme Kodu

Javascript ile süreli ve süresiz yönlendirme kodlarını paylaştım.

  1. Süresiz Yönlendirme

[gcode]

<script type="text/javascript">

window.location = "http://www.google.com.tr/"

</script>

[/gcode]

2. Süreli Yönlendirme

3 saniye için 3000 değeri girildi kendinize göre düzenleyebilirsiniz.

[gcode]

<html>
<head>
<script type="text/javascript">

function bekle(){
    window.location = "http://www.google.com.tr"
}

</script>
</head>
<body onLoad="setTimeout('bekle()', 3000)">
<h2>Yönlendiriliyor!</h2>
<p>3 saniye için 3000 değeri girildi kendinize göre düzenleyebilirsiniz !</p>

</body>
</html>

[/gcode]