Umair Jameel Umair Jameel - 4 months ago 21
jQuery Question

Use elements when DOM is fully loaded in html

I want my child elements of body tag to be used when document is fully loaded. like I have

<body>
Country: <br>
<div>
<datalist id="country"></datalist>
<input type="text" list="country" id="search" onmouseover = 'populate("country")'/>
</div>
</body>


In the input element, i am using onmouseover event to call javascript function. But I want that thing to be enabled when all element are fully loaded.

Up till now, I have seen online that there is an onload event that can be used in body tag to call any particular function. But I don't want to call any function on onload event, just want to make sure that onmouseover event of input element should fired when body is fully loaded.

Answer

You can use jQuery to listen on the window load event and then create your mouseover listener on the input whenever all media is fully loaded:

$(window).on("load", function() {
    $("#search").on("mouseover", function() {
        populate("country");
    });
});

Instead of window.load you could even use document.ready. The first will even wait until all other things, like images, are loaded. The last will only wait until the DOM is finished ...

// $(function() {}) is a shorthand for $(document).ready(function() {});
$(function() {
    $("#search").on("mouseover", function() {
        populate("country");
    });
});
Comments