Resetting values in Javascript and JQuery when clicking a button

I've recently implemented a feature on my website header where clicking on the search button reveals a search bar, and clicking on the account button reveals an account bar. With some valuable assistance from Madalin, I was able to achieve this functionality through JavaScript (source: "DIV moving up and down using javascript").

However, I have encountered a challenge. Is there a way to reset the JavaScript when either the "search" or "account" button is clicked? Currently, if one button has been activated and then you click the other, you need to click twice on the initial button to trigger the action again. Please refer to the provided jsfiddle link for clarity: [https://jsfiddle.net/27jaodcg][1]

The current behavior is that clicking on the "account" button will close the search bar, and clicking on the search bar will close the account bar, which works perfectly for a single interaction.

However, if the account button has been clicked previously, the script assumes the account bar is still open. Therefore, when clicking on the search button, it closes the account bar first, but since it's already closed by the search button click, nothing happens when clicking on the account button again.

I hope this explanation clarifies the situation :)

Below is the existing JavaScript jQuery code:

jQuery(document).ready(function($){
  $("#account").on('click',function(){
  if($(this).hasClass('open')) {
        // Account button actions when already open
  } else {
        // Account button actions when closed
  }
  });
  $("#searchid").on('click',function(){
  if($(this).hasClass('open')) {
        // Search button actions when already open
  } else {
        // Search button actions when closed
  }
  });
});

Thank you in advance for any insights!

Answer №1

To ensure smooth operation when opening the toolbars, make sure to remove the "open" class from the other toolbar. Check out the code snippet below for reference.

jQuery(document).ready(function($){
  $("#account").on('click',function(){
    if($(this).hasClass('open')) {
      $("#topheaderid").animate({ top: '0' }, { duration: 500, queue: false });
      $("#accountbarid").animate({ height: '0' }, { duration: 500, queue: false });
      $("#searchbarid").animate({ height: '0' }, { duration: 500, queue: false });
      $('#contentid').animate({ marginTop: '60px' }, { duration: 500, queue: false });
      $(this).removeClass('open');   
    } else {
      $("#topheaderid").animate({ top: '60px' }, { duration: 500, queue: false });
      $("#accountbarid").animate({ height: '60px' }, { duration: 500, queue: false });
      $("#searchbarid").animate({ height: '0' }, { duration: 500, queue: false });
      $('#contentid').animate({ marginTop: '120px' }, { duration: 500, queue: false });
      $(this).addClass('open');  
      $("#searchid").removeClass('open');
    }
  });
    
  $("#searchid").on('click',function(){
    if($(this).hasClass('open')) {
      $("#topheaderid").animate({ top: '0' }, { duration: 500, queue: false });
      $("#accountbarid").animate({ height: '0' }, { duration: 500, queue: false });
      $("#searchbarid").animate({ height: '0' }, { duration: 500, queue: false });
      $('#contentid').animate({ marginTop: '60px' }, { duration: 500, queue: false });
      $(this).removeClass('open');   
    } else {
      $("#topheaderid").animate({ top: '0' }, { duration: 500, queue: false });
      $("#accountbarid").animate({ height: '0' }, { duration: 500, queue: false });
      $("#searchbarid").animate({ height: '60px' }, { duration: 500, queue: false });
      $('#contentid').animate({ marginTop: '120px' }, { duration: 500, queue: false });
      $(this).addClass('open');
      $("#account").removeClass('open');
    }
  });
});

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

Click on a specific image in a table using Cypress with a specific source URL

I need help with a query for Cypress regarding a table of items, each item having active (blue) and not active (black) images. How can I set up this query? Below is an image of the table list: https://i.stack.imgur.com/74qzb.png And here is the HTML code ...

The sluggish speed experienced when using the datatables jQuery plugin in conjunction with the Brunch

Currently, I am utilizing Brunch as a framework for the frontend of a web application. My approach involves drawing each row of a table as a view and then converting the table to datatables. For specific UI reasons, it's essential that each row is r ...

Dynamically getting HTML and appending it to the body in AngularJS with MVC, allows for seamless binding to a

As someone transitioning from a jQuery background to learning AngularJS, I am facing challenges with what should be simple tasks. The particular issue I am struggling with involves dynamically adding HTML and binding it to a controller in a way that suits ...

Dynamically fetching and uploading files from a specific path using Node.js, Express, and Angular 1.x

How can I upload or move all files from a specific folder using NodeJS, Express, and Angular 1.x by providing the folder path? What is the best way to handle this operation in either Angular or Node? Should I use: var fs = require('fs') module ...

Make the width of a table column match the width of the header

I am currently using Primeng2 datatable and I am looking to adjust the column width to match the header size. This is my HTML code: <p-dataTable #dtselfcollectmonthly [exportFilename]="exportname" [rows]="10" [value]="rawdatatrucks"> <ng-con ...

The error page is requesting a root-layout, which indicates that having multiple root layouts is not feasible

My issue is as follows: The not-found page located in my app directory requires a root-layout which I have added to the same directory. However, this setup prevents me from using multiple root layouts in the structure below. How can I resolve this? It see ...

Is there a way to send the image object to the onclick function as it is being assigned?

I apologize if my question is a bit unclear, as I am currently teaching myself how to use javascript. I am working on generating image thumbnails dynamically and would like the ability for users to enlarge the image when they click on the thumbnails. The p ...

Looking through a Json file and retrieving data with the help of Javascript

I am currently working on developing a dictionary application for FirefoxOS using JavaScript. The structure of my JSON file is as follows: [ {"id":"3784","word":"Ajar","type":"adv.","descr":" Slightly turned or opened; as, the door was standing ajar.","tr ...

assigning a numerical value to a variable

Is there a way to create a function for a text box that only allows users to input numbers? I want an alert message to pop up if someone enters anything other than a number. The alert should say "must add a number" or something similar. And the catch is, w ...

CSS: Adding decorative trailing dots below the header when positioned over a background

I am seeking assistance with achieving a specific effect in CSS, as shown in the attached screenshot. The trailing dots should cover the entire width of the element (100%) and be responsive. However, I encountered an issue when placing the header on a bac ...

Having difficulty accessing the sound file despite inputting the correct path. Attempts to open it using ./ , ../ , and ../../ were unsuccessful

While attempting to create a blackjack game, I encountered an issue. When I click the hit button, a king card picture should appear along with a sound. However, the sound does not play and the error message Failed to load resource: net::ERR_FILE_NOT_FOUND ...

Utilizing ChartJS to convert a chart into a Base64 image within a Vue environment

I am currently utilizing the PrimeVue chart component, which is built on top of ChartJS. The configuration is very similar. The documentation indicates that I need to instantiate a new Chart() and then call toBase64Image(); My main query is, how do I ac ...

What is the reason behind negative numbers appearing as "5-" rather than "-5" in the basic calculator coded using HTML and JavaScript?

As I am practicing my coding skills, I encountered an interesting issue. Any operation that results in a negative number displays as wrong, but when using console.logs it shows the correct result. Can someone explain why this is happening? <!DOCTYPE h ...

Troubleshooting in Electron: What is the best way to access objects within the render scope from the console?

During my experience in web development, I have always appreciated the ability to access and manipulate variables and functions through the browser's development console at runtime. For instance, if I define a var foo = 3; in my code, I am able to ...

Is it possible to use CSS and HTML to rotate a cube and expand its sides?

I am attempting to rotate the cube and expand its faces. I have experimented with the following code: .wrapper{ position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); } .cube-wrap { width: 40px; height: 40px; ...

Tips for positioning label/input box/button on Internet Explorer 7

Here is a Fiddle example you can check out, along with the corresponding code : <div class="menu-alto"> <ul> <li> <a title="Link" href="#">Link</a> </li> <li class="newsletter ...

What is the best way to implement conditional styling in Vue.js?

Looking to incorporate a conditional style into my Component. Here is my component: <site-pricing color="primary" currency="$" price="25" to="/purchase" > <template v-slot:title>Complete</templat ...

After submitting a post, the click event of a button in IE 10 using jQuery is not

The uploadButton feature allows users to upload an image and store it locally. I utilize fileinput to select the image, and when uploadbutton is clicked, the image data is sent back to the server. While this functionality works smoothly in Chrome, I encou ...

Tips on expanding the row number column width in jqGrid

Within my JQuery Grid, I am utilizing a parameter called rownumbers. jQuery("#dateInfo").jqGrid({ url : theURL, datatype : "json", sortable: false, colNames:['Date & Time'], colModel:[{name:'arrivalTime',index:'arrivalTime& ...

ng-repeat isn't displaying the data

I have always been comfortable using the ng-repeat in Angular, but this time I seem to be facing a problem. I am trying to populate my DOM with data from a JSON file, but for some reason, the fields are not displaying as expected. Is there something wrong ...