Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
100
rated 0 times [  103] [ 3]  / answers: 1 / hits: 5246  / 11 Years ago, fri, december 20, 2013, 12:00:00

I've got an MVC app that uses a DevExpress gridview for displaying data. The reason I mention this is because after updating a record, I am trying to display a <div> with a message in it and have it either close (hide) after 3 seconds, or close when the user either clicks on it, or clicks on anything else on the page. I've read a ton of articles on SO about how to close and open elements with jQuery or Javascript but I am having difficulty with it.



Here's my fiddle, which gets me about 3/4 the way there....the div opens when the button is clicked (simulates the 'Update' part of the DevExpress grid), and if you click on the message, it closes. What I can't figure out is how to make it auto-close after 3 seconds. I did try to use the .delay(), like so $('#msg').delay(3000).toggle(500); but it appears that .delay() actually stops all other UI events until the duration is over. The side effects to this is that if the user clicks on any other part of the document, it doesn't respond until the delay duration is over....so the delay duration closes the div but then the 'click' event of the document fires and displays the div (hope that makes sense).



In short, I'm trying to auto-display a div on a postback (button click) and then either auto-close it after 3 seconds, or close it when the user clicks on it, or any other element in the document.



Any advice/guidance is appreciated!


More From » jquery

 Answers
3

Use a timer with setTimeout()



$(document).ready(function ($) {
$(.messageInTab).click(function () {
$(this).hide(500);
clearTimeout(timer)
});

var timer;
$(button).click(function (e) {
$('#msg').show(500);
timer = setTimeout(function () {
$('#msg').hide(500);
}, 3000);
});
});


Demo: Fiddle



Update: It won't hide if you click anywhere in the page when the message is displayed, so try



$(document).ready(function ($) {
var $msg = $('#msg');
$(document).click(function () {
if ($msg.is(':visible')) {
$msg.hide(500);
clearTimeout(timer);
}
});

var timer;
$(button).click(function (e) {
e.stopPropagation();
if ($msg.is(':hidden')) {
timer = setTimeout(function () {
$('#msg').hide(500);
}, 3000);
}
$msg.toggle(500);
});
});


Demo: Fiddle


[#49358] Thursday, December 19, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
laytonlamontm

Total Points: 745
Total Questions: 130
Total Answers: 130

Location: Cambodia
Member since Thu, Oct 7, 2021
3 Years ago
;