Bootstrap Alert Auto Close - javascript

My need is to call alert when I click on Add to Wishlist button and should disappear the alert in 2 secs. This is how I tried, but the alert is disappearing instantly as soon as it is appearing. Not sure, where the bug is.. Can anyone help me out?
JS Script
$(document).ready (function(){
$("#success-alert").hide();
$("#myWish").click(function showAlert() {
$("#success-alert").alert();
window.setTimeout(function () {
$("#success-alert").alert('close');
}, 2000);
});
});
HTML Code:
<div class="product-options">
<a id="myWish" href="" class="btn btn-mini">Add to Wishlist </a>
Purchase
</div>
Alert Box:
<div class="alert alert-success" id="success-alert">
<button type="button" class="close" data-dismiss="alert">x</button>
<strong>Success!</strong>
Product have added to your wishlist.
</div>

For a smooth slide-up:-
$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert").slideUp(500);
});
$(document).ready(function() {
$("#success-alert").hide();
$("#myWish").click(function showAlert() {
$("#success-alert").fadeTo(2000, 500).slideUp(500, function() {
$("#success-alert").slideUp(500);
});
});
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div class="product-options">
<a id="myWish" href="javascript:;" class="btn btn-mini">Add to Wishlist </a>
Purchase
</div>
<div class="alert alert-success" id="success-alert">
<button type="button" class="close" data-dismiss="alert">x</button>
<strong>Success! </strong> Product have added to your wishlist.
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

Using a fadeTo() that is fading to an opacity of 500 in 2 seconds in "I Can Has Kittenz"'s code isn't readable to me. I think it's better using other options like a delay()
$(".alert").delay(4000).slideUp(200, function() {
$(this).alert('close');
});

Why all the other answers use slideUp is just beyond me. As I'm using the fade and in classes to have the alert fade away when closed (or after timeout), I don't want it to "slide up" and conflict with that.
Besides the slideUp method didn't even work. The alert itself didn't show at all. Here's what worked perfectly for me:
$(document).ready(function() {
// show the alert
setTimeout(function() {
$(".alert").alert('close');
}, 2000);
});

I found this to be a better solution
$(".alert-dismissible").fadeTo(2000, 500).slideUp(500, function(){
$(".alert-dismissible").alert('close');
});

one more solution for this
Automatically close or fade away the bootstrap alert message after 5 seconds:
This is the HTML code used to display the message:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="alert alert-danger">
This is an example message...
</div>
<script type="text/javascript">
$(document).ready(function () {
window.setTimeout(function() {
$(".alert").fadeTo(1000, 0).slideUp(1000, function(){
$(this).remove();
});
}, 5000);
});
</script>
It's not limited to showing the message through JS, the message could already be displayed when the page loads.

I know this thread is old, but I just thought I would add my script for Bootstrap 5, incase anyone else needs it
<script>
setTimeout(function() {
bootstrap.Alert.getOrCreateInstance(document.querySelector(".alert")).close();
}, 3000)
</script>

Html:
<div class="alert alert-info alert-dismissible fade show js-alert" role="alert">
Javascript:
if (document.querySelector('.js-alert')) {
document.querySelectorAll('.js-alert').forEach(function($el) {
setTimeout(() => {
$el.classList.remove('show');
}, 2000);
});
}

$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
$("#success-alert").alert('close');
});
Where fadeTo parameters are fadeTo(speed, opacity)

This is a good approach to show animation in and out using jQuery
$(document).ready(function() {
// show the alert
$(".alert").first().hide().slideDown(500).delay(4000).slideUp(500, function () {
$(this).remove();
});
});

Tiggers automatically and manually when needed
$(function () {
TriggerAlertClose();
});
function TriggerAlertClose() {
window.setTimeout(function () {
$(".alert").fadeTo(1000, 0).slideUp(1000, function () {
$(this).remove();
});
}, 5000);
}

C# Controller:
var result = await _roleManager.CreateAsync(identityRole);
if (result.Succeeded == true)
TempData["roleCreateAlert"] = "Added record successfully";
Razor Page:
#if (TempData["roleCreateAlert"] != null)
{
<div class="alert alert-success">
×
<p>#TempData["roleCreateAlert"]</p>
</div>
}
Any Alert Auto Close:
<script type="text/javascript">
$(".alert").delay(5000).slideUp(200, function () {
$(this).alert('close');
});
</script>

This worked perfectly even though you clicked the button multiple times.
Here I created an onClick function to trigger the closeAlert function.
function closeAlert(){
const alert = document.getElementById('myalert')
alert.style.display = "block"
setTimeout(function(){
alert.style.display = "none"
}, 3000);
}

Related

Hide and show functionality not working

I am doing and show functionality I'm tried scenarios but it is not working, Please let me know what i did mistake.
My code :
function showButtons() {
$("#view").click(function(){
$("#allversion").show();
});
$("#view").click(function(){
$("#allversion").hide();
});
}
<div id="allversion" style="display:none">
SOME DISPLY CODE HERE
</div>
let me know the changes i need to made
<a onclick="showButtons()" id="view">View More</a>
Problem is that every time you call function showButtons that binds additional 2 click events every time (so clicking on link 2 times you will have 4 events in total). And your code shows and hides element at the same time.
You need to toggle it:
$(document).ready(function() {
$('#view').click(function() {
$('#allversion').slideToggle();
});
});
#allversion {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="view">View More</a>
<div id="allversion">VISIBLE!</div>
You don't need to call onclick="showButtons()" event for that. You can easily hide and show your section something like this:
$(document).ready(function(){
$("#view").click(function(){
$("#allversion").toggle();
});
});
I recommend you to use toggle method. The problem is that you have to use one single click event handler.
$("#view").click(function(e){
$("#allversion").toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="allversion" >
SOME DISPLY CODE HERE
</div>
<a id="view">View More</a>
You can use toggle as suggested by others or you can try this
$("#view").click(function(){
if($("#allversion").hasClass('show'))
{
$("#allversion").removeClass('show').addClass('hide');
}
else
{
$("#allversion").removeClass('hide').addClass('show');
}
change to the following code, it should work.
<a id="view">View More</a>
var isClicked = false;
$( "#view" ).click(function() {
if (isClicked == true) {
$("#allversion").css("display", "none");
isClicked = false;
}
else {
$("#allversion").css("display", "inline");
isClicked = true;
}
});
Also you can use .toggle() to switch the visibility.
<a id="view">View More</a>
$( "#view" ).click(function() {
$("#allversion").toggle();
});
As per your question "Why isn't my code working?".
If your code is exactly as is here as on your site, it's not working because the script is initializing before the DOM is loaded.
Move your script to the bottom of the page or put it in to a
$(document).ready(function(){
//Code goes here
});
This works with me.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
function showButtons() {
$("#allversion").toggle();
}
</script>
</head>
<body>
<div id="allversion" >
SOME DISPLY CODE HERE
</div>
<a onclick="showButtons()" id="view">View More</a>
</body>
</html>

How to Fade In a notification by clicking a text field

Hi guys I need help (again). I wanted to learn how to make the notification or alert box fade-in and fade-out after clicking a editable textbox.
This is the code for the alert box:
<div class="alert alert-warning fade in">
×
Alert: Please don't do this.
</div>
and this is the script for onClick:
function clicks() {
document.getElementById("notif").innerHTML = "Hello World";
}
</script>
I was thinking I will put the div alert box inside a condition or just a script with onClick function
Working example on CodePen: http://codepen.io/oculusriff/pen/aBoKvE
HTML
<div id="alert" class="alert alert-warning fade">
×
Alert: Please don't do this.
</div>
<textarea id="txt"></textarea>
JS
var textarea = document.getElementById('txt');
var alert = document.getElementById('alert');
txt.addEventListener('focus', function() {
alert.classList.add('in');
setTimeout(function() {
alert.classList.remove('in');
}, 2000);
});
txt.addEventListener('blur',function (){
alert.classList.remove('in')
});
I would recommend using CSS approach to the animation. i.e. on click add/remove a class and let css handle the animation.
However if you want to use a JavaScript solution , here is one that does not change your code much
var myclickHandler = function() {
// first show the alert
$('.alert').show().fadeTo(500, 1);
// Now set a timeout to hide it
window.setTimeout(function() {
$(".alert").fadeTo(500, 0).slideUp(500, function() {
$(this).hide();
});
}, 3000);
}
// start with the alert hidden
$('.alert').hide();
$('#myTextBox').on('click', myclickHandler)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="alert alert-warning fade in">
× Alert: Please don't do this.
</div>
<input id="myTextBox" type="text" value="Click here">

How to close a modal when clicking outside

I want to hide a div by clicking on the close link in it, or by clicking anywhere outside that div.
I am trying following code, it opens and close the div by clicking close link properly, but if I have problem to close it by clicking anywhere outside the div.
<div id="float_tabs">
<ul>
<li><?= Yii::t('app','Sign in'); ?></li>
<li>
<?= Yii::t('app','Create an account'); ?>
<button type="button" class="close" aria-hidden="true" id="open" onclick="$('.floating_box').toggle('.hide_sign_in_box');">×</button>
<script src="jquery-1.12.0.min.js">
$(document).ready(function () {
$('#close').hide()
});
$('#open').on('click', function () {
$('#float_tabs').show(500)
});
$(document).mouseup(function (e) {
var popup = $("#float_tabs");
if (!$('#open').is(e.target) && !popup.is(e.target) && popup.has(e.target).length == 0) {
popup.hide(500);
}
});
</script>
The problem is you can not have an external script and an inline script together. They need to be separate elements.
<script src="jquery-1.12.0.min.js">
$(document).ready(function () {
...
</script>
needs to be
<script src="jquery-1.12.0.min.js"></script>
<script>
$(document).ready(function () {
...
</script>

Div fading in and out

I need your help, I am working on a website where I want a div to delay for 2 seconds then fade in when another div is clicked, but when I want to click it again (to close it) I want it to fade out instantly. Any help?
If you can use Jquery, the following code will help you do it as i got what you want:
this is default css:
.invisElem{display:none}
and the jquery code:
$('body').on('click', '.boxbutton1', function(){
var counter = $(this).data('count');
if(counter == undefined){
counter = 0;
setTimeout(function() {
$('.gymtext').fadeIn(500)//fadeIn after 2 seconds(2000 ms)
}, 2000);
}
else if(counter == 0){
$('.gymtext').fadeOut(function(){
$('.gymtext').remove()
});//fadeout quickly then remove
}
})
i tried to write it down novice friendly if you needed help add comment
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div").fadeToggle(240);
});
});
</script>
<button>Click to fade DIV</button>
<div id="div" style="width:100px;height:100px;background-color:blue;"></div>
Html:
<div>Show div1 and hide div2</div>
<div id="div1">Div1</div>
<div id="div2">Div2</div>
Css:
#div2 {display:none;}
Jquery:
$('#btn').click(function(e){
$('#div1').fadeOut('slow', function(){
$('#div2').fadeIn('slow');
});
});

Problems with manipulating divs within simplemodal dialog popup - Further Edit

Ok, I'm having a major headache with simplemodal - I know I'm almost there, but can't get this to quite work right. I have a simplemodal dialog that has several dynamically created divs inside it, such as
<html>
<head>
<!-- Confirm CSS files -->
<link type='text/css' href='css/confirm.css' rel='stylesheet' media='screen' />
</head>
<body>
<div id='container'>
<h1>Test Page</h1>
<div id='content'>
<div id='confirm-dialog'>
Page Content Goes Here
</div>
<!-- modal content -->
<div id='confirm'>
<div class='header'><span>Header Text</span></div>
<div class='message'>
<div id='optionDiv0'><input type='radio' id='options' name='options' value='0' />Option0</div>
<div id='optionDiv1'><input type='radio' id='options' name='options' value='1' />Option1</div>
<div id='optionDiv2'><input type='radio' id='options' name='options' value='2' />Option2</div>
</div>
<div class='buttons'>
<div class='yes'>OK</div>
</div>
</div>
</div>
<!-- Load JavaScript files -->
<script type='text/javascript' src='scripts/jquery.js'></script>
<script type='text/javascript' src='scripts/jquery.simplemodal.js'></script>
<script type="text/javascript">
jQuery(function ($) {
$('#confirm-dialog input.confirm, #confirm-dialog a.confirm').click(function (e) {
e.preventDefault();
confirm("", function () {
for(var k = 0; k <= 3; k++) {
if(options[k].checked) {
var ele = document.getElementById("optionDiv" + k);
ele.style.display = "none;";
//alert("Stop Here");
}
}
});
});
});
function confirm(message, callback) {
$('#confirm').modal({
closeHTML: "<a href='#' title='Close' class='modal-close'>x</a>",
position: ["20%",],
overlayId: 'confirm-overlay',
containerId: 'confirm-container',
containerCss: {
height: 300,
width: 450,
backgroundColor: '#fff',
border: '3px solid #ccc'
},
onShow: function (dialog) {
var modal = this;
$('.message', dialog.data[0]).append(message);
// if the user clicks "yes"
$('.yes', dialog.data[0]).click(function () {
// call the callback
if ($.isFunction(callback)) {
callback.apply();
}
// close the dialog
modal.close(); // or $.modal.close();
});
}
});
}
</script>
</body>
</html>
In the click code, I'm trying to make it so when the user clicks on one of the radio buttons, then clicks 'OK', that item is no longer visible in the popup. If I follow that code with an alert("Stop here");(shown in the code above, commented out), then I can see the div disappear from the popup. But once I clear the alert box, (or if I comment it out so it never runs), the next time I activate the dialog, the div that I hid is re-appearing. How can I keep it hidden, so that it remains hidden the next time the dialog is activated, or is that possible? Thanks in advance.
FINAL EDIT: Found the solution for the dialog box reverting to its original state every time it opens. I pasted this in just above the jquery code, and it works like a charm:
<script> $.modal.defaults.persist = true; </script>
Found on this site in another thread, as part of a different question. Thanks for all who helped.
Your code still doesn't look complete to me, but as for your confirm function callback
confirm("", function(){
$('#confirm input[type=radio]').each(function(){
if($(this).is(':checked'))
$(this).parent().empty();
});
});
Like that?

Categories