How to make an HTML element appear after a specific page - javascript

I want to make the element <div id="text"> appear after a loading screen: "Welcome in Shanghaied".
But I can't make it show.
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Idk</title>
<script src="skrypt.js"></script> <!--Zaimportowanie javascriptu-->
<link rel="stylesheet" type="text/css" href="style.css"> <!--Odwołanie do cssa-->
</head>
<body>
<div class="disappear">
<div class="container"> <!--Div z napisem-->
<div class="data">Welcome in Shanghaied</div> <!--Tu wpisz tekst-->
</div>
<!--Rozpoczęcia javascriptu-->
<script type="text/javascript">
const text = baffle(".data");
text.set({
characters : '▒▓░ >▒█▓▒▒ >█▓▒░ ██▒ ▒█/▒░ ▓░>> <▒▓ █▒▓░ █▒▓▓',
// szybkość, im większa tym wolniej
speed: 69
})
text.start();
//ilość znaków
text.reveal(4201);
</script>
</div>
<div class="content">
<div id="text">
<p>Test for the Text</p>
</div>
</div>
</body>
</html>
Css
html, body{
margin: 0; /* margines */
padding: 0; /* Padding */
width: 100%; /* Szerokość */
height: 100vh; /* Wysokość */
background: #101010; /* Kolor tła */
cursor: none; /* Chowanie kursora */
}
.data{
font-family: Arial, Verdana, sans-serif; /* Po font family dajemy nazwe czcionki */
color: #fff; /* Kolor czcionki */
font-size: 40px; /* Rozmiar czcionki */
letter-spacing: 12px; /* Spacje pomiędzy literami */
font-weight: 500; /* Grubość czcionki */
position: absolute; /* Pozycja czcionki */
top: 50%; /* Pozycja czcionki */
left:50%; /* Pozycja czcionki */
transform: translate(-50%, -50%);
}
.disappear {
animation: disappear 0s linear 3.2s forwards;
}
#keyframes disappear {
to {opacity:0;}
}
#text p {
display: inline-block;
font-size: 21px;
text-align: center;
position: absolute;
animation: appear 2s;
left: 315px;
}
#keyframes appear {
from {
left: -100px;
}
to {
left: 315px;
}
}
#-moz-keyframes appear {
/* Firefox */
from {
left: -100px;
}
to {
left: 315px;
}
}
#-webkit-keyframes appear {
/* Safari and Chrome */
from {
left: -100px;
}
to {
left: 315px;
}
}
#-o-keyframes appear {
/* Opera */
from {
left: -100px;
}
to {
left: 315px;
}
}
JS
/*!
* baffle 0.3.6 - A tiny javascript library for obfuscating and revealing text in DOM elements.
* Copyright (c) 2016 Cam Wiegert <cam#camwiegert.com> - https://camwiegert.github.io/baffle
* License: MIT
*/
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.baffle=e():t.baffle=e()}(this,function(){return function(t){function e(r){if(n[r])return n[r].exports;var i=n[r]={exports:{},id:r,loaded:!1};return t[r].call(i.exports,i,i.exports,e),i.loaded=!0,i.exports}var n={};return e.m=t,e.c=n,e.p="",e(0)}([function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{"default":t}}var i=n(2),o=r(i);t.exports=o["default"]},function(t,e){"use strict";function n(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n]);return t}function r(t,e){return t.split("").map(e).join("")}function i(t){return t[Math.floor(Math.random()*t.length)]}function o(t,e){for(var n=0,r=t.length;n<r;n++)e(t[n],n)}function u(t){return t.map(function(t,e){return!!t&&e}).filter(function(t){return t!==!1})}function s(t){return"string"==typeof t?[].slice.call(document.querySelectorAll(t)):[NodeList,HTMLCollection].some(function(e){return t instanceof e})?[].slice.call(t):t.nodeType?[t]:t}Object.defineProperty(e,"__esModule",{value:!0}),e.extend=n,e.mapString=r,e.sample=i,e.each=o,e.getTruthyIndices=u,e.getElements=s},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{"default":t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var o=n(1),u=n(3),s=r(u),c={characters:"AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz~!##$%^&*()-+=[]{}|;:,./<>?",exclude:[" "],speed:50},a=function(){function t(e,n){i(this,t),this.options=(0,o.extend)(Object.create(c),n),this.elements=(0,o.getElements)(e).map(s["default"]),this.running=!1}return t.prototype.once=function(){var t=this;return(0,o.each)(this.elements,function(e){return e.write(t.options.characters,t.options.exclude)}),this.running=!0,this},t.prototype.start=function(){var t=this;return clearInterval(this.interval),(0,o.each)(this.elements,function(t){return t.init()}),this.interval=setInterval(function(){return t.once()},this.options.speed),this.running=!0,this},t.prototype.stop=function(){return clearInterval(this.interval),this.running=!1,this},t.prototype.set=function(t){return(0,o.extend)(this.options,t),this.running&&this.start(),this},t.prototype.text=function(t){var e=this;return(0,o.each)(this.elements,function(n){n.text(t(n.value)),e.running||n.write()}),this},t.prototype.reveal=function(){var t=this,e=arguments.length<=0||void 0===arguments[0]?0:arguments[0],n=arguments.length<=1||void 0===arguments[1]?0:arguments[1],r=e/this.options.speed||1,i=function(){clearInterval(t.interval),t.running=!0,t.interval=setInterval(function(){var e=t.elements.filter(function(t){return!t.bitmap.every(function(t){return!t})});(0,o.each)(e,function(e){var n=Math.ceil(e.value.length/r);e.decay(n).write(t.options.characters,t.options.exclude)}),e.length||(t.stop(),(0,o.each)(t.elements,function(t){return t.init()}))},t.options.speed)};return setTimeout(i,n),this},t}();e["default"]=function(t,e){return new a(t,e)}},function(t,e,n){"use strict";function r(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function i(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(e,"__esModule",{value:!0});var u=n(1),s=function(){function t(e){o(this,t),this.value=e,this.init()}return t.prototype.init=function(){return this.bitmap=this.value.split("").map(function(){return 1}),this},t.prototype.render=function(){var t=this,e=arguments.length<=0||void 0===arguments[0]?[]:arguments[0],n=arguments.length<=1||void 0===arguments[1]?[]:arguments[1];return e.length?(0,u.mapString)(this.value,function(r,i){return n.indexOf(r)>-1?r:t.bitmap[i]?(0,u.sample)(e):r}):this.value},t.prototype.decay=function(){for(var t=arguments.length<=0||void 0===arguments[0]?1:arguments[0];t--;){var e=(0,u.getTruthyIndices)(this.bitmap);this.bitmap[(0,u.sample)(e)]=0}return this},t.prototype.text=function(){var t=arguments.length<=0||void 0===arguments[0]?this.value:arguments[0];return this.value=t,this.init(),this},t}(),c=function(t){function e(n){o(this,e);var i=r(this,t.call(this,n.textContent));return i.element=n,i}return i(e,t),e.prototype.write=function(t,e){return this.element.textContent=this.render(t,e),this},e}(s);e["default"]=function(t){return new c(t)}}])});

You can either create a page, which only does the loading screen, and then move onto another page with the element.
or otherwise give the loading screen an opaque background to hide the element, then hide it afterwards.
document.getElementById("text").style.display = "none"; //Hide
document.getElementById("text").style.display = "none"; //Show
You can additionally defer the script via:
<script src="script.js" defer></script>

Well.. first of all, your text is black on a black background.. so it's never gonna appear unless you change that. :-) Secondly, you can add a function that will execute it after your loading ends called setTimeout, tag the p using query selector and apply the animation.
I changed the variable to timeLoading to track your intro, applied it in, and used that to change setTimeout.. with a change of -1000 to make it better (not sure why, the loading is kinda weird). The only thing that is wrong now is that at the beginning your text should be off screen.. but I'll leave that to you to practice. ;)
Here's the code you need:
<script type="text/javascript">
const text = baffle(".data");
text.set({
characters : '▒▓░ >▒█▓▒▒ >█▓▒░ ██▒ ▒█/▒░ ▓░>> <▒▓ █▒▓░ █▒▓▓',
// szybkość, im większa tym wolniej
speed: 69
})
text.start();
//ilość znaków
let timeLoading = 4000; // Set your intro loading here
text.reveal(timeLoading);
setTimeout(() => {
document.querySelector("#text p").style.animation = "appear 2s";
}, timeLoading - 1000);
</script>

Related

Barba js not transitioning my page, How do I fix not defined?

I am trying to at a page transition with Barba.js not using an animator just Css Keyframes,
I just cant seem to get the transition working. the only error im getting is barba not defined but I don't see where ?
installed Barba via npm
used the cdn script link
attached both html pages to each the css and the js page
initiated the DOM.
still not having any luck . VERY STUCK
there is a second html page called page two formatted exactly like the first
TIA
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/index.css">
<script src="Index.js" defer></script>
<title>Document</title>
</head>
<body>
<body data-barba="wrapper">
<main data-barba="container" data-barba-namespace="home">
<!-- put here the content you wish to change
between your pages, like your main content <h1> or <p> -->
<div class="Page1">
<h1>Welcome home</h1>
to my network projects
</div>
</main>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/barba.js/1.0.0/barba.min.js" integrity="sha512-7b1FfB2MGnB65aK6jrbS8k3REB+8bEE8UfP/TEwacejD0g02nLLI1VL4IPcKyiLk2lf7HJWaUYEUWc65aqaXQg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://unpkg.com/#barba/core"></script>
</body>
</html>
{
margin: 0%;
padding: 0%;
box-sizing: border-box;
}
.Page1, .Page2{
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
width: 100%;
flex-direction: column;
position: absolute;
}
a{
color: antiquewhite;
text-decoration: none;
margin-top: 50px;
padding: 10px 30px;
border: 2px solid black;
}
.Page1{
background-color: pink;
}
.Page2{
background-color: antiquewhite;
}
.slide-in {
animation: slide-in 0.5s forwards;
}
#keyframes slide-in {
from {
transform: translateX(100%);
visibility: visible;
}
to{
transform: translateX(0%);
}
}
(function (Barba) {
document.addEventListener("DOMContentLoaded", function (event) {
console.log('pjax start');
// Barba init
Barba.Pjax.start();
// Barba prefetch init
Barba.Prefetch.init();
var FadeTransition = Barba.BaseTransition.extend({
start: function () {
/**
* This function is automatically called as soon the Transition starts
* this.newContainerLoading is a Promise for the loading of the new container
* (Barba.js also comes with an handy Promise polyfill!)
*/
// As soon the loading is finished and the old page is faded out, let's fade the new page
Promise
.all([this.newContainerLoading, this.fadeOut()])
.then(this.fadeIn.bind(this));
},
fadeOut: function () {
/**
* this.oldContainer is the HTMLElement of the old Container
*/
},
fadeIn: function () {
/**
* this.newContainer is the HTMLElement of the new Container
* At this stage newContainer is on the DOM (inside our #barba-container and with visibility: hidden)
* Please note, newContainer is available just after newContainerLoading is resolved!
*/
this.newContainer.classList.Add('slide-in');
this.newContainer(animationend,function(){
var that = this
this.newContainer.classList.remove('slide-in');
that.done
});
}
});
/**
* Next step, you have to tell Barba to use the new Transition
*/
Barba.Pjax.getTransition = function () {
/**
* Here you can use your own logic!
* For example you can use different Transition based on the current page or link...
*/
return FadeTransition;
};
});
}(Barba));

How do I set the active state for image buttons instead of just focused state with my current code?

First time posting here and new to programming with just 3 days of experience.
I'm having some trouble getting my default button to be active instead of just focused. I've attempted to read other posts about this, but my lack of experience makes it hard for me to put 2 and 2 together.
The page is going into squarespace so I'm trying to do it all in one code block. I don't want the buttons to deactivate when the user clicks on other parts of the website, which it currently happens. (Even if they click on blank areas).
Thank you very much for any advice you can give me.
/* Change Button Size/Border/BG Color And Align To Middle */
.services {
width: 210px;
height: 135px;
padding: 0px;
border: 0px;
outline: 0px;
cursor: pointer;
color: #999999;
font-size: 20px;
text-align: center;
background: url("https://i.ibb.co/G5mn9nY/Services-Buttons-Combined-Big.png") no-repeat;
/* As all link share the same background-image */
}
/* Set Mouseover Button Text and Current/Active Color */
.services:focus,
.services:hover,
.services:active {
color: black;
}
/* Position Button Text*/
divtext {
position: relative;
top: 90px;
}
/* Div Wrapper to format button areas. */
.servicesbuttonwrapper {
display: flex;
flex-flow: row wrap;
justify-content: space-around;
}
/* Div Wrapper to format revealed description text. */
.servicestextwrapper {
text-align: left;
margin-left: 100px;
margin-right: 32px;
top: 50px;
position: relative;
}
/* Change Image rollover position depending On Focus. */
.assets {
background-position: 0 0;
}
.assets:focus,
.assets:hover,
.assets:active {
background-position: 0 -135px;
}
.viz {
background-position: 0 -270px;
}
.viz:focus,
.viz:hover,
.viz:active {
background-position: 0 -405px;
}
.software {
background-position: 0 -540px;
}
.software:focus,
.software:hover,
.software:active {
background-position: 0 -675px;
}
.more {
background-position: 0 -810px;
}
.more:focus,
.more:hover,
.more:active {
background-position: 0 -945px;
}
/* Hides intitial button descriptions. */
#assets,
#viz,
#software,
#more {
display: none;
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Services</title>
</head>
<body>
<!--Div wrapper so we can format positioning of buttons in CSS-->
<div class="servicesbuttonwrapper">
<!--Base buttons plus javascript functions for click behavior. This used to be <button class> instead of <a href> but I read somewhere this is better... seems to work ok.-->
<a href="javascript:void(0)" id="defaultstate" onclick="show('software');" class="services software">
<divtext>INTERACTIVE SOFTWARE</divtext>
</a>
<a href="javascript:void(0)" onclick="show('assets');" class="services assets">
<divtext>3D ASSET CREATION</divtext>
</a>
<a href="javascript:void(0)" onclick="show('viz');" class="services viz">
<divtext>3D VISUALIZATION</divtext>
</a>
<a href="javascript:void(0)" onclick="show('more');" class="services more">
<divtext>IMAGE CREATION</divtext>
</a>
</div>
<!--Base description text.-->
<div class="servicestextwrapper">
<div id="assets">3D Assets Description.</div>
<div id="viz">3D Visualization Description.</div>
<div id="software">Interactive Software Description.</div>
<div id="more">And More Description.</div>
</div>
<!--Javascript function to hide/show elements based on button press.-->
<script type="text/javascript">
function show(elementId) {
document.getElementById("assets").style.display = "none";
document.getElementById("viz").style.display = "none";
document.getElementById("software").style.display = "none";
document.getElementById("more").style.display = "none";
document.getElementById(elementId).style.display = "block";
}
</script>
<!--Javascript function to set first button as focus.-->
<script>
window.onload = function() {
document.getElementById("defaultstate").click();
};
var linkToFocus = document.getElementById('defaultstate');
linkToFocus.focus();
</script>
</body>
</html>
Welcome to Stack Overflow.
So first thing to note, the :active pseudo element only applies when the user clicks (mouse-down) on something. You can see it here
The most common method is to apply the css class "active", and have a .active selector on whatever element you want to style.
Right now you have the buttons affected by hover and focus, so when the user clicks outside the button it loses focus.
You can solve this by changing a bit of CSS and javascript. The edited portions are marked by /* EDIT */
I would not recommend the last line where I exploit the fact that your function passes in the element ID, and that element ID matches the class of the button that was used to select it. A better way would to have show take the Javascript event as argument, then use the event.target to get the a tag clicked on, then use a getElementById on something like a data-target="more" attribute. This will allow you to change the CSS class without coupling the class to the implementation of the Javascript
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Services</title>
</head>
<style>/* Change Button Size/Border/BG Color And Align To Middle */
.services {
width:210px;
height:135px;
padding: 0px;
border:0px;
outline:0px;
cursor: pointer;
color: #999999;
font-size: 20px;
text-align: center;
background: url("https://i.ibb.co/G5mn9nY/Services-Buttons-Combined-Big.png") no-repeat; /* As all link share the same background-image */
}
/* Set Mouseover Button Text and Current/Active Color */
/* EDIT */
.services:focus, .services:hover, .services.active {
color: black;
}
/* Position Button Text*/
divtext {
position: relative;
top: 90px;
}
/* Div Wrapper to format button areas. */
.servicesbuttonwrapper {
display: flex;
flex-flow: row wrap;
justify-content: space-around;
}
/* Div Wrapper to format revealed description text. */
.servicestextwrapper {
text-align: left;
margin-left: 100px;
margin-right: 32px;
top: 50px;
position: relative;
}
/* Change Image rollover position depending On Focus. */
.assets {
background-position: 0 0;
}
/* EDIT */
.assets:focus, .assets:hover, .assets.active {
background-position: 0 -135px;
}
.viz {
background-position: 0 -270px;
}
/* EDIT */
.viz:focus, .viz:hover, .viz.active {
background-position: 0 -405px;
}
.software {
background-position: 0 -540px;
}
/* EDIT */
.software:focus, .software:hover, .software.active {
background-position: 0 -675px;
}
.more {
background-position: 0 -810px;
}
/* EDIT */
.more:focus, .more:hover, .more.active {
background-position: 0 -945px;
}
/* Hides intitial button descriptions. */
#assets, #viz, #software, #more {
display: none;
}
</style>
<body>
<!--Div wrapper so we can format positioning of buttons in CSS-->
<div class="servicesbuttonwrapper">
<!--Base buttons plus javascript functions for click behavior. This used to be <button class> instead of <a href> but I read somewhere this is better... seems to work ok.-->
<divtext>INTERACTIVE SOFTWARE</divtext>
<divtext>3D ASSET CREATION</divtext>
<divtext>3D VISUALIZATION</divtext>
<divtext>IMAGE CREATION</divtext>
</div>
<!--Base description text.-->
<div class="servicestextwrapper">
<div id="assets">3D Assets Description.</div>
<div id="viz">3D Visualization Description.</div>
<div id="software">Interactive Software Description.</div>
<div id="more">And More Description.</div>
</div>
<!--Javascript function to hide/show elements based on button press.-->
<script type="text/javascript">
/* EDIT */
function show(elementId) {
document.getElementById("assets").style.display = "none";
document.getElementById("viz").style.display = "none";
document.getElementById("software").style.display = "none";
document.getElementById("more").style.display = "none";
document.getElementById(elementId).style.display = "block";
// get a list of the buttons with ".services" class
const buttons = document.querySelectorAll(".services");
for(let button of buttons) {
// remove ".active" class
button.classList.remove("active");
}
// add the active class to element button specified by argument
document.querySelector("." + elementId).classList.add("active");
}
</script>
<!--Javascript function to set first button as focus.-->
<script>
window.onload=function(){
document.getElementById("defaultstate").click();
};
var linkToFocus = document.getElementById('defaultstate');
linkToFocus.focus();
</script>
</body>
</html>

Fade in text on load

I've seen that there are different ways to fade in an object on load but every time I try to apply it to my own code I must be messing something up. I've been trying css and javascript so I'm good to use whatever I can get working.
I would like Hello to fade up on load but then 5 seconds later Next Page also fade's in.
Here's my code so far.
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
<link href="sky.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="sky.js"></script>
</head>
<body>
<div id="Welcome">
<h1> Hello </h1>
</div>
<div id="Next">
<h2> Next Page </h2>
</div>
<video autoplay muted loop id="VidBackground">
<source src="video/home.mp4">
</video>
</body>
</html>
and here's my css
h1, h3, a {
color: #ffffff;
line-height: 2;
}
#welcome {
position: absolute;
bottom: 15%;
right: 20%;
z-index: 2;
}
#next {
position: absolute;
bottom: 10%;
right: 20%;
z-index: 2;
}
#VidBackground {
position: fixed;
right: 0;
bottom: 0;
object-fit: cover;
z-index: -1;
}
This will be a good fit for CSS transitions.
You can use them like this:
transition: <css property> <transition-duration> <transition-function>
Example:
#next {
transition: opacity 0.5s ease-in-out;
opacity: 0;
/*pointer-events makes this node not respond to mouse/touch events
Which is probably what we want while the button is invisible.*/
pointer-events: none;
}
Now whenever the opacity style changes on #next it will transition instead of appearing instantaneous. Typically you would trigger it by some javascript.
window.onload = function() {
setTimeout(function() {
//Re-enable mouse/touch events on the #next button
document.getElementById("next").style.pointerEvents = 'auto';
//Show the #next button
//Since opacity style is transitioned, the opacity change will automatically trigger the transition.
document.getElementById("next").style.opacity = 1;
}, 5000);
});
Further reading on transitions can be found over at the MDN docs: https://developer.mozilla.org/en-US/docs/Web/CSS/transition

Javascript: Iterate through ID -> cannot set property 'onclick' of null javascript

I'm trying to code a modal with a slideshow. It works fine for the first picture when I type '1' instead of 'i' in the for loop. When I use 'i' in the for loop I get the error message "cannot set property 'onclick' of null javascript"
I know that this is some very beginner stuff... but I'm sitting here now for hours to find a solution...
Thank you for your help!
window.onload = function() {
var modal;
var prefixModal = 'myModal';
var img;
var prefixmyImg = 'myImg';
var modalImg;
var prefixmodalImg = 'img';
for (var i = 0; i <= 6; i++) {
modal = document.getElementById(prefixModal + i);
img = document.getElementById(prefixmyImg + i);
modalImg = document.getElementById(prefixmodalImg + i);
}
var closey = document.getElementsByClassName('close');
img.onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
}
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
};
.container_slideshow {
white-space: nowrap;
overflow-y: hidden;
overflow-x: scroll;
display: block;
height: 8rem;
margin-top: 1rem;
min-width: 100%;
}
.content_slideshow {
display: inline-block;
height: 100%;
width: 40vw;
background-color: darkgray;
margin-left: 0;
margin-right: .5rem;
}
.content_slideshow:last-child {
margin: 0;
}
}
/* Style the Image Used to Trigger the Modal */
#myImg {
border-radius: 5px;
cursor: pointer;
transition: 0.3s;
}
#myImg:hover {opacity: 0.7;}
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 50%; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: scroll; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(57,61,69,0.6); /* Black w/ opacity */
}
/* Modal Content (Image) */
.modal-content {
margin: auto;
display: block;
width: 80%;
max-width: 700px;
}
/* Caption of Modal Image (Image Text) - Same Width as the Image */
#caption {
margin: auto;
display: block;
width: 80%;
max-width: 700px;
text-align: center;
color: #ccc;
padding: 10px 0;
height: 150px;
}
/* Add Animation - Zoom in the Modal */
.modal-content, #caption {
animation-name: zoom;
animation-duration: 0.6s;
}
#keyframes zoom {
from {transform:scale(0)}
to {transform:scale(1)}
}
/* The Close Button */
.close2 {
display: none;
position: absolute;
color: #f1f1f1;
transition: 0.3s;
width: 100%;
height: 100%;
}
.close:hover,
.close:focus {
color: #bbb;
text-decoration: none;
cursor: pointer;
}
HTML:
<div class="container_slideshow">
<div class="content_slideshow">
<!-- Trigger the Modal -->
<img class="slider" id="myImg1" src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/ac/SilburyHill_gobeirne.jpg/1200px-SilburyHill_gobeirne.jpg" alt="">
<!-- The Modal -->
<a class="close">
<div id="myModal1" class="modal">
<!-- Modal Content (The Image) -->
<img class="modal-content" id="img1">
<!-- Modal Caption (Image Text) -->
<div id="caption"></div>
</div>
</a>
</div>
<div class="content_slideshow">
<!-- Trigger the Modal -->
<img class="slider" id="myImg2" src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/ac/SilburyHill_gobeirne.jpg/1200px-SilburyHill_gobeirne.jpg" alt="">
<!-- The Modal -->
<a class="close">
<div id="myModal2" class="modal">
<!-- Modal Content (The Image) -->
<img class="modal-content" id="img2">
<!-- Modal Caption (Image Text) -->
<div id="caption"></div>
</div>
</a>
</div>
</div>
The reason is for (var i = 0; i <= 6; i++) {. The count starts from 0 and it will try to find a dom element with id myModal6.
Change the for loop to
for (var i = 0; i < 6; i++) {
After a very rough look I'd say the DOM node with id "myModal0" doesn't exist (which is most likely true for your other prefixes as well it just happens to be the first you try to get the DOM node of.
Keep in mind that your loop starts at 0 not 1.
Also keep in mind that each node you are trying to assign must exist beforehand! So you either have to have each element in your html file or create them on the fly with JS.
If you wanted to start at 1 you could do:
for (let i=1; i<x; i++) {
// do smth ...
}
It looks like this code:
for (var i = 0; i <= 6; i++) {
modal = document.getElementById(prefixModal + i);
img = document.getElementById(prefixmyImg + i);
modalImg = document.getElementById(prefixmodalImg + i);
// NOTE: put the code that does something IN HERE,
// right now it's outside the loop
}
is iterating through all elements in the HTML document that have ids from "myModal0" through "myModal6", and the same for the other two prefixes "myImg" and "img".
I don't see all these elements in your HTML document. I only see "myModal1" and "myModal2" (as well as elements 1 and 2 of "myImg" and "img".
It looks like you either need to reduce the size of the loop so it only iterates through the elements you actually have, or you need to fill out the rest of the HTML and put in the rest of the elements (all the way from 0 through (and including) 6.
Oh and there's another thing to remember here too, none of your actual code that is causing the error, is inside the loop. All you do in the loop is setting the names of the variables. So the later code is always using "myModal6", because that is the last thing the loop sets the names to.

JavaScript alert box with timer

I want to display the alert box but for a certain interval. Is it possible in JavaScript?
If you want an alert to appear after a certain about time, you can use this code:
setTimeout(function() { alert("my message"); }, time);
If you want an alert to appear and disappear after a specified interval has passed, then you're out of luck. When an alert has fired, the browser stops processing the javascript code until the user clicks "ok". This happens again when a confirm or prompt is shown.
If you want the appear/disappear behavior, then I would recommend using something like jQueryUI's dialog widget. Here's a quick example on how you might use it to achieve that behavior.
var dialog = $(foo).dialog('open');
setTimeout(function() { dialog.dialog('close'); }, time);
May be it's too late but the following code works fine
document.getElementById('alrt').innerHTML='<b>Please wait, Your download will start soon!!!</b>';
setTimeout(function() {document.getElementById('alrt').innerHTML='';},5000);
<div id='alrt' style="fontWeight = 'bold'"></div>
setTimeout( function ( ) { alert( "moo" ); }, 10000 ); //displays msg in 10 seconds
In short, the answer is no. Once you show an alert, confirm, or prompt the script no longer has control until the user returns control by clicking one of the buttons.
To do what you want, you will want to use DOM elements like a div and show, then hide it after a specified time. If you need to be modal (takes over the page, allowing no further action) you will have to do additional work.
You could of course use one of the many "dialog" libraries out there. One that comes to mind right away is the jQuery UI Dialog widget
I finished my time alert with a unwanted effect.... Browsers add stuff to windows. My script is an aptated one and I will show after the following text.
I found a CSS script for popups, which doesn't have unwanted browser stuff. This was written by Prakash:- https://codepen.io/imprakash/pen/GgNMXO. This script I will show after the following text.
This CSS script above looks professional and is alot more tidy. This button could be a clickable company logo image. By suppressing this button/image from running a function, this means you can run this function from inside javascript or call it with CSS, without it being run by clicking it.
This popup alert stays inside the window that popped it up. So if you are a multi-tasker you won't have trouble knowing what alert goes with what window.
The statements above are valid ones.... (Please allow).
How these are achieved will be down to experimentation, as my knowledge of CSS is limited at the moment, but I learn fast.
CSS menus/DHTML use mouseover(valid statement).
I have a CSS menu script of my own which is adapted from 'Javascript for dummies' that pops up a menu alert. This works, but text size is limited. This hides under the top window banner. This could be set to be timed alert. This isn't great, but I will show this after the following text.
The Prakash script above I feel could be the answer if you can adapt it.
Scripts that follow:- My adapted timed window alert, Prakash's CSS popup script, my timed menu alert.
1.
<html>
<head>
<title></title>
<script language="JavaScript">
// Variables
leftposition=screen.width-350
strfiller0='<table border="1" cellspacing="0" width="98%"><tr><td><br>'+'Alert: '+'<br><hr width="98%"><br>'
strfiller1=' This alert is a timed one.'+'<br><br><br></td></tr></table>'
temp=strfiller0+strfiller1
// Javascript
// This code belongs to Stephen Mayes Date: 25/07/2016 time:8:32 am
function preview(){
preWindow= open("", "preWindow","status=no,toolbar=no,menubar=yes,width=350,height=180,left="+leftposition+",top=0");
preWindow.document.open();
preWindow.document.write(temp);
preWindow.document.close();
setTimeout(function(){preWindow.close()},4000);
}
</script>
</head>
<body>
<input type="button" value=" Open " onclick="preview()">
</body>
</html>
2.
<style>
body {
font-family: Arial, sans-serif;
background: url(http://www.shukatsu-note.com/wp-content/uploads/2014/12/computer-564136_1280.jpg) no-repeat;
background-size: cover;
height: 100vh;
}
h1 {
text-align: center;
font-family: Tahoma, Arial, sans-serif;
color: #06D85F;
margin: 80px 0;
}
.box {
width: 40%;
margin: 0 auto;
background: rgba(255,255,255,0.2);
padding: 35px;
border: 2px solid #fff;
border-radius: 20px/50px;
background-clip: padding-box;
text-align: center;
}
.button {
font-size: 1em;
padding: 10px;
color: #fff;
border: 2px solid #06D85F;
border-radius: 20px/50px;
text-decoration: none;
cursor: pointer;
transition: all 0.3s ease-out;
}
.button:hover {
background: #06D85F;
}
.overlay {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
background: rgba(0, 0, 0, 0.7);
transition: opacity 500ms;
visibility: hidden;
opacity: 0;
}
.overlay:target {
visibility: visible;
opacity: 1;
}
.popup {
margin: 70px auto;
padding: 20px;
background: #fff;
border-radius: 5px;
width: 30%;
position: relative;
transition: all 5s ease-in-out;
}
.popup h2 {
margin-top: 0;
color: #333;
font-family: Tahoma, Arial, sans-serif;
}
.popup .close {
position: absolute;
top: 20px;
right: 30px;
transition: all 200ms;
font-size: 30px;
font-weight: bold;
text-decoration: none;
color: #333;
}
.popup .close:hover {
color: #06D85F;
}
.popup .content {
max-height: 30%;
overflow: auto;
}
#media screen and (max-width: 700px){
.box{
width: 70%;
}
.popup{
width: 70%;
}
}
</style>
<script>
// written by Prakash:- https://codepen.io/imprakash/pen/GgNMXO
</script>
<body>
<h1>Popup/Modal Windows without JavaScript</h1>
<div class="box">
<a class="button" href="#popup1">Let me Pop up</a>
</div>
<div id="popup1" class="overlay">
<div class="popup">
<h2>Here i am</h2>
<a class="close" href="#">×</a>
<div class="content">
Thank to pop me out of that button, but now i'm done so you can close this window.
</div>
</div>
</div>
</body>
3.
<HTML>
<HEAD>
<TITLE>Using DHTML to Create Sliding Menus (From JavaScript For Dummies, 4th Edition)</TITLE>
<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
<!-- Hide from older browsers
function displayMenu(currentPosition,nextPosition) {
// Get the menu object located at the currentPosition on the screen
var whichMenu = document.getElementById(currentPosition).style;
if (displayMenu.arguments.length == 1) {
// Only one argument was sent in, so we need to
// figure out the value for "nextPosition"
if (parseInt(whichMenu.top) == -5) {
// Only two values are possible: one for mouseover
// (-5) and one for mouseout (-90). So we want
// to toggle from the existing position to the
// other position: i.e., if the position is -5,
// set nextPosition to -90...
nextPosition = -90;
}
else {
// Otherwise, set nextPosition to -5
nextPosition = -5;
}
}
// Redisplay the menu using the value of "nextPosition"
whichMenu.top = nextPosition + "px";
}
// End hiding-->
</SCRIPT>
<STYLE TYPE="text/css">
<!--
.menu {position:absolute; font:10px arial, helvetica, sans-serif; background-color:#ffffcc; layer-background-color:#ffffcc; top:-90px}
#resMenu {right:10px; width:-130px}
A {text-decoration:none; color:#000000}
A:hover {background-color:pink; color:blue}
-->
</STYLE>
</HEAD>
<BODY BGCOLOR="white">
<div id="resMenu" class="menu" onmouseover="displayMenu('resMenu',-5)" onmouseout="displayMenu('resMenu',-90)"><br />
Alert:<br>
<br>
You pushed that button again... Didn't yeah? <br>
<br>
<br>
<br>
</div>
ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
<input type="button" value="Wake that alert up" onclick="displayMenu('resMenu',-5)">
</BODY>
</HTML>
Pure HTML + CSS 5 seconds alert box using the details element toggling.
details > p {
padding: 1rem;
margin: 0
}
details[open] {
visibility: hidden;
position: fixed;
width: 33%;
transform: translate(calc(50vw - 50%), calc(50vh - 50%));
transform-origin: center center;
outline: 10000px #000000d4 solid;
animation: alertBox 5s;
border: 15px yellow solid
}
details[open] summary::after {
content: '❌';
float: right
}
#keyframes alertBox {
0% { visibility: unset}
100% { visibility: hidden }
}
<details>
<summary>Show the box 5s</summary>
<p>HTML and CSS popup with 5s tempo.</p>
<p><b>Powered by HTML</b></p>
</details>
Nb: the visibility stay hidden at closure, haven't found a way to restore it from CSS, we might have to use js to toggle a class to show it again. If someone find a way with only CSS, please edit this post!!
If you are looking for an alert that dissapears after an interval you could try the jQuery UI Dialog widget.
tooltips can be used as alerts. These can be timed to appear and disappear.
CSS can be used to create tooltips and menus. More info on this can be found in 'Javascript for Dummies'. Sorry about the label of this book... Not infuring anything.
Reading other peoples answers here, I realized the answer to my own thoughts/questions. SetTimeOut could be applied to tooltips. Javascript could trigger them.
by using this code you can set the timer on the alert box , and it will pop up after 10 seconds.
setTimeout(function(){
alert("after 10 sec i will start");
},10000);
You can now use the HTMLDialogElement.
In this example a dialog is created when you click the button, and a timeout function is created to close it:
async function showMessage(message) {
const dialog = document.createElement("dialog");
document.body.appendChild(dialog);
dialog.innerText = message;
dialog.show();
setTimeout(function () {
dialog.close();
}, 1000);
}
<button class="btn" onclick="showMessage('This is my message')">click me!</button>
If you want you can test it on codepen.
function alertWithTimeout(title,message,timeout){
var dialog = $("<div id='dialog-confirm' title='"+title+"'>"+message+"</div>").dialog();
setTimeout(function() { dialog.dialog('close'); }, timeout);
}
alertWithTimeout("Error","This is the message" ,5000);

Categories

Resources