Show hide div with a time limit JS not Jquery - javascript

I have the following div hidden in the head of my site.
<div id="esperaMensaje" class="mensajeEspera" style="display:none;">
<p>Espere un momento...</p>
</div>
That when the user clicks on the button with the class "continue" The div appears, and then hides after 8 seconds.
I tried using jquery which would be the easiest but it didn't work as I am setting it up in prestashop and it is a bit cumbersome as it is using an old version of jquery so I would like to make it work with pure js.

Add an event listener on the button for "click", set the <div> to it's default display property, then after 8 seconds set it back to display: none via setTimeout.
document.querySelector(".continue").addEventListener("click", () => {
const div = document.querySelector("#esperaMensaje");
div.style.display = "";
setTimeout(() => div.style.display = "none", 8000); // 8000ms = 8s
});
<button class="continue">continue button</button>
<div id="esperaMensaje" class="mensajeEspera" style="display:none;">
<p>Espere un momento...</p>
</div>

Related

Creating a script for a button to close other sections when opening its own sections

This is hard to explain precisely. But here we go:
I have a button that calls a function
<button onclick="myFunction_gsm()">Men</button>
When the button is pressed, it triggers a script. This script grabs a hidden section and displays it. The script goes like this:
<script>
//Gender Selection Script Men//
function myFunction_gsm() {
var x = document.getElementById("men-sizing");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
</script>
On the screen this plays out so that you click the button, a section appears, if I click the same button again the section hides again. However, I have another 2 sections. 3 Sections in total. For this example, the above script works for 1 section, the A section. There is also B and C. I would like to include the behavior that when A has been pressed, therefore displaying section A, if I then press the button for B the B section appears but the A section disappears without having to press the A button again. A Dynamic change of sorts.
I am a complete starter for coding but I assume it's something you add into the if statement. Any help would be greatly appreciated.
I would prefer solutions that incorporate the code I have now, since I won't have much use recreating it from scratch. It would solve this, but cause many new problems.
Define a class for all sections, for example sec. On click event pass the selected id, hide all of them and just toggle the selected one.
function myFunction_gsm(sectionId) {
let sec = document.querySelectorAll('.sec');
sec.forEach(itm => {
if(itm.id !== sectionId) itm.style.display = 'none'
})
var x = document.getElementById(sectionId);
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
let sec = document.querySelectorAll('.sec');
sec.forEach(itm => {
itm.style.display = 'none'
})
<button onclick="myFunction_gsm('sec1')">Sec1</button>
<button onclick="myFunction_gsm('sec2')">Sec2</button>
<button onclick="myFunction_gsm('sec3')">Sec3</button>
<div class="sec" id="sec1"> some text 1 here</div>
<div class="sec" id="sec2"> some text 2 here</div>
<div class="sec" id="sec3"> some text 3 here</div>
You might use class names for the sections. Then at the start of the function have all elements with that class name be hidden and afterwards display the currently clicked one.
If you want to preserve the toggle functionality for the section (so clicking A twice displays and hides it again), you want to check the display state of the currently clicked one first before hiding all. And then only display the clicked one if it was hidden before.
The modern approach is to avoid using .style within JS. This add the stylign as inline-style which ahs the highest specificty weight with exeption of important. The modern solution is to use classList to apply, remove or toggle a CSS-Class.
You add a class to CSS to hide element such as: .display-none { display: none; }`
Then you add a function to your button to hide all sections with a certain class by adding the class mentioned at step 1: function hideAll() { document.querySelectorAll('.class-name').forEach(el => el.classList.add('display-none')); }
You add a second function to the onclick trigger of a button thow a certain element by removing the class: element.classList.remove('display-none');
function hideAll() {
document.querySelectorAll('.section').forEach(el => el.classList.add('display-none'));
}
function showA() {
document.querySelector('#section-a').classList.remove('display-none');
}
function showB() {
document.querySelector('#section-b').classList.remove('display-none');
}
function showC() {
document.querySelector('#section-c').classList.remove('display-none');
}
.display-none {
display: none;
}
<button onclick="hideAll(); showA()">Show A</button>
<button onclick="hideAll(); showB()">Show B</button>
<button onclick="hideAll(); showC()">Show C</button>
<section id="section-a" class="section display-none">Section A</section>
<section id="section-b" class="section display-none">Section B</section>
<section id="section-c" class="section display-none">Section C</section>
CSS-only Solution
If you dont want to sue scripts, you could use a pure CSS-Method that works through the :target selector. This allows you to use anchor as "trigger".
Hide the scetiond with display: none; either by selecting them directly or adding a class to them.
use an anchor with an href="#id" instead of a link. This will move the page to that element but also manipulate the websites adress.
Use *:target { display: block; } to show targeted elements:
.display-none {
display: none;
}
*:target {
display: block;
}
/* for styling purpose only */
a {
margin-right: 15px;
}
Show A
Show B
Show C
<section id="section-a" class="display-none">Section A</section>
<section id="section-b" class="display-none">Section B</section>
<section id="section-c" class="display-none">Section C</section>

Javascript - Show a div section set as hidden

I know there are A LOT of Qs on hiding-showing a div: I tried them all but somehow nothing seems to work.
I have a form and on loading the page div 1 shows. Once user hits the "Next" button then div 2 (previously not displayed) needs to show. What I would need help with is get the div 2 displayed upon click of the Next button
here is one of my many attempts:
<div>
table 1
</div>
<button name="next" onclick="javascript:showDiv();"> Next </button>
<script type="text/javascript">
function showDiv() {
div = document.getElemntById('dynamic');
div.style.visibility = "visible";
}
</script>
<div id="dynamic" style="display:none">
table 2
<input type="submit" value="Submit"/>
</div>
</form>
</body>
If anyone at all could help me I would be most grateful!! Thank you
You need to switch between "display:none" and "display:block" to hide and show the div.
Also you function should be document.getElementById instead of document.getElemntById
function showDiv() {
div = document.getElementById('dynamic');
div.style.display = "block";
}
<button name="next" onclick="javascript:showDiv();"> Next </button>
<div id="dynamic" style="display:none">
table 2
<input type="submit" value="Submit"/>
</div>
Confusingly, display: none can't be cancelled out by setting visibility to visible. The display property determines how the layout engine positions the div, and the visibility property determines whether it is rendered. So if you start off the div with
<div id="dynamic" style="visibility:hidden">
It should work fine. I generally don't recommend hiding stuff using display: none because it forces the browser to re-layout the window which can move elements around. Using visibility means that everything stays still.
if(document.getElementById("div1").style.display == "none")
{
document.getElementById("div1").style.display = "";//show it
}
else
{
document.getElementById("div1").style.display = "none";//hide it
}

Adding Timeout breaks everything

I have 3 nav buttons that, when hovered over, open a menu underneath. I want to add a timer when then mouse leaves the button so it doesn't close right away after opening. It bugs out a bit then. This is my starter code in jquery, for opening the drop-menu
$('.info').hover(function () {
$('.d-skills').show(500);
$('.d-info').hide(500);
$('.d-exp').hide(500);
});
If I add this code in it breaks and nothing works
function(){ t = setTimeout(function(){$('.d-info').hide(500)}, 500;)
}
Also, i add
var t;
on the very beggining, and i separate the functions with a ','.
'd-info' is the class for the drop menu, and 'info' is the button class
You can use handlerOut function for hover.
Below is a simple snippet that demonstrates this and hides the sections after a 1.5 second delay.
$('.info').hover(function () {
$('.d-sections').show(500);
}, function() {
setTimeout(function() {
$('.d-sections').hide(500);
}, 1500);
});
.d-sections {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="info">
Hover here for more Information!
<div class="d-sections">
<div class="d-skills">
The D Skills section!
</div>
<div class="d-info">
The D Info section!
</div>
<div class="d-exp">
The D Exp section!
</div>
</div>
</div>
https://jsfiddle.net/32bekom9/1/

slideDown does not work for the first time

I'm adding animation to show a hidden div when a checkbox is changed,
The first time it's clicked the div appears with no animation but it works both ways after the first time.
How can I make it work also on the first time?
Here is my div (also using bootstrap)
var postOptionsSourcesWrapper = $("#post-options-sources-wrapper");
var postOptionsExclusiveCheckbox = $("#post-exclusive-cb");
postOptionsExclusiveCheckbox.change(function() {
if ($(this).is(":checked")) {
postOptionsSourcesWrapper.slideUp(300, "easeOutCirc", function() {
postOptionsSourcesWrapper.addClass("hidden");
});
} else {
postOptionsSourcesWrapper.removeClass("hidden");
postOptionsSourcesWrapper.slideDown(300, "easeOutCirc");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="post-options-sources-wrapper" class="margin-b-5 hidden">
<label class="text-md thick-600">Original post references</label>
<div class="box-marker box-marker-white">
<div class="thick-600 color-gray text-sm text-uppercase">
Add one or multiple sources.
</div>
</div>
</div>
UPDATE: this issue is solved by adding display:none; to the div
When adding the bootstrap class .hidden to hide for some reason it's not adding the display:none; that is part of the .hidden class in bootstrap... not sure why, but adding the style display:none; or calling postOptionsSourcesWrapper.hide() solves this issue.
This code will achieve what you want to achieve.
You just have to replace your script with this one.
var postOptionsSourcesWrapper = $("#post-options-sources-wrapper");
var postOptionsExclusiveCheckbox = $("#post-exclusive-cb");
postOptionsSourcesWrapper.hide();
postOptionsExclusiveCheckbox.change(function() {
postOptionsSourcesWrapper.slideToggle(300,postOptionsSourcesWrapper.is(":checked"));
});

Hide existing <div> and show previous <div> in multi-branch form

I will start by telling you that this is my very first Javascript program from scratch. I am trying to make a back button that will go to the previously chosen div in a form (hide the current div and show the previous one the user chose).
The form has multiple paths to follow, paths within paths and not all selectors are buttons. There might be an onchange event or a radio button or even text input (text inputs have a next button to click).
I have had it working where it will hide the current div but show all previous chosen divs. It's now working where it hides the current div but shows nothing.
I have read a bunch of postings here and in other forums but have not found what I need yet. Any help would be greatly appreciated.
You can see the actual site here and I have put up a JSfiddle but for some reason I can't get it working there.
Here is the code from the fiddle:
<div>
<form>
<div id="uno" class="showFirst">
<button onclick="hideUno()">First Button</button>
</div>
<div id="dos" class="hideFirst">
<button onclick="hideDos()">Second Button</button>
</div>
<div id="tres" class="hideFirst">
<button onclick="hidetres()">Third Button</button>
</div>
<div id="quattro" class="hideFirst">
<button onclick="hideQuattroUno()">Fourth Button</button>
<button onclick="hideQuattroDos()">Fifth Button</button>
</div>
<div id="branchUno" class="hideFirst">
<p>First Branch</p>
</div>
<div id="branchDos" class="hideFirst">
<p>Second Branch</p>
</div>
</form>
<button id="backButton" onclick="goToPrevious" class="hideFirst">Back</button>
</div>
.hideFirst {
display: none;
}
function goToPrevious() {
var current = $(".chosen").find(":visible");
$(current).hide();
$(current).prev(".chosen").show();
}
function hideUno() {
$("#backButton").toggle();
$("#uno").toggle();
$("#uno").addClass("chosen");
$("#dos").toggle();
}
function hideDos() {
$("#dos").toggle();
$("#dos").addClass("chosen");
$("#tres").toggle();
}
function hideTres() {
$("#tres").toggle();
$("#tres").addClass("chosen");
$("#quattro").toggle();
}
function hideQuattroUno() {
$("#quattro").toggle();
$("#quattro").addClass("chosen");
$("#branchUno").toggle();
}
function hideQuattroDos() {
$("#quattro").toggle();
$("#quattro").addClass("chosen");
$("#branchDos").toggle();
}
Here are a few of the questions I've reviewed here:
retain show / hide div on multistep form
Hide and Show div in same level
how to show previous div of clicked div in angular.js
show div and hide existing div if open with jQuery?
Show one div and hide the previous showing div
I realize it's not the cleanest code, but as I said this is my first and I am trying to cleanup as I go along and learn new things.
You could make a bit of automatization instead of creating onclick events for each button/select separately.
For "Back" functionality, I'd use an array to store elements "on the fly" at each step, instead of checking visibility later on.
I'll make it this way:
Remove CSS rule display:none for hideFirst class (elements will be hidden using jQuery).
Add an class to the buttons/selects/check-boxes/etc... as event inndicator.
Add data-next attribute (to store id of the element which should be shown on click/change)
HTML:
<div id="firstDiv" class="hideFirst">
<button class="my-btn" data-next="#secondDiv" type="button">Show next<button>
</div>
<div id="secondDiv" class="hideFirst">
<select class="my-select" data-next="#thirdDiv">
<option>Helo World</option>
...
</select>
</div>
...
Script:
$(document).ready(function(){
// hide all 'hideFirst' elements, except the first one:
$('.hideFirst:not(:first)').hide();
// declare 'history' variable as an empty array (it will be used to store 'hideFirst' elements for 'Back' functionality):
var history = [];
// click event for the buttons :
$('.my-btn').click(function(e){
// as the button will submit the form if you're not using type="button" attribute, use this:
e.preventDefault();
showNext($(this));
});
// change event for selects :
$('.my-select').change(function(){
showNext($(this));
});
// Method used to show/hide elements :
function showNext(el){
// check if element has a 'data-next' attribute:
if(el.data('next')){
// hide all elements with 'hideFirst' class:
$('.hideFirst').hide();
// show 'Back' button:
$('#backButton').show();
// show the element which id has been stored in 'data-next' attribute:
$(el.data('next')).show();
// Push the parent element ('.hideFirst') into history array:
history.push(el.closest('.hideFirst'));
}
}
// click event for 'back' button:
$('#backButton').click(function(){
// hide all elements with 'hideFirst' class:
$('.hideFirst').hide();
// remove the last '.hideFirst' element from 'history' array and show() it:
history.pop().show();
// hide 'back' button if history array is empty:
history.length || $(this).hide();
}).hide(); // hide 'back' button on init
});
DEMO

Categories

Resources