Fetching input box value on submit button click - javascript

I am working on a game using ImpactJS engine and I have created a basic form for my game which contains input box and a submit button. I am able to retrieve values from the input box but what I want is that when the player clicks on submit whatever value is there in the input box gets fetched and I should be able to get that value on Submit click. If the value is null I should get an alert saying "no value or whatever". I want to use this final value and assign it to a variable that I can use in my JavaScript files inside the Impact engine to keep a track of the input from within the game. I am new to HTML, CSS in general so I have no clue how to achieve this.
Below is my HTML/CSS code that has an input box and a submit button.
<!DOCTYPE html>
<html>
<head>
<title>Impact Game</title>
<style type="text/css">
html,body {
background-color: #333;
color: #fff;
font-family: helvetica, arial, sans-serif;
margin: 0;
padding: 0;
font-size: 12pt;
}
#problemform {
display: none;
width: 300px;
height: 100px;
}
#probleminput {
position: absolute;
display: none;
top: 450px;
left: 240px;
height: 50px;
width: 350px;
}
#problemsubmit {
position: absolute;
display: none;
top: 530px;
left: 623px;
height: 40px;
width: 100px;
padding: 5px 10px 8px 2px;
}
#prob_submit_msg {
width: 30%;
margin-left: auto;
margin-right: auto;
text-align: center;
}
#canvaswrapper {
position: relative;
height: 768px;
width: 1024px;
display: block;
margin: auto;
margin-top: 80px;
vertical-align: middle;
}
#canvas {
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
</style>
<script type="text/javascript" src="lib/jquery.min.js"></script>
<script type="text/javascript" src="lib/impact/impact.js"></script>
<script type="text/javascript" src="lib/game/main.js"></script>
</head>
<body>
<div id="canvaswrapper">
<canvas id="canvas" width="1024" height="768"></canvas>
<div id="problemform" class="form-inline">
<input id="probleminput" class="form-inline" type="text" style="display: inline;"></input>
<button id="problemsubmit" class="btn" style="display: inline-block;">Submit</button>
</div>
<div id ="prob_submit_mssg" style="display: block;"></div>
</div>
</body>
</html>
Below is my block of code in ImpactJS in a different JS file to display the input box and submit button using Jquery
ProblemDisplay:function() {
this.setQuestion('This is a title','this is where the body will go and it will be super long and impossible to read or understand.', 'This is a hint');
this.isActive = true;
var form = $("#problemform");
var inputBox = $("#probleminput");
var submitButton = $("#problemsubmit");
form.show();
inputBox.show();
submitButton.show();
},
This is what I have working for now. But now I want the string passed in the input box to be stored in a different variable when clicking the submit button. How to achieve this?
Thanks!

Create an event listener for a click on the submit button.
In jQuery:
$('#submit-button').on('click', function() {
});
In vanilla js
document.getElementById('submit-button').addEventListener('click', function() {
});
Then get the value from the input box:
In jQuery:
$('#submit-button').on('click', function() {
var value = $('input').val();
// Do what you want with the value
});
In vanilla js
document.getElementById('submit-button').addEventListener('click', function() {
var value = document.getElementById('input').value;
// Do what you want with the value
});

Try With this.. :
html:
<input id="probleminput" class="form-inline" type="text" style="display: inline;"> </input>
<button id="problemsubmit" class="btn" style="display: inline-block;">Submit</button>
<a id='testop' ></a>
Js:
var form = $("#problemform");
var inputBox = $("#probleminput");
var submitButton = $("#problemsubmit");
submitButton.click(function(){
var getval = ($("#probleminput").val()?$("#probleminput").val():alert('please fill the text field'))
$('#testop').text(getval);
});
Complete DEMO

If all you need is the value of the input field when someone clicks on the button, then this solution may work for you:
Fiddle Demo
JS:
$('#problemsubmit').on('click', function (event) {
event.preventDefault();
var formInput = $('#probleminput').val();
});

Related

Undo does not work for a replaced content on a div in html

I am trying to create a code that works when you put it on the google search bar, that is a must and i created a div you can edit, also i created a reset button that replaces the content on the div with the default text, but when I try to press ctrl + z it does not go back, and i don't know how to make it work
-I cannot get rid of the: data:text/html, part because it wouldn't work in the search bar for google
-i do have to have all the code types in just one document, because i have to copy paste it all on the google search bar
function reset() {
div_1.innerHTML = '<p> Default text<p>';
}
.div_1 {
display: block;
background-color: rgba(255, 0, 0, 0.5);
height: 80%;
position: relative;
width: 60%;
position-left: 100px;
}
<div contenteditable="true" class="div_1" id="div_1">
<p> Default text<p>
</div>
<button onclick="reset()">reset</button>
function reset() {
div_1.innerHTML = ''; //set the inner HTML to empty string
}
.div_1 {
display: block;
background-color: rgba(255, 0, 0, 0.5);
height: 80%;
position: relative;
width: 60%;
position-left: 100px;
}
<div contenteditable="true" class="div_1" id="div_1">
<p> Default text<p>
</div>
<button onclick="reset()">reset</button>
I think you are trying to make the form empty when you press reset button.
So you have to change the inner HTML to an empty string in order to do that.
I hope it helped
i was able to find an option with the memento pattern and creating an event for the ctrl + z input on the keyboard
function copy(){
inp1.select();
navigator.clipboard.writeText(inp1.value);
ctn.innerHTML = inp1.value;
}
var mementos = [];
function reset() {
mementos.push(document.getElementById('div_1').innerHTML);
div_1.innerHTML= '<p>caller name: </p><p>reason for the call:</p><p>CTN: <div class="ctn" id="ctn"></p><p><br></p><p></p>';
}
document.addEventListener('keydown', function(event) {
if (event.ctrlKey && event.key === 'z') {
var lastMemento = mementos.pop();
div_1.innerHTML = lastMemento;
}
});
function undo() {
var lastMemento = mementos.pop();
div_1.innerHTML = lastMemento;
}
input{
width:200px;
height: 100%;
}
.div_1{
display: block;
background-color:rgba(255, 0, 0, 0.5);
height:400px;
position: relative;
width: 400px;
padding-left: 2px;
}
button{
position: relative;
}
.ctn {
display: inline;
background-color: red;
}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Notes</title>
</head>
<body>
<link rel="stylesheet" href="syles.css">
<input placeholder="(000)-000-0000" maxlength="10" id="inp1">
<button onclick="reset()">reset</button>
<button onclick="copy()">copy</button>
<button onclick="undo()">Undo</button>
<div contenteditable="true"class="div_1" id="div_1">
<p>caller name: </p><p>reason for the call:</p><p>CTN: <div class="ctn" id="ctn"></p><p><br></p><p></p>
</div>
</body>
</html>

href link not working with innerHTML script with "onmouseover change text" and onmouseout

My goal is to have text change onmouseover from "hello" (without a link) to "Google" and provide an 'href' on the resulting "Google" text, and then revert to "hello" onmouseout without a link.
The code below works in changing the text from "hello" to "Google" but,
the link on "Google" does not work (even though I can right-click on "Google" and open the link on another tab)
the text does not change back to "hello" onmouseout.
Thanks for your help in advance!
Here is my code:
<style>
.container {
margin-top: 6vw;
margin-left: 40%;
margin-right: 40%;
}
</style>
<div class="container">
<h1>
<div class="hello" id="hello1" onmouseover="changeText()" onmouseout="changeText(this,'Hello.')">Hello.</div>
</h1>
</div>
<script>
function changeText() {
if (document.getElementById("hello1")) {
a = document.getElementById("hello1")
a.innerHTML = 'Google'
}
}
</script>
try this way onmouseout="this.innerHTML='Hello.';"
function changeText() {
if (document.getElementById("hello1")) {
a = document.getElementById("hello1")
a.innerHTML = 'Google'
}
}
.container {
margin-top: 6vw;
margin-left: 40%;
margin-right: 40%;
}
<div class="container">
<h1>
<div class="hello" id="hello1" onmouseover="changeText()" onmouseout="this.innerHTML='Hello.';">Hello.</div>
</h1>
</div>
By changing a class of a parent tag, any and all child tags can be affected via CSS. Having the HTML ready when the page loads and then hiding it is better than constantly creating and destroying HTML for trivial effects.
The events "mouseenter" and "mouselrave" are handled by a property event handler and an event listener. Either one is sufficient, but avoid using attribute event handlers:
<div onmouselame="lameAttributeEventHandler()">...</div>
Details are commented in the example below
// Reference the <header>
const hdr = document.querySelector('.title');
/* This is a property event handler
// Whenever the mouse enters within the borders of
// the <header>:
// '.google' class is added
// '.hello' class is removed
*/
hdr.onmouseenter = function(event) {
this.classList.add('google');
this.classList.remove('hello');
};
/* This is an even listener
// Whenever the mouse exits the <header> the
// opposite behavior of the previous handler
// happens
*/
hdr.addEventListener("mouseleave", function(event) {
this.classList.add('hello');
this.classList.remove('google');
});
.title {
height: 50px;
margin-top: 3vh;
border: 3px solid black;
text-align: center;
}
h1 {
margin: auto 0;
}
.hello span {
display: inline-block;
}
.hello a {
display: none;
}
.google a {
display: inline-block;
}
.google span {
display: none;
}
<header class="title hello">
<h1>
<span>Hello</span>
Google
</h1>
</header>
You can try this, May it help u to solve the problem
<!DOCTYPE html>
<head>
<title>change text on mouse over and change back on mouse out
</title>
<style>
#box {
float: left;
width: 150px;
height: 150px;
margin-left: 20px;
margin-top: 20px;
padding: 15px;
border: 5px solid black;
}
</style>
</head>
<html>
<body>
<div id="box" onmouseover="changeText('Yes, this is Onmouseover Text')" onmouseout="changeback('any thing')" >
<div id="text-display" >
any thing
</div>
</div>
<script type="text/javascript">
function changeText(text)
{
var display = document.getElementById('text-display');
display.innerHTML = "";
display.innerHTML = text;
}
function changeback(text)
{
var display = document.getElementById('text-display');
display.innerHTML = "";
display.innerHTML = text;
}
</script>
</body>
</html>

Get several JSON object printed to the page

I'm making a site where the user will be able to search for a country and the city or cities in that country will show on the page. I'm able to show one city now for each country but if the country have two or more cities only one of the cities shows. I tried the "+=" to create several cards that will show on the page. That created some issues for me. I'm thinking that I have to use the "appendChild()" function to append each city card to a new div in the DOM. But i'm not 100% sure how to do that, with this code.
If I type in "USA" in the searchfield and USA both have LA and NY as cities. The first one shows now, but I want both to show. I've tried using document.createElement('cityCard') and append cityCard to the container where the cards show. But I did not get it to work as I wanted, I might have done some syntax mistake.
Is this the rigth mindset for this task? Or is it a better way?
Don't mind the CSS, its not done.
Link to a fiddle where all the code is.
https://jsfiddle.net/uzfb852g/12/
added the code under aswell(its the same as in the fiddle)
HTML CODE:
<!DOCTYPE html>
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Martel:400,700,900"
rel="stylesheet">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>FINN DITT FERIESTED!</h1>
<form id="inputForm">
<input type="text" id="sokFelt">
<button id="btn">Search</button>
<button id="allBtn">Alle steder</button>
</form>
<div id="break"></div>
<div id="searchWord"></div>
<div id="cardContainer">
<div id="cityCards">
<h2 id="country"></h2>
<h4 id="city"></h4>
<img id="cityImg">
</div>
</div>
<button id="btnTwo"></button>
<script src="content.js"></script>
</body>
</html>
CSS CODE:
body{
margin: auto;
width: 100%;
height: 100%;
}
h1{
text-align: center;
margin: 25px;
color: tomato;
font-family: 'Martel', serif;
text-shadow: 1px 2px #333;
font-weight: 900;
}
#inputForm{
text-align: center;
margin: 25px;
}
#break{
width: 80%;
margin: auto;
height: 1px;
text-align: center;
background-color: #333;
}
#btn{
padding: 5px 15px;
}
#sokFelt{
padding: 5px 15px;
}
#searchWord{
font-size: 24px;
margin: 40px;
color: #333;
font-weight: bold;
}
#cardContainer{
width: 100%;
margin: auto;
display: flex;
flex-direction: column;
flex-wrap: wrap;
}
#cityCards{
padding: 12px 22px;
background-color: aqua;
border-radius: 5px;
width: 20%;
height: 250px;
}
#cityImg{
width: 100%;
height: 200px;
}
#allBtn{
padding: 5px 15px;
}
JS CODE:
var form = document.getElementById('inputForm');
var input = form.querySelector('input');
var country = document.getElementById("country");
var city = document.getElementById("city");
var cityImg = document.getElementById("cityImg");
var searchWord = document.getElementById("searchWord");
/*IMAGES*/
var place = [
{land: 'Norge', by: 'Oslo', img: 'img/Oslo.jpg'},
{land: 'USA', by: 'Los Angeles', img: "img/LA.jpg"},
{land: 'USA', by: 'New York', img: "img/NewYork.jpg"},
{land: 'Tyskland', by: 'Berlin', img: 'img/berlin.jpg'},
{land: 'Frankrike', by: 'Paris', img:'img/berlin.jpg'}
];
form.addEventListener('submit', (e) => {
e.preventDefault();
for(var i = 0; i < place.length; i += 1){
if(input.value === place[i].land) {
searchWord.innerHTML = input.value;
document.createElement('cityCards');
country.innerHTML = place[i].land;
city.innerHTML = place[i].by;
cityImg.src = place[i].img;
}
}
});
document.getElementById("btnTwo").addEventListener("click", function(){
document.createElement("")
});
Try this to see the problem:
country.innerHTML += place[i].land;
city.innerHTML += place[i].by;
citycards is not an HTML element
You must use an array with divĀ“s (array[i]=document.createElement('div'))
Then create images with img[i] = document.createElement('img')
Set the img.src, and append this with appendChild to cardcontainer.
Using createElement and appendChild would be the right way to go, but you could also use a template tag instead.
Then you could just fill the template with the filtered information and import the template to the DOM.
Here is an example on how this could look like. You may want to take a look at the array function filter, map and forEach.
var form = document.getElementById('inputForm');
var input = form.querySelector('input');
var searchWord = document.getElementById("searchWord");
var template = document.querySelector('#cardContainer');
var getAllBtn = document.getElementById('allBtn');
var place=[{land:"Norge",by:"Oslo",img:"http://www.telegraph.co.uk/travel/destination/article137625.ece/ALTERNATES/w460/oslocityhall.jpg"},{land:"USA",by:"Los Angeles",img:"http://www.zocalopublicsquare.org/wp-content/uploads/2015/10/DistantLASkylineBIG-levinson.jpg"},{land:"USA",by:"New York",img:"https://www.city-journal.org/sites/cj/files/New-York.jpg"},{land:"Tyskland",by:"Berlin",img:"http://www.telegraph.co.uk/content/dam/Travel/Destinations/Europe/Germany/Berlin/Berlin%20cathedral-xlarge.jpg"}];
form.addEventListener('submit', (e) => {
e.preventDefault();
});
getAllBtn.addEventListener("click", function() {
// clear your container div to empty all previous added elements.
searchWord.innerHTML = "";
// filter your place data on the land property of each item.
place.filter( item => item.land === input.value )
// set the img src attr and text content for the elements in the template.
.map( item => {
template.content.getElementById("country").textContent = item.land;
template.content.getElementById("city").textContent = item.by;
template.content.getElementById("cityImg").src = item.img;
return document.importNode(template.content, true);
})
// append them to your container element.
.forEach( item => {
searchWord.appendChild(item)
})
});
body{margin:auto;width:100%;height:100%}h1{text-align:center;margin:25px;color:tomato;font-family:'Martel',serif;text-shadow:1px 2px #333;font-weight:900}#inputForm{text-align:center;margin:25px}#break{width:80%;margin:auto;height:1px;text-align:center;background-color:#333}#btn{padding:5px 15px}#sokFelt{padding:5px 15px}#searchWord{font-size:24px;margin:40px;color:#333;font-weight:700}#cardContainer{width:100%;margin:auto;display:flex;flex-direction:column;flex-wrap:wrap}#cityCards{padding:12px 22px;background-color:aqua;border-radius:5px;width:20%;height:250px}#cityImg{width:100%;height:200px}#allBtn{padding:5px 15px}
<h1>VACATION</h1>
<form id="inputForm">
<input type="text" id="sokFelt">
<button id="btn">Search</button>
<button id="allBtn">All places</button>
</form>
<div id="break"></div>
<div id="searchWord"></div>
<template id="cardContainer">
<div id="cityCards">
<h2 id="country"></h2>
<h4 id="city"></h4>
<img id="cityImg">
</div>
</template>

How to change the background color of an input field when text is entered?

I'm pretty new with Javascript and jQuery, and can't seem to indentify the reason why my code acts like it does.
I have created two seemingly identical functions to change the background color of an input field.
Their goal is to turn the background color of the given input field to the color #00FF7F if anything is typed in the field. And if not, the field should be transparent.
Code JS:
$(document).ready(function () {
var $input1 = $("#logindata1");
var $input2 = $("#logindata2");
function onChangeInput1() {
$input1.css("background-color", "#00FF7F");
var value = $.trim($(".form-control").val());
if (value.length === 0) {
$input1.css("background-color", "transparent");
}
}
function onChangeInput2() {
$input2.css("background-color", "#00FF7F");
var value = $.trim($(".form-control").val());
if (value.length === 0) {
$input2.css("#background-color", "transparent");
}
}
$input1.on("keyup", onChangeInput1);
$input2.on("keyup", onChangeInput2);
});
css:
#loginbox {
width: 400px;
height: 200px;
margin-left: auto;
margin-right: auto;
margin-top: 25%;
}
.logindata {
margin-left: auto;
margin-right: auto;
margin-top: 20px;
height: 60px;
width: 290px;
transition: 0.25s ease;
}
.form-control {
margin-left: auto;
margin-right: auto;
height: 55px;
width: 288px;
border-style: none;
background-color: transparent;
text-align: center;
border: solid 2px #00FF7F;
transition: 0.25s ease;
font-size: 25px;
font-family: "Trebuchet MS";
}
.form-control:hover {
box-shadow: 0px 0px 30px #2E8B57;
}
::-webkit-input-placeholder {
color: #00FF7F;
}
Simple HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Test</title>
<!-- Stylesheet link -->
<link rel="stylesheet" type="text/css" href="assets/style.css">
<!-- jQuery link -->
<script type="text/javascript" src="assets/vendor/jquery-3.1.0.min.js"></script>
</head>
<body>
<div id="loginbox">
<div class="logindata" id="logindata1">
<input type="text" class="form-control" placeholder="Username">
</div>
<div class="logindata" id="logindata2">
<input type="password" class="form-control" placeholder="Password">
</div>
</div>
<!-- Javascript link-->
<script type="text/javascript" src="assets/js/javascript.js"></script>
</body>
On the jsbin above, try typing in both the Username and Password field to see how they react differently.
Images of what happens. Didn't want to include all images here:
http://imgur.com/a/qgubP
I realize there probably is a way to compromise my js/jquery into 1 function that each input field calls instead of have a function for each.
If both of these fields are required, here's a much simpler solution using CSS only.
Add the attribute required to your <input> tags and then use the pseudo-class :valid.
.form-control:valid {
background-color: #00FF7F;
}
Code snippet:
#loginbox {
width: 400px;
height: 200px;
margin-left: auto;
margin-right: auto;
margin-top: 25%;
}
.logindata {
margin-left: auto;
margin-right: auto;
margin-top: 20px;
height: 60px;
width: 290px;
transition: 0.25s ease;
}
.form-control {
margin-left: auto;
margin-right: auto;
height: 55px;
width: 288px;
border-style: none;
background-color: transparent;
text-align: center;
border: solid 2px #00FF7F;
transition: 0.25s ease;
font-size: 25px;
font-family: "Trebuchet MS";
}
.form-control:hover {
box-shadow: 0px 0px 30px #2E8B57;
}
::-webkit-input-placeholder {
color: #00FF7F;
}
.form-control:valid {
background-color: #00FF7F;
}
<div id="loginbox">
<div class="logindata" id="logindata1">
<input type="text" class="form-control" placeholder="Username" required>
</div>
<div class="logindata" id="logindata2">
<input type="password" class="form-control" placeholder="Password" required>
</div>
</div>
jsFiddle : https://jsfiddle.net/7vzjz2u5/3/
jQuery
$(document).ready(function() {
$('.change-background').on('change', function() {
var $this = $(this);
var value = $.trim($this.val());
// toggleClass can be provided a bool value,
// If we provide true we add class, if false we remove class
$this.toggleClass('filled-background', value.length !== 0);
}).change();
// We also want to call a 'change' event on
// all inputs with the change-background class just incase the page has
// pre-filled in values
});
Instead of listening for the keyup event and then running a function, just create a listener on the change event, also if we just apply one class to all inputs we want the background colour to change on, we can just create one listener which will do it for any input with the class change-background.
Html
<div id="loginbox">
<div class="logindata" id="logindata1">
<input type="text" class="change-background form-control" placeholder="Username">
</div>
<div class="logindata" id="logindata2">
<input type="password" class="change-background form-control" placeholder="Password">
</div>
</div>
Css (the extra class for background color)
.filled-background {
background-color: #00FF7F;
}
Also side note
listening for keyup is back, someone may want to copy and paste their username and password and if they do this it won't trigger an keyup event if they use right click and paste.
Your code clears the background color when the length is 0. The way it checks the length is with this snippet of code:
var value = $.trim($(".form-control").val());
The selector $(".form-control") will select all elements with the CSS class of .form-control. This is a problem because there is more than one of them; in this case, it will always return the value from the first element found.
You should change the code to check for the specific control by searching by ID, like so:
var value = $.trim($("#logindata1 input").val()); //get user ID
var value = $.trim($("#logindata2 input").val()); //get password
You have some minor mistakes, but no worry. We can fix it.
First Problem
Other answers are pointing something important: you are trying to get the value selecting all elements with form-control class.
var value = $.trim($(".form-control").val());
You can do it, replacing your selector by your already declared variables $input1 and $input2. This way:
var value = $.trim($input1.val());
var value = $.trim($input2.val());
Second
Ok. First problem solved. The second problem is in your second function. You trying to set an invalid css: $input2.css("#background-color", "transparent");
When should be: $input2.css("background-color", "transparent"); (without #).
Next One
Nice. Next one. The id's you are setting logindata1 and logindata2 are on your divs. So, you are wrongly trying to get the value of the div instead the value of the input. you can fix your selector by appending input, this way:
var $input1 = $("#logindata1 input");
var $input2 = $("#logindata2 input");
Finally
So, finally, it should work:
$(document).ready(function () {
var $input1 = $("#logindata1 input");
var $input2 = $("#logindata2 input");
function onChangeInput1() {
$input1.css("background-color", "#00007F");
var value = $.trim($input1.val());
if (value.length === 0) {
$input1.css("background-color", "transparent");
}
}
function onChangeInput2() {
$input2.css("background-color", "#00007F");
var value = $.trim($input2.val());
if (value.length === 0) {
$input2.css("background-color", "transparent");
}
}
$input1.on("keyup", onChangeInput1);
$input2.on("keyup", onChangeInput2);
});
Your value check is not right. With your jQuery, you are checking the value of both inputs every time.
Try checking the single inputs that you are interested in instead.
$(document).ready(function () {
var $input1 = $("#logindata1");
var $input2 = $("#logindata2");
function onChangeInput1() {
$input1.css("background-color", "#00FF7F");
var value = $.trim($input1.val());
if (value.length === 0) {
$input1.css("background-color", "transparent");
}
}
function onChangeInput2() {
$input2.css("background-color", "#00FF7F");
var value = $.trim($input2.val());
if (value.length === 0) {
$input2.css("#background-color", "transparent");
}
}
$input1.on("keyup", onChangeInput1);
$input2.on("keyup", onChangeInput2);
});

JavaScript: any tips on improving this code on opening/closing menu?

I've been lurking w3schools for some time and studying javaScript. I've struggled for a few days with a code of which the function is to open and then close the opened menu on click again. I couldn't do this with a single , but I've managed to it with two.
I've managed to do this with the following method:
<div id="menuClosed" style="background: blue; color: white; width: 500px; height: 50px; transition: 0.3s">
<p id="menuString" style="margin: auto; text-align:center;">
Click on the button to open the menu
</p>
<button id="menuButton" onclick="changeStyle('Closed')" style="margin-left:250px;">Open</button>
<div>
<p style="font-size: 30px; text-align:center;">Bonefish</p>
</div>
<button id="menuButton2" onclick="changeStyle('Open')" style = "margin-left:250px; display: none;">Close</button>
</div>
<script>
function changeStyle(idMenu) {
//compresses OPEN and CLOSE buttons ID into a var
var menuButton = document.getElementById("menuButton");
var menuBotton2 = document.getElementById("menuButton2");
//Compresses menu DIV's ID into a var
var menuConfig = document.getElementById("menu" + idMenu);
//styles that will serve as factor for opening/closing the menu
var style1 = "background: blue; color: white; width: 500px; height: 50px; transition: 0.3s";
var style2 = "background: blue; color: white; width: 500px; height: 150px; transition: 0.3s";
//opens Menu and changes ID to "menuOpen"
if (idMenu === "Closed") {
menuConfig.style = style2;
menuConfig.id = "menuOpen";
menuButton.style = "display: none; margin-left:250px;";
menuButton2.style = "margin-left:250px; display: initial;"
}
//Closes menu and chages ID to "menuClosed"
if (idMenu === "Open") {
menuConfig.style = style1;
menuConfig.id = "menuClosed";
menuButton.style = "display: initial; margin-left:250px;";
menuButton2.style = "margin-left:250px; display: none;";
}
}
</script>
What I actually wanted to do, is to be able to both open and close the menu with the same button, but I can't figure out how.
I believe it can be done through changing <button id="menuButton" onclick="changeStyle('Closed')" style="margin-left:250px;">Open</button> changeStyle('Closed') into changeStyle('Open') and making necessary adjustments, but, again, my tries on that have failed.
Thanks by advance.
If you could use jQuery and some css, it you'll get what you want
UPDATED WITH JAVASCRIPT
var divmenu=document.getElementById('menu');
function toggleMenu(btn){
if(btn.className=='open'){
btn.className='close';
divmenu.className='close';
btn.innerText='Open';
}else{
btn.className='open';
divmenu.className='open';
btn.innerText='Close';
}
}
div{
padding:10px 0;
color: white;
transition: 0.3s;
background: blue;
}
div.open{
height: 150px;
}
div.close{
height: 20px;
overflow:hidden;
}
<div id="menu" class="close">
<p id="menuString" style="margin: auto; text-align:center;">
Click on the button to open the menu
</p>
<p style="font-size: 30px; text-align:center;">Bonefish</p>
</div>
<p style="text-align:center; margin:0; padding:5px 0;"><button type="button" class="close" onclick="toggleMenu(this);">Open</button></p>

Categories