Home > Software design >  Hiding a div with JQuery
Hiding a div with JQuery

Time:04-28

Good Morning, I went through a lot of similar question and solution but still can't hide the 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"   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.

Your help is appreciated.

CodePudding user response:

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
}

CodePudding user response:

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

CodePudding user response:

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>  

CodePudding user response:

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"   visible="false">It will hide after 5 seconds</div>

  • Related