Toggle menu using jQuery to show and hide options

I'm currently working on a menu that should open when the button is clicked once and close when clicked again. I had done this before but I seem to have forgotten how to achieve it. Here is the code snippet that I tried to use:

var main = function(){
$('#menuopen').click(function(){
$('.leftbox').show();
$('.leftbox').animate({left: "0"});
$('.topbox').animate({left: "15%", width: "85%"});
},
function(){
$('.leftbox').animate({left: "-15%"});
$('.leftbox').hide();
$('.topbox').animate({left: "0", width: "100%"});
}
);
}

$(document).ready(main);
body {
background-color: #CCCCCC;
}

h2{
text-align: center;
font-family: 'Lato', sans-serif;
}

.topbox{
position: absolute;
top: 0%;
left: 0%;
width: 100%;
height: 10%;
background-color: #006699;
}

.leftbox{
display: none;
position: absolute;
background-color: #FFFFFF;
top: 0px;
left: -15%;
width: 15%;
height: 100%;
box-shadow: 10px 67px 5px #888888;
}

#commentbox{
position: absolute;
top: 87%;
left: 30%;
width: 50%;
resize: none;
border-radius: 5px;
outline: none;
box-shadow: 10px 10px 10px #888888;
}

#submitbox{
position: absolute;
background-color: #006699;
left: 82%;
top: 87%;
height: 66px;
width: 132px;
border-radius: 5px;
border: 0px;
outline: none;
box-shadow: 10px 10px 10px #888888;
font-family: 'Lato', sans-serif;
font-weight:;
}

#menuopen{
position: absolute;
top: 25%;
left: 15px;
height: 32px;
width: 32px;
}
<!DOCTYPE html>
<html>
<head>
<link href='http://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="topbox">
<h2> Lobby </h2>
<img id="menuopen" src="menu_icon.png"/>
</div>
<div class="leftbox">
</div>
<div class="inputbox">
<textarea placeholder="Enter your comment!" id="commentbox" rows="4" cols="50"></textarea>
<input id="submitbox" type="submit" value="Submit">
</div>
</body>
</html>

Can anyone point out what might be the issue with this code? Is the jQuery implementation correct? :O

Answer №1

While your code is almost right, consider setting a variable such as var isOpen = false;. Then, when the user clicks the button, perform a check like this:

if(isOpen == false){ perform opening })
. Otherwise, perform closing . This is necessary because jQuery may not be aware of the current state of the element, so manual checks are required.

Answer №2

Looks like @George was faster, but here's another approach: create a state variable called opened that toggles with each click event:

var main = function(){
   var opened = false;
$('#menuopen').click(function(){
        if (opened) {
  $('.leftbox').animate({left: "-15%"});
  $('.leftbox').hide();
  $('.topbox').animate({left: "0", width: "100%"});
        } else {
  $('.leftbox').show();
  $('.leftbox').animate({left: "0"});
  $('.topbox').animate({left: "15%", width: "85%"});
       }
       opened = !opened;
});
}

$(document).ready(main);
body {
background-color: #CCCCCC;
}

h2{
text-align: center;
font-family: 'Lato', sans-serif;
}

.topbox{
position: absolute;
top: 0%;
left: 0%;
width: 100%;
height: 10%;
background-color: #006699;
}

.leftbox{
display: none;
position: absolute;
background-color: #FFFFFF;
top: 0px;
left: -15%;
width: 15%;
height: 100%;
box-shadow: 10px 67px 5px #888888;
}

#commentbox{
position: absolute;
top: 87%;
left: 30%;
width: 50%;
resize: none;
border-radius: 5px;
outline: none;
box-shadow: 10px 10px 10px #888888;
}

#submitbox{
position: absolute;
background-color: #006699;
left: 82%;
top: 87%;
height: 66px;
width: 132px;
border-radius: 5px;
border: 0px;
outline: none;
box-shadow: 10px 10px 10px #888888;
font-family: 'Lato', sans-serif;
font-weight:;
}

#menuopen{
position: absolute;
top: 25%;
left: 15px;
height: 32px;
width: 32px;
}
<!DOCTYPE html>
<html>
<head>
<link href='http://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="topbox">
<h2> Name's Lobby </h2>
<img id="menuopen" src="menu_icon.png"/>
</div>
<div class="leftbox">
</div>
<div class="inputbox">
<textarea placeholder="Enter your comment!" id="commentbox" rows="4" cols="50"></textarea>
<input id="submitbox" type="submit" value="Submit">
</div>
</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with HTML on Eclipse for Android development?

There seems to be an issue with the HTML code in this program. When attempting to use x or any other HTML code, it does not format correctly. This is unusual as HTML has worked in the past. The problem occurs with the first string array and not with the ...

How to Use CSS to Copy a Style Path and Conceal an Element within an iFrame

My goal is to adjust a division by including a width element in its CSS properties. I have attempted to use Chrome and Firebug to copy the CSS path, but it seems that the result is incorrect. After inserting it into my style.css file, the division remains ...

Trouble Deciphering JSON Array Using Eval Function

I'm facing an issue with two files in my project - one is a PHP file containing an array that is echoed using json_encode, and the other is a JavaScript file containing various functions for a webpage. One particular function in the JavaScript file is ...

align-content and justify-content in flexbox are not producing the desired results

align-content and justify-content don't appear to be working when I test them in both Chrome and Firefox. I'm puzzled as to why they're not functioning as expected. #container { display: flex; flex-wrap: wrap; justify-content: cent ...

The pop-up menu appears in a location different from where the anchor element is positioned

Having an issue with the menu placement when clicking on an Avatar. The menu is appearing in the wrong position: https://i.sstatic.net/955eJ.png The avatar button "OB" on the right side is where the issue occurs. No console errors present and inspecting ...

How can the WordPress Gutenberg Popover be positioned to follow the cursor?

I have a component called Popover that I want to position at the cursor's location. For instance, in a component called RichText, if the user's cursor is at the beginning, middle, or end of a sentence, the Popover should appear depending on the c ...

Is it possible to fill dropdown menus on a webpage using jQuery or JavaScript without the need for an ajax call?

Currently, I am looking to populate multiple dropdown lists using jQuery when the page loads rather than relying on ajax responses to events. My Controller is responsible for creating several List objects that will be used for these dropdowns. Right now, I ...

What is the best way to create an onwheel event that produces an up and down effect using JavaScript?

Looking for a way to trigger a function or loop when scrolling up or down using the onwheel event. Check out the code snippet below: let demo = document.querySelector('#demo'); let c = 0; window.onwheel = function() { c ++; demo.innerHTML ...

Struggling to get the findAndModify or Update functions to work properly in MongoDB. Despite fetching the desired data from my ajax call, I am unable to make any changes in the database

Here is the ajax code snippet: $(function () { $("#upvoteClick").click(function () { $.ajax({ type:"POST", data: {upvote: 2}, dataType: 'json', url:"http://localhost:9000/api/upvote" }).success(functi ...

Deactivate the Mention and Hash tag in ngx-linkifyjs

I am currently utilizing ngx-linkifyjs to automatically convert URLs in text to clickable hyperlinks. However, I am facing an issue where it is also converting # and @ tags into links. Is there a way to prevent the conversion of # and @ while maintain ...

Unable to update state in my React app when clicking on a button

There is a requirement for a button click to filter the job-card array by one specific category. For example, clicking on the button "Marketing" should only show jobs from the array that have the property "jobstags: Marketing". I followed a similar procedu ...

Ways to conceal the TippyJS tooltip so it doesn't show up on video embeds

My website has tooltips enabled, but I am looking to hide the tooltip pop-ups that appear specifically over youtube video embeds. Upon inspecting the webpage, I found the code snippet below that is associated with youtube videos: <div data-tippy-root id ...

What is the best way to send AJAX post data to a Node.js server?

I am currently facing an issue with passing a unique ID object back to the server side using Ajax after making an API call. I need help figuring out what might be going wrong in my code. This is the client side code snippet where I loop through a JavaScri ...

Preserve the output from the jQuery ajax request

I have created a custom function that calls an ajax request and saves the response data to a variable before returning it. It always shows '0' as the return value, but the alert displays numbers like 3712. Below is the implementation of the func ...

Adding an existing element to the DOM using Javascript/jQuery

I am facing an issue in my DOM where I have an element with two children, a div block and a button. My goal is to add a new copy of the same div block to the parentNode whenever the button is clicked. Currently, I am using the following code in the button ...

how to adjust the width of table columns dynamically using ng-repeat and AngularJS

Working on a user interface that contains a table where the column widths adjust according to percentage data. I'm using ng-repeat to populate the table, but need help setting unique widths for each piece of data received. Here's some of my Angul ...

Transferring Data Between Two Modals

Currently working on developing an approval/edit process for the company website. The setup involves a jquery datatable that showcases scheduled events specific to the logged-in user in a particular format. results = await response.json(); var tr = $(this) ...

Single jQuery scrolling loader malfunctioning in WebKit browser

I've been conducting an interesting experiment in which new entries are dynamically loaded onto a page as you scroll down. Check out a practical demonstration here. In Firefox, everything seems to be working perfectly. However, when viewed in WebKit ...

Increment counter when a key is pressed in Angular 4 and decrement when the backspace key is pressed

As a beginner in Angular, my goal is to create a feature where: The character count in a label increases as text is entered into a textarea. When the backspace key is pressed, the counter should decrease. If the user attempts to enter more characters tha ...

Tips for embedding a script into an HTML document

I've been experimenting with tinymce npm and following their guide, but I've hit a roadblock. Including this line of code in the <head> of your HTML page is crucial: <script src="/path/to/tinymce.min.js"></script>. So, I place ...