'Hiding a div with JQuery

My div is inside a user control, it shows a "successful" message after a gridview update. I don't want that div to be persistent and want to hide it after a few seconds without refreshing the page. Here is my code:

<div id="MsgInfo" runat="server"  class="divMsg" visible="false" /></div>

In my usercontrol I added the link to the script file:

<script type="text/javascript" src="../HideMsg.js"></script>

The script:

$(function () {
    setTimeout(function () { 
       $("#MsgInfo").fadeOut(1500); 
    }, 
    5000);
});

I don't know what is missing there but the message can't fade out or disappear.

I went through a lot of similar question and solution but still can't hide the div with Jquery.



Solution 1:[1]

Check this working example: codepen

Inside update click you need to use setTimeout

$("#showDiv").click(function () {
   $("#MsgInfo").fadeIn(1500);

   setTimeout(function () {
     $("#MsgInfo").fadeOut(1500);
   }, 5000);
});

CSS:

#MsgInfo {
  display: none
}

Solution 2:[2]

Use class name instead of id. The reason is you are using asp.net control GridvView with runat server. So it will have updated value for id (try inspecting element on browser and check id). So, instead of using id selector try using class selector. Try like below.

$(function () {
    setTimeout(function () { $(".divMsg").fadeOut(1500); }, 5000);
});

You can also refer this answer here : Getting ID from asp.net runat server in jQuery

Solution 3:[3]

If #MsgInfo div comes after page load then try to add script inside #MsgInfo div.

 <script>   
 const myTimeout = setTimeout(myMsgInfo, 5000);
    
    function myMsgInfo() {
      var x = document.getElementById("MsgInfo");
      x.style.display = "none";
    }
 </script>  

Solution 4:[4]

The problem is in your div closing tag use <div>..</div> not <div/>...</div>

$(function () {
setTimeout(function () { $("#MsgInfo").fadeOut(1500); }, 5000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="MsgInfo" runat="server"  class="divMsg" visible="false">It will hide after 5 seconds</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Usama
Solution 2
Solution 3 YAGNIK PADALIYA
Solution 4 Mateen