Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call js function after div is loaded

Tags:

I have a div element which is loaded after a click on a radio button.

Need to hide a part of the div after it is loaded.

$(function($) {
  $('.div_element').on('load', function() {
    $('.textbox').hide();
  });
});

The above code doesn't work. I need to trigger a function after the div is shown on the page.

like image 760
phpblogger Avatar asked Jun 21 '18 05:06

phpblogger


People also ask

How do you call a function after DOM is loaded?

Use DOMContentLoaded event callback You can use the DOMContentLoaded event as the trigger for executing your code. Do this by using document. addEventListener() to tie a custom function to the event. This example shows you how to define a custom function that will execute only after the DOM is loaded.

How do you call a function when HTML is loaded?

The first approach for calling a function on the page load is the use an onload event inside the HTML <body> tag. As you know, the HTML body contains the entire content of the web page, and when all HTML body loads on the web browser, it will call the function from the JavaScript.


2 Answers

Here is how I would go about it. This is using vanilla JavaScript but it can easily be adapted to use jQuery.

The idea is to use Mutation Observers. I hope it helps.

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>DOM MUTATION OBSERVERS</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
    <form name="radios">
        <input type="radio" name="gender" value="male" id="maleRadio" checked> Male
        <br>
        <input type="radio" name="gender" value="female" id="femaleRadio"> Female
        <br>
        <input type="radio" name="gender" value="other" id="otherRadio"> Other
    </form>

    <!-- This div will be displayed when the radio button whose value is female is clicked. -->
    <div id="femaleDiv" style="display: none">
        <p>The textbox should be below...</p>
        <input type="text" id="textToHide">
    </div>

    <script>
        // After the document loads...
        document.onload = function () {
            // Attach an onclick listener to the radio buttons.
            var radios = document.forms["radios"].elements["gender"];
            for (var i = 0, max = radios.length; i < max; i++) {
                radios[i].onclick = function (event) {
                    var radio = event.target || event.srcElement;
                    console.log(radio.name);
                    if (radio.value === "female") {
                        document.getElementById("female").style.display = "block"
                    }
                }
            }

            // Get the div whose change in attributes we are interested in.
            var targetNode = document.getElementById("femaleDiv");

            // Set the mutation observer to only listen to attribute mutations
            var config = { attributes: true };

            // This will be called when a mutation has been observed
            var callback = function(mutationsList) {
                for (var mutation of mutationsList) {
                    if (mutation.type == "attributes") {
                        console.log(mutation);
                        console.log('The ' + mutation.attributeName + ' attribute was modified.');
                        if (targetNode.style.display == "block") {
                            document.getElementById("textToHide").style.display = "none";
                        }
                    }
                }
            };

            // Create the observer
            var observer = new MutationObserver(callback);

            // Start observing
            observer.observe(targetNode, config);

            // Uncomment this to stop observing at at the right place.
            // observer.disconnect();
        } ();
    </script>
</body>

</html>
like image 175
Floyd Kots Avatar answered Oct 05 '22 11:10

Floyd Kots


Although it may not be good solution but you can check in an interval if the div exist, if it is then you can do further:

$(() => {
  const checkDiv = setInterval(() => {
    if($('.div_element').length > 0) {    // it's better to use id instead of the class as selector
      clearInterval(checkDiv);
      // more action here
    } 
  }, 100); // check after 100ms every time
});
like image 42
Rohit Sharma Avatar answered Oct 05 '22 12:10

Rohit Sharma