Quick / Basic Question - Hide/Show Toggle (Java Script) - javascript

I have a basic question that I think somebody may easily be able to answer. I have very little coding experience but just need one simple change to complete website I am making,.
I have a simple toggle similar to this example I have used. :
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
</style>
</head>
<body>
<text onclick="myFunction()">Try it</text>
<div id="myDIV">
This is my DIV element.
</div>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
</body>
</html>
I would like the #myDIV to disappear when clicking outside the div/container as well as disappear when clicking on the "Try it" text/button. I guess I must edit the script. I have tried for a few hours but no luck.
Could somebody help me with this? Sorry if silly / basic question.

You should get the general DOM and inverse the function like: if div clicked, display block else display none.

Add a hide class to hide myDIV. It would make it much easier JS-wise to hide and show the div. Then, let the window handle the clicks rather than the button:
var x = document.getElementById("myDIV");
var y = document.getElementById("myBtn")
window.addEventListener("click", function(e) {
if(e.target != x && e.target != y) {
x.classList.add("hide");
} else if(e.target == y) {
x.classList.toggle("hide");
}
});
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
#myDIV.hide {
display: none;
}
<text id="myBtn">Try it</text>
<div id="myDIV">
This is my DIV element.
</div>

Check out this snippet, I feel this solves your usecase.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
</style>
</head>
<body>
<text onclick="myFunction()">Try it</text>
<div id="myDIV">
This is my DIV element.
</div>
<script>
window.onload = function () {
var x = document.getElementById("myDIV");
x.style.display = "none"
document.onclick = function (e) {
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
};
};
</script>
</body>
</html>

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
/*display: none;*/
}
</style>
</head>
<body>
<text onclick="myFunction()">Try it</text>
<!--you have to add display property and the default value of it will be none-->
<!--you can add this to the style directly-->
<div id="myDIV" style="display: none">
This is my DIV element.
<!--for adding a link you have to use like this-->
Hello google
</div>
<script>
function myFunction() {
const x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
// this event will run when your left mouse down
document.addEventListener("mousedown", (event) => {
// check if the event target is not the element with id of [myDIV]
// check if the event target is not the element with id of [link] cus when you click on the link the target will be link element
if (event.target.id !== "myDIV" && event.target.id !== "link") {
const x = document.getElementById("myDIV");
x.style.display = "none";
}
});
</script>
</body>
</html>

Related

How to generate multiple div at random position inside a parent div using Javascript?

I am actually trying to create a game when someone hover on the gray area then it will ask if he wants to play if he confirm then random 5 div will appear in some different area of that parent div.
at first there should be only 1 big div. when someone will hover a mouse there will be option if he wants to play the game. then the big div will generate 5 small divs inside it. ( next i have delete if someone click small divs and need to track point, so its a small game for just my learning perpose
but i stuck here because i can't generate divs in random position. if you run my code you will see 3 divs verticaly appear when you confirm to play
function hoverinside(x) {
let answer = confirm("Do you want to play the game?");
if (answer == true) {
alert("Enjoy the game");
myFunction();
}
else {
alert("If you want to play just hover on the gray area again");
location.reload();
}
}
function myFunction() {
var element = document.createElement('div');
element.style.cssText = "width:55px; height:55px; background:green;";
document.body.appendChild(element);
var div1 = document.getElementById("square");
div1.insertBefore(element, div1.childNodes[5])
var element2 = document.createElement('div');
element2.style.cssText = "width:55px; height:55px; background:yellow;"
document.body.appendChild(element2);
var div2 = document.getElementById("square");
div2.insertBefore(element2, div2.childNodes[5])
var element3 = document.createElement('div');
element3.style.cssText = "width:55px; height:55px; background:red;";
document.body.appendChild(element3);
var div3 = document.getElementById("square");
div3.insertBefore(element3, div3.childNodes[5])
}
function removediv1() {
var element = document.getElementById("div2");
element.classList.remove("div2");
}
h1 {
font-style: bold;
color: brown;
}
#square{
height: 350px;
width: 700px;
background-color: rgb(170, 168, 168);
border: brown;
border-style: solid;
}
#square1{
height: 35px;
width: 70px;
background-color: rgb(245, 10, 10);
}
<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 href="style.css" rel="stylesheet" type="text/css">
<script src="gamejs.js"></script>
<title>Game</title>
</head>
<body onload=OpenInNewtab(google.com)>
<h1>Game:</h1>
<p>we will create the game over here. no problem just wait and chill and play with us.we will create the game over here. no problem just wait and chill and play with us.</p>
<h1>Points:</h1>
<br>
<div id="square" onmouseover="hoverinside(this)" >
<div id="child1"> </div>
</div>
</body>
</html>
this is my code
You can do something like this.
Steps
Create a child div
Add id to itnot necessay.
For distinguishing, add different colors
Make the child div as absolute
Add random left & right position styling to Child Div (This will assure the randomness)
Updated the code, so that child div be be confined inside parent div.
You can refer to this codepen: https://codepen.io/hackhimanshu1024/pen/JjrjOjK
Note: I am not adding hover and deleting events. You can handle it as per your code.
Note: Add other styles as per your requirements.
const parentBody = document.getElementById("root");
const btn1 = document.getElementById("btn1");
const btn2 = document.getElementById("btn2");
let i = 0, interval
function addDiv(cnt = 5) {
const div = document.createElement('div');
div.id = 'div';
div.style.top = `${Math.random() * 100}%`;
div.style.left = `${Math.random() * 100}%`;
div.style.backgroundColor = `rgb(${Math.random() * 100},${Math.random() * 100},${Math.random() * 100})`;
parentBody.appendChild(div);
i++;
if (i === cnt) clearInterval(interval);
}
function intervalDiv(){
i=0;
interval = setInterval(addDiv, 1000);
}
function multipleDiv(){
i=0;
while(i<5){
addDiv();
}
}
btn1.addEventListener('click', intervalDiv);
btn2.addEventListener('click', multipleDiv);
*{
box-sizing: border-box;
padding:0;
margin:0;
}
body{
height:100vh;
max-height:100vh;
max-width:100vw;
padding: 100px;
}
#root{
height:100%;
max-height:100%;
position: relative;
}
#btn1, #btn2{
position:relative;
z-index:200;
}
#div {
width: 200px;
height: 200px;
position: absolute;
transform: translate(-50%,-50%);
}
<html>
<body>
<div id="root">
<button id="btn1">CLICK ME on Interval</button>
<button id="btn2">CLICK ME for 5 times</button>
</div>
</body>
</html>

Need help making an image appear on click

I am making a thing where when you click on the hidden image it appears. Every time that I do it, though, the image just stays hidden. I know that I am actually clicking the image because I made it so that it follows under my cursor. It also works in reverse. If the image is visible and I click on it it turns invisible.
Here is my HTML:
document.addEventListener('mousemove', function(e) {
let body = document.querySelector('body');
let boom = document.getElementById('boom');
let left = e.pageX;
let top = e.pageY;
boom.style.left = left + 'px';
boom.style.top = top + 'px';
});
function animation(){
var boom = document.getElementById("boom");
boom.style.display = "none";
document.getElementById("boom").src = "file:///C:/Users/domin/Desktop/Atom/rootfolder/Boom%20Salamon/Salamon.png";
}
body {
background-color: #000000;
}
header {
background: grey;
padding: 10px;
margin: 0px;
font-size: 13px
}
#boom{
display: block;
position: absolute;
transform: translate(-50%,-50%);
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
<title>Boom! Salamon</title>
</head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body>
<header>
<h2 style="color: white; text-align: center">Boom! Salamon.<br>Click in the area below to witness the magic!</h2>
</header>
<img onclick='animation()' id="boom" src='file:///C:/Users/domin/Desktop/Atom/rootfolder/Boom%20Salamon/Boom!.png' height="250" width="250"></img>
<script src="app.js"></script>
</body>
</html>
What's happening?
yes as #Abin mentioned you have not added any code to unhide it I have modified your
html and js file to add this functionality like when you click on text it will be visible again.
Note: i have added that visible condition on click of header text but you can define it anywhere.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="Styles.css">
<title>Boom! Salamon</title>
</head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body>
<header>
<h2 id='clickme' style="color: white; text-align: center">Boom! Salamon.<br>Click here to witness the magic!</h2>
</header>
<img onclick='animation()' id="boom" src='file:///C:/Users/domin/Desktop/Atom/rootfolder/Boom%20Salamon/Boom!.png' height="250" width="250"></img>
<script src="app.js"></script>
</body>
</html>
app.js
document.addEventListener('mousemove', function(e) {
let body = document.querySelector('body');
let boom = document.getElementById('boom');
let left = e.pageX;
let top = e.pageY;
boom.style.left = left + 'px';
boom.style.top = top + 'px';
});
function animation(){
var boom = document.getElementById("boom");
boom.style.visibility = 'hidden';
document.getElementById("boom").src = 'file:///C:/Users/domin/Desktop/Atom/rootfolder/Boom%20Salamon/Salamon.png';
}
document.getElementById("clickme").onclick = function() {
boom.style.visibility = 'visible';
}
in above i have used pure js.
There was nothing in the code you have provided to unhide the image, I have added a sample code that works as per your req. Click on the text, and the image will appear on the bottom.
/* document.addEventListener('mousemove', function(e) {
let body = document.querySelector('body');
let boom = document.getElementById('boom');
let left = e.pageX;
let top = e.pageY;
boom.style.left = left + 'px';
boom.style.top = top + 'px';
});
*/
var clickEl = document.getElementById('click-el')
clickEl.addEventListener('click', function(){
var imgEl = document.getElementById('boom');
imgEl.style.display = 'block';
})
/*
function animation(){
var boom = document.getElementById("boom");
boom.style.display = "none";
document.getElementById("boom").src = "file:///C:/Users/domin/Desktop/Atom/rootfolder/Boom%20Salamon/Salamon.png";
} */
body {
background-color: #000000;
}
header {
background: grey;
padding: 10px;
margin: 0px;
font-size: 13px
}
#boom{
display: none;
}
<header>
<h2 id='click-el' style="color: white; text-align: center">Boom! Salamon.<br>Click here to witness the magic!</h2>
</header>
<img onclick='animation()' id="boom" src='https://static.remove.bg/sample-gallery/graphics/bird-thumbnail.jpg' height="250" width="250"/>

Why do I need to press the button 2 times to make this function work? [duplicate]

This question already has answers here:
Why do I have to click this input button twice to call a function?
(4 answers)
Closed 1 year ago.
Below I have 2 pieces of code. The purpose of the code is to alternate between showing and hiding an element by clicking on the button.
Logically, I feel both pieces of code are sound and should work in exactly the same way. However, #1 functions as required whilst #2 doesn't. #2 requires 2 presses of the button to first display the element. After that, it functions as required.
I assume I have made a mistake linked to nomenclature, but I am unable to pinpoint it. Please help in doing so.
#1
<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
visibility: hidden;
}
</style>
</head>
<body>
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.visibility === "hidden") {
x.style.visibility = "visible";
} else {
x.style.visibility = "hidden";
}
}
</script>
</body>
</html>
#2
<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
visibility: hidden;
}
</style>
</head>
<body>
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.visibility === "visible") {
x.style.visibility = "hidden";
} else {
x.style.visibility = "visible";
}
}
</script>
</body>
</html>
That's happening because the x.style returns inline style for an element (the value sets on the div tag <div id="myDIV" style="/*this value*/"> and not the overall element styling) which is empty by default , think of it as any other HTML attributes like id or width.
So what you want to do, is to declare the visibility propriety inside the div like so :
<div id="myDIV" style="visibility: hidden;">
this way x.style.visibility will return 'hidden' from the first time.
Here are two snippets so you see the difference:
The same as your code just added a console.log
<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
visibility: hidden;
}
</style>
</head>
<body>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
console.log('x.style.visibility = '+x.style.visibility);
if (x.style.visibility === "hidden") {
x.style.visibility = "visible";
} else {
x.style.visibility = "hidden";
}
}
</script>
<div id="myDIV">
This is my DIV element.
</div>
</body>
</html>
and now if we set visibility as an inline style
<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
</style>
</head>
<body>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
console.log('x.style.visibility = '+x.style.visibility);
if (x.style.visibility === "hidden") {
x.style.visibility = "visible";
} else {
x.style.visibility = "hidden";
}
}
</script>
<div id="myDIV" style="visibility: hidden;">
This is my DIV element.
</div>
</body>
</html>
account for starting condition
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.visibility === "hidden" || !x.style) {
x.style.visibility = "visible";
} else {
x.style.visibility = "hidden";
}
}

Javascript: Make a div visible/invisible based on page title

This is the code I have currently come up with. It fills in the correct title, but the page does not become visible on having a page title match. How do I go about fixing this? What is the proper way of "if page title, execute this code"?
<head>
<title>Page Name 1</title>
</head>
<body>
<style>
#notavailablemsg {
font-size: 30px;
color: #f04e37;
display: inline;
}
#notavailablemsg div {
display: inline;
visibility: hidden;
}
#submsg {
font-size: 22px;
visibility: hidden;
}
#pagename {
font-style: italic;
}
</style>
<center>
<div id="notavailablemsg">
<div>The page </div>
<br>
<div id="pagename">page title</div>
<div> no longer exists</div>
</div>
<div id="submsg">
We are sorry for the inconvenience.
</div>
</center>
<script>
var errortitle = document.getElementsByTagName("title")[0].innerHTML;
document.getElementById("pagename").innerHTML = errortitle;
</script>
<script>
if (errortitle == "Page Name 1") {
document.getElementByID("notavailablemsg").innerHTML.style.visibility = "visible";
document.getElementByID("submsg").innerHTML.style.visibility = "visible";
}
</script>
</body>
</html>
#Midas answered: Modify to
document.getElementById("notavailablemsg").style.visibility = "visible";
document.getElementById("submsg").style.visibility = "visible";
You can use document.title to get current title.
Example
<!DOCTYPE html>
<html>
<head>
<title>YourGoodTitle</title>
<style>
div {
border: 1px solid red;
width: 100%;
height: 50px;
display: none; /* its good to use display: none to hide elements*/
}
</style>
</head>
<body onload="myFunction()">
<h1>Hello World!</h1>
<center>
<div id="notavailablemsg">
Bad title
</div>
<div id="availablemsg">
Glad you are here
</div>
</center>
<script>
function myFunction() {
var title = document.title;
if( title == "YourGoodTitle" ) {
// select and make elements visible
document.getElementById( "availablemsg" ).style.display = "block";
} else {
// hide the elements you want, make their display = none;
// for example
document.getElementById( "availablemsg" ).style.display = "none";
// show your expected elements
document.getElementById( "notavailablemsg" ).style.display = "block";
}
}
</script>
</body>
</html>
https://plnkr.co/edit/KS2obzXrUqtzT8FWUvwL?p=preview
So if your title is YourGoodTitle, YourGoodTitle message will be shown. Else Bad title will be printed

Animation without jquery, slide left and right

I am trying to slide a div to the left when I show it and slide it to the right when I hide it, but I don't want to use jQuery. Is there a way to do simple animation and support IE7 and IE8 without using a javascript library?
Here is my show/hide js:
function showHide() {
var Elliot = document.getElementById('Daniel').style.display;
if (Elliot == "block") {
document.getElementById('Daniel').style.display = "none";
} else {
document.getElementById('Daniel').style.display = "block";
};
};
HTML would look like:
click me
<div id="Daniel" style="display:block; width: 300px; height: 50px;">
<!-- some stuff -->
</div>
Below is a function that can get you started:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<style>
#yea {
margin-left: 100px;
height: 100px;
width: 100px;
background: blue;
border: 1px black solid;
}
</style>
</head>
<body>
<div id='yea'></div>
<input type="button" value="Capacity Chart" onclick="animateMe();" >
<script>
function animateLeft(obj, from, to){
if(from >= to){
obj.style.visibility = 'hidden';
return;
}
else {
var box = obj;
box.style.marginLeft = from + "px";
setTimeout(function(){
animateLeft(obj, from + 1, to);
}, 25)
}
}
function animateMe() {
animateLeft(document.getElementById('yea'), 100, 700);
}
</script>
</body>
</html>
https://jsfiddle.net/geh7ewLx/

Categories

Resources