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

Using Angular 2 to trigger an event when a native DOM element is loaded

I am working towards my main objective of having a textarea element automatically focused upon creation. I recently came up with an idea to use e.target.focus() on the onload event. It would look something like this: <textarea rows="8" col="60" (load)= ...

What is the reason for using 'app' as the top-level directory name in React Native import statements within a project setting?

Seeking to comprehend the imports within React Native source code, specifically in a file named questionnaire.actions.js, relative to the top-level directory called lucy-app: ./src/containers/newUserOnboarding/questionnaire/questionnaire.actions.js The m ...

Slice the towering text in half lengthwise

Ensure that the last line of visible text fits within a 20px padding, or else it should be completely cut off. The challenge lies in the varying text lengths of h3 each time. It's difficult to predict how much needs to be trimmed. Currently, the tex ...

Utilizing Bootstrap 5's table design to occupy the rest of the available vertical

In my .NET Core 7 MVC project, I am facing a challenge where I want to make a details table scroll and occupy the available vertical space on the screen dynamically. I have tried using h-25, h-50 classes to achieve the scrolling effect on the table. Howev ...

Using Javascript to automatically replace content when the page is loaded

Having trouble with my fullCalendar jquery calendar and the 'eventClick' method. When I click on an event, the URL is getting encoded incorrectly. For example, I'm trying to pass a Wordpress URL like this: http://sitedomain.com/?post_type= ...

Revamp the layout of the lower HTML video menu

Here is my code: <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> video { width: 100%; height: auto; } </style> </head> <body> <video width="400" controls> ...

I am having trouble with updating an array in React useState. Every time I try to make changes, it keeps reverting back to the initial state. What could

My current task involves managing a state array called monthlyIncidents, which contains 12 numbers that need to be updated under certain conditions. I attempted to update the elements by copying the array, modifying the specific element, and then updating ...

Which is quicker: loading JSON via Ajax or loading the entire output through Ajax?

I'm interested in gathering different perspectives on this topic. Currently, I have Jquery initiating a function through ajax which loads data in two ways: The ajax script fetches JSON data from the server itself, then utilizes JavaScript to pars ...

What is the best way to make a box modal function that displays a different image source than the one shown in the modal?

I'm looking to create a box modal that shows one image on the page, and then displays a different image in the popup when clicked. Here's what I currently have: <div class="row"> <div class="modal-image"><img id="myImg" src="http ...

Invoke a function from a different vue.js component using the this.$refs property

I'm facing an issue with triggering a sibling element. What I've tried so far <b-img @click="callFileLoader"/> <b-file type="file" ref="fileUploader"></b-file> ... methods:{ callFileLoader () { this.$refs.fileUploader.c ...

Inquiring about browserify or webpack on a website using node - a few queries to consider

Seeking assistance with a website project I am currently working on. The project consists of 7 HTML documents, 3 stylesheets, 8 JavaScript files (including jQuery.min.js and some additional jQuery plugins), and various images. I am looking to bundle and mi ...

Guide to accessing a newly opened window from a different domain originating from the current window

Currently working on an Angular project, I am facing a scenario where I have a link on page A that directs users to a different origin page B. The HTML code for the link is shown below: ... <a href="https://another.origin"> PAGE B </a> ... On ...

Animate your SVG with CSS using hover effects that originate from the center of the SVG

I successfully implemented this animation using GSAP and you can view the Codepen for reference: https://codepen.io/whitelionx/full/vYGQqBZ const svgs = document.querySelectorAll("svg"); svgs.forEach((svg) => { const tl = gsap .timelin ...

Adjust the ZIndex on a div through interactive clicking

For my new project, I'm exploring a concept inspired by Windows 7. The idea is that when you double click on an icon, a window will open. If you keep double clicking on the same icon, multiple windows should appear. The challenge I'm facing is im ...

What is the best way to include the existing query string value in the hyperlinks on my page?

My main coding objective is to simultaneously search multiple websites. To accomplish this, I want to create a query string containing the search terms (primarily for analytics purposes) using a form. By utilizing JavaScript, I am aiming to include the s ...

Using the power of JavaScript to iterate through elements with the

Looking for a way to integrate JSON data into your simple bootstrap page? Here's a script that might help: Take a look at the following script: var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && ...

Assign separate classes to even and odd div elements

My PHP code block has this structure: $flag = false; if (empty($links)) { echo '<h1>You have no uploaded images</h1><br />'; } foreach ($links as $link) { $extension = substr($link, -3); $image_name = ($extensi ...

Disable toggling on selected elements within the header of a Bootstrap 5 accordion

I implemented a Bootstrap 5 accordion with the functionality to display a popover when clicking on an icon within the accordion header. While the popover is working, I encountered an issue where the accordion also toggles when the popover-handler element i ...

Having difficulty inputting password for telnet login using Node.js

When I use telnet from the Windows command line, everything works smoothly: > telnet telehack.com (... wait until a '.' appears) . login username? example password? (examplepass) * * * * * * * Logged... (...) @ (This is the prompt when you ...

What is the best way to ensure that a specific number of XHR callbacks have successfully completed before proceeding with further actions?

I have four requests that each have their own callback and can fire in any order. However, I need all the callbacks to finish successfully before executing mergeData. The issue with my current approach is that the initial parameter values do not refresh ...