How to show alert after click the button again? - javascript

I have an alert that is triggered by a button and this alert dissapear after 3 seconds.
How can I show that alert every time we click the button ? Currently it works only once.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="ex1">
<button id="alert-trigger" data-dismiss="alert" class="btnClick">
Trigger Alert
</button>
<div id="example" class="alert" role="alert"></div>
<script type="text/template" id="alert-template">
<p>
<span lang="da">Merhaba</span>,
hello,
<span lang="ja">Hallo</span>
</p>
</script>
<script type="text/javascript">
$(document).ready(function() {
window.setTimeout(function() {
$(".alert").fadeTo(1000, 0).slideUp(1000, function() {
$(this).remove();
});
}, 3000);
});
</script>
</div>

For the moment you don't bind any click event to that <button> I assume that you're looking for something like this :
$(document).ready(function() {
//First hide the alert :
$("#example").hide();
// then bind the click :
$("#alert-trigger").on("click", function () {
$("#example").fadeIn(); // Shows the alert
window.setTimeout(function() {
$("#example").fadeOut(); // hides it again
}, 3000);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="ex1">
<button id="alert-trigger" data-dismiss="alert" class="btnClick">
Trigger Alert
</button>
<div id="example" class="alert" role="alert">I'm an ALERT !</div>
</div>

With pure javaScript, just set the default opacity of the #example element to 0, change the opacity to 1 whenever your #alert-trigger button is clicked and use the setTimeout() method to change it back to 0 after 1 second.
With jQuery, just hide #example element by default and then simply use the fadeIn() method to fade it in on click and the use the setTimeout() method along with the fadeOut() method to fade the element out again after a set amount of seconds.
Check and run the following Code Snippets for practical examples of what I have described above:
Pure JavaScript approach:
/* JavaScript */
const btn = document.getElementById("alert-trigger");
const box = document.getElementById("example");
btn.addEventListener("click", function(){
box.style.opacity = 1;
setTimeout(function(){box.style.opacity = 0}, 1000);
});
/* CSS */
body {text-align: center;}#alert-trigger{background-color: green; padding: 5px; color: #FFF;}
#example {background-color: grey;padding: 10px;margin: 10px 0px;
opacity:0; /* initial opacity value set to 0 */
transition: all 1s; /* will fade the element instead of hiding/showing the element instantly */
}
<!-- HTML -->
<button id="alert-trigger">Trigger Alert</button>
<div id="example" >
<h2>Box Content Here:</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus quia dolore cumque aliquid eaque nisi, eos praesentium delectus tempore quidem? Iure tenetur cupiditate, laborum, saepe aut alias voluptatem impedit molestias.</p>
</div>
jQuery approach:
/* JavaScript */
$("#alert-trigger").on("click", function(){
$("#example").fadeIn(); // fade in the example div
setTimeout(function(){
$("#example").fadeOut(); // fade out the example div
}, 1000);
})
/* CSS */
#example {display:none;} /* initially hide it by default */
<!-- HTML -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="alert-trigger">Trigger Alert</button>
<div id="example" >
<h2>Box Content Here:</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus quia dolore cumque aliquid eaque nisi, eos praesentium delectus tempore quidem? Iure tenetur cupiditate, laborum, saepe aut alias voluptatem impedit molestias.</p>
</div>

Related

How to close a menu bar when clicking outside of it [duplicate]

This question already has answers here:
How do I detect a click outside an element?
(91 answers)
Closed 2 years ago.
I'm trying to find multiple ways to close a sidebar menu that pops out from the left side. The idea of this is to have a page with an "Open/Close Menu" button. As expected this button should be able to open and close the menu with clicked, but I also want to include an option of closing it when simply clicking outside the menu bar.
My thought process behind this is to add a div that surrounds all of the content on the page, and gives it a class name of "notMenu". I would define the dimensions of this to be the entire page and give it a z-index of 1. When the menu pops up, it would be on top of .notMenu with a z-index of 2, yet I can't seem to get it to work.
var menuBtn = document.querySelector('.menuBtn');
var sidebar = document.querySelector('.sidebar');
var closeMenuBtn = document.querySelector('.closeMenuBtn');
var notMenu = document.querySelector('.notMenu');
var nav = 'closed'
menuBtn.addEventListener('click', function() {
if (nav === 'closed') {
sidebar.style.display = 'block'
nav = 'open'
} else {
sidebar.style.display = 'none'
nav = 'closed'
}
});
// closeMenuBtn.addEventListener('click',function(){
// sidebar.style.display = 'none'
// });
closeMenuBtn.addEventListener('click', function() {
sidebar.style.display = 'none';
nav = 'closed';
});
/*
notMenu.addEventListener('click',function(){
sidebar.style.display = 'none'
nav = 'closed';
})
*/
h1 {
text-align: center;
}
.menuBtn {
position: relative;
left: 50%;
transform: translateX(-50%);
}
.closeMenu {
font-size: 30px;
z-index: 2;
}
.sidebar {
position: absolute;
top: 0;
height: 100vh;
width: 300px;
background: grey;
display: none;
z-index: 2;
}
.notMenu {
position: absolute;
top: 0;
height: 100%;
width: 100%;
z-index: 1;
}
<body>
<div class="notMenu">
<h1> Header </h1>
<div class="sidebar">
<ul>
<li><a href=''>Link1</a></li>
<li><a href=''>Link2</a></li>
<li><a href=''>Link3</a></li>
</ul>
<button class="closeMenuBtn">Close Menu</button>
</div>
<button class="menuBtn">Open/Close Menu</button>
<div class="content1">
<br><br> Lorem ipsum dolor sit amet consectetur, adipisicing elit. Aspernatur quia ipsam optio, veritatis corrupti exercitationem quae itaque accusamus voluptas ipsa consequuntur nostrum, culpa, cum dolore incidunt ducimus harum minus doloremque?
</div>
<div class="content2">
<br><br> Lorem ipsum dolor sit amet consectetur adipisicing elit. Eum quia laboriosam ut accusantium itaque adipisci vitae error provident voluptate, dolorem veniam dignissimos atque accusamus aut rem quos esse fugit voluptas soluta laudantium.
Nam voluptates maxime sapiente, pariatur voluptatibus mollitia quia.
</div>
</div>
<!--closes .notMenu-->
</body>
CodePen Link
Alternatively, is there a way to do this without designated a new class as .notMenu? I assume there is a possibility to do this with e.target in JS with if statements.
function(e){
if (e.target !== 'sidebar'){
sidebar.style.display = 'none'
}
}
The issue I ran into with this is that e.target returns an object. I'm unable to define which objects represent the sidebar and which ones do not, therefore I can't determine if the area outside the sidebar is being clicked.
try this
window.addEventListener('mouseup', function(e) {
var x = document.querySelector('.sidebar');
if (event.target != document.querySelector(".icon")) {
x.style.display = "none";
}
});
var menuBtn = document.querySelector('.menuBtn');
var sidebar = document.querySelector('.sidebar');
var closeMenuBtn = document.querySelector('.closeMenuBtn');
var notMenu = document.querySelector('.notMenu');
var nav = 'closed'
menuBtn.addEventListener('click',function(){
if (nav === 'closed'){
sidebar.style.display='block'
nav = 'open'
}
else{
sidebar.style.display = 'none'
nav = 'closed'
}
});
closeMenuBtn.addEventListener('click',function(){
sidebar.style.display = 'none';
nav = 'closed';
});
// fire event if click is outside of sidebar and menubtn
window.onclick = function(event) {
if (event.target !== sidebar && event.target !== menuBtn) {
sidebar.style.display = "none";
console.log('clicked');
}
}
h1{
text-align:center;
}
.menuBtn{
position:relative;
left:50%;
transform:translateX(-50%);
}
.closeMenu{
font-size:30px;
z-index:2;
}
.sidebar{
position:absolute;
top:0;
height:100vh;
width:300px;
background:grey;
display:none;
z-index:2;
}
.notMenu{
position:absolute;
top:0;
height:100%;
width:100%;
z-index:1;
}
<div class="notMenu">
<h1> Header </h1>
<div class="sidebar">
<ul>
<li><a href =''>Link1</a></li>
<li><a href =''>Link2</a></li>
<li><a href =''>Link3</a></li>
</ul>
<button class="closeMenuBtn">Close Menu</button>
</div>
<button class="menuBtn">Open/Close Menu</button>
<div class="content1">
<br><br>
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Aspernatur quia ipsam optio, veritatis corrupti exercitationem quae itaque accusamus voluptas ipsa consequuntur nostrum, culpa, cum dolore incidunt ducimus harum minus doloremque?
</div>
<div class="content2">
<br><br>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Eum quia laboriosam ut accusantium itaque adipisci vitae error provident voluptate, dolorem veniam dignissimos atque accusamus aut rem quos esse fugit voluptas soluta laudantium. Nam voluptates maxime sapiente, pariatur voluptatibus mollitia quia.
</div>
</div>
try this

Switching Div's on Refresh

I have a div at the top of the page, middle, and bottom. When I refresh the page each time I would like the top and bottom divs to switch without affecting the middle div at all. Thanks in advance for any answers.
My jsfiddle
Code:
.top {
background: lightpink;
padding: 40px;
}
.content {
background: white;
}
.bottom {
background: lightblue;
padding: 40px;
}
<div class="top">
1
</div>
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ullam fuga impedit, obcaecati, commodi dolores quasi odit numquam esse aliquid, alias natus doloribus nihil eius dicta eaque, nobis veritatis! Praesentium, laboriosam.
</div>
<div class="bottom">
2
</div>
It can be done using sessionStorage and cloning divs.
What this is doing is taking a copy of each div in the clone variables and then using a sessionStorage value to toggle between the states. If the sessionStorage value is 0 then it will do nothing but change the value, if it's 1 then it'll remove the divs and then add them in the new order from the cloned content.
var divOne = document.querySelector('.top');
var divTwo = document.querySelector('.bottom');
var divOneClone = document.querySelector('.top').outerHTML;
var divTwoClone = document.querySelector('.bottom').outerHTML;
var divContent = document.querySelector('.content');
if (sessionStorage.getItem('refreshState')) {
if (sessionStorage.getItem('refreshState') == 1) {
divOne.parentNode.removeChild(divOne);
divTwo.parentNode.removeChild(divTwo);
divContent.insertAdjacentHTML('beforebegin', divTwoClone);
divContent.insertAdjacentHTML('afterend', divOneClone);
sessionStorage.setItem('refreshState', 0);
} else {
sessionStorage.setItem('refreshState', 1);
}
} else {
sessionStorage.setItem('refreshState', 0);
}
Here's a working JS Fiddle example.

Prevent Bootstrap collapse item from "jumping"

I've set up a Bootstrap collapse plugin to use with my list of frequently asked questions:
https://jsfiddle.net/2d8ytuq0/
<ul class="faq__questions">
<li>
..
<p class="collapse" id="faq__question_1">...</p>
</li>
</ul>
The problem is when you collapse back the extended description it kind of "jumps". I think this happens due to the bottom margin the p element has. I tried to replace it with padding-bottom, but this didn't solve the issue. Is there any way to fix this without breaking the original layout?
This problem causes because your collapsed element has a margin-bottom:15px.
Your new HTML markup
<div class="collapse" id="faq__question_1">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Saepe nesciunt rerum mollitia nobis corporis sint error quaerat cupiditate animi doloribus! Voluptas dolores, incidunt perspiciatis labore velit libero minus consequuntur blanditiis.</p>
</div>
Simply add this css to override margin property..This works fine
.faq__questions > li p {
margin: 0;
}
You could always add a css transition to it.
I add an active state to the panels and to a css transition on the margin-top.
JS
// Add active class to open panel on faqs accordion
$('.faq__questions').on('show.bs.collapse', 'li', function () {
$(this).addClass('active');
});
$('.faq__questions').on('hide.bs.collapse', 'li', function () {
$(this).removeClass('active');
});
CSS
.faq__questions li .collapse{
margin-top: 0;
transition: all .2s ease-in-out;
}
.faq__questions li.active .collapse{
margin-top: 30px;
}

Loading content into a div [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am trying to create a page with images that upon a user hovering loads content into a div on the same page. So far, I have created the html file and the stylesheet. It's a fairly simple, table-based page, with three images that have the css hover effect on them and link to three different pages. My challenge is figuring out how to load content into the div. I am completely new to Javascript so this is going to be quite the learning curve I imagine but any help will be appreciated. I have attached an image to illustrate what I am trying to do. Thanks everyone]1
Updated question. Thanks for your input everybody. (Back from the holidays - will be going over suggestions)
My css code:
.Image1{
background-image:url('Image1_REG.jpg');
height:86px;
width:86px;
display: block;
}
.Image1:hover {
background-image:url('Image1_Shadow.jpg');
height:86px;
width:86px;
display:block;
}
.Image2{
background-image:url('Image2_REG.jpg');
height:86px;
width:86px;
display: block;
}
.Image2:hover {
background-image:url('Image2_Shadow.jpg');
height:86px;
width:86px;
display:block;
}
.Image3{
background-image:url('Image3_REG.jpg');
height:86px;
width:86px;
display: block;
}
.Image3:hover {
background-image:url('Image3_Shadow.jpg');
height:86px;
width:86px;
display:block;
}
#contentDiv{
height:150px;
width:350px;
left:50px;
top:150px;
position:absolute;
background-color:#452835;}
table {
width:600px;
height:auto;
column-width:200px;
left:150px;
top:150px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="newStyle.css"></link>
</head>
<body>
<body>
<table>
<tbody>
<tr><img src="header.jpg" align ="center" /></tr>
<tr>
<td><a class="Image1" href="http://link1" target="_blank"></a>
</td>
<td>
<a class="Image2" href="http://link2" target="_blank"></a>
</td>
<td><a class="Image3" href="http://link3" target="_blank"></a></td>
</tr>
</tbody>
</table>
<div id="contentDetails">Where the hover text is to be displayed</div>
</body>
</html>
You'll need a small bit of JavaScript but nothing you can't learn in half an hour. I'd advise you read the MDN JS primer but only to get a grasp for how JS works.
In essence you need to locate the element you want to hover over and then have multiple <div>s on your page containing your content. You add a JavaScript mouseover event on the elements you want to hover over and in the callback function you supply to it you tell it to hide all the divs and then display only the div you want.
I think you should be able to work out everything from these pages:
How to get an element in JS
How to add a mouseover event
How to hide and show elements
Best of luck with it. If you're stuck once you've written some code feel free to edit your question and comment on mine (so I know to take a look) and I'll try help.
Here's a very basic example I created that will help get you started:
JS Fiddle:
http://jsfiddle.net/dvav1gdo/5/
HTML
<div class="module">
<div class="tabs">
<div class="tab">
<img style="-webkit-user-select: none;" src="http://dummyimage.com/200x150/000/fff.jpg" width="200" height="150">
</div>
<div class="tab">
<img style="-webkit-user-select: none;" src="http://dummyimage.com/200x150/000/fff.jpg" width="200" height="150">
</div>
<div class="tab">
<img style="-webkit-user-select: none;" src="http://dummyimage.com/200x150/000/fff.jpg" width="200" height="150">
</div>
</div>
<div class="tab-panels">
<div class="tab-panel active">
<div class="content">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Velit unde inventore, aliquam architecto minus minima quis. Aliquid voluptates, dolorum ullam dicta nesciunt molestiae maiores! Ratione quasi officia recusandae laboriosam nihil voluptate perferendis fugiat quae provident aliquam harum id tenetur quisquam, ab repellendus suscipit eligendi temporibus facilis sapiente a veniam voluptatibus quidem in voluptatum vero. Soluta excepturi quisquam, sed, quas rem aperiam atque obcaecati nulla repellendus corporis? Consequatur aut quidem, earum enim asperiores. Libero deserunt dignissimos blanditiis est, repellendus qui molestiae tenetur quas assumenda officiis modi totam, quae ullam. Quaerat officiis tempora molestias voluptatibus sint quo incidunt nostrum quisquam sed excepturi?</p>
</div>
</div>
<div class="tab-panel">
<div class="content">
<p>Lorem ipsum dolor sit amet.</p>
</div>
</div>
<div class="tab-panel">
<div class="content">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Error fugit harum voluptates. Deserunt adipisci libero incidunt nostrum similique laborum dicta, porro natus harum odit, voluptatum vitae, minima iure omnis. Odit, nemo incidunt voluptas placeat est quis ab dolor. Iure, corporis.</p>
</div>
</div>
</div>
</div>
CSS
.tab {
display: inline-block;
}
.tab-panel {
display: none;
&.active {
display: block;
}
}
jQuery
$(document).ready(function () {
var $tabs = $('.tab');
var $panels = $('.tab-panel')
// attach js event handler to all tab jQuery objects
$tabs.on('mouseover', function() {
var $this = $(this);
// get hover index
var hindex = $this.index();
// use the active class to show and hide correct panel based on current hover index
$panels.removeClass('active');
$panels.eq(hindex).addClass('active');
});
});
You could use the hover or click function to detect interaction with the image then you use the div id/name to change the text with query i believe its should be $("").text("Some info")
example:
<div style="height:100px; width:100px" class="title"> //*
first text
</div>
The code that you need in order to change the text in the div which his class name is "title" (SEE comment "//*" above):
$('div.title').text('Some info');
Also See for more information "Use jquery to set value of div tag":
Use jquery to set value of div tag
LINKS:
http://api.jquery.com/text/
http://api.jquery.com/hover/
http://api.jquery.com/click/
Also you can use #tanjir 's code as example:
$('#img1').hover(function(){
$('#contentDiv').text("content for text 1")
};
Remember that
$('#img1'). hover(function(){
// CODE EXECUTE HERE AFTER HOVER OF IMAGE 1
}
*** this example has # in the start because he use the id of the div instead of the class name! so it would look like:
<div ID="img1">
</div>
Is a listener that wait you to hover, when you will hover the code where the comment is will execute.

printing hidden data through jquery

I have the following code where for display I want to hide the detail code and only should during print:
<div>
<ul>
<li>
<span style="font-size: 1.25em;">
<strong>#dateformat(startdate, "mm-dd-yyyy")# - #dateformat(enddate, "mm-dd-yyyy")#</strong>
</span><br/><br/>
#fullLeft(stripHTML(details),30)#
</div>
<div style="display:none;" class="completedata" align="left">
#details#
</div>
<li>
</ul>
</div>
$(window).load(function() {
$('li').each(function () {
$(this).css({
"page-break-after": "always"
});
$(".completedata").css('display','block');
window.print();
});
});
It shows the printing code on load with hidden display data, but when i cancel the printing command, it keeps the hidden div displays as block and shows in the display screen too.
The right way to do this is to use #media print:
.completedata { display: none; }
#media print
{
.completedata { display: block !important; }
}
$("button").on("click", function() {
window.print();
});
.completedata {
color: #e74c3c;
}
.completedata {
display: none;
}
#media print {
.completedata {
display: block !important;
}
button { display: none; }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Assumenda impedit sapiente atque quas aliquam a voluptate obcaecati saepe incidunt itaque eligendi sequi optio delectus similique laborum unde sint consectetur magnam?</p>
<p class="completedata">I appear only when printing the page!</p>
<button>Print me</button>

Categories