Conceal several divs using Jquery upon clicking

I have developed a fitness application that includes buttons on each exercise page to display information, input data, and track progress. Currently, when these buttons are clicked, the corresponding divs overlap and are all visible at the same time.

What I am aiming for is to have only one div displayed at a time - primarily showing the information but hiding the other divs when the user interacts with the different buttons.

Below is the HTML code snippet:

<div id="buttons">
    <a class="Smallbutton" id="showInfo">
        <img src="img/info.png" />
    </a>
    <a class="Smallbutton" id="showDataInput">
        <img src="img/add-item.png" />
    </a>
    <a class="Smallbutton" id="showHistory">
        <img src="img/bar-chart.png" />
    </a>
</div>
<div class="info" style="display: none;">
    <p>Instructions on how to perform the exercise here.</p>
</div>
<div class="dataInput" style="display: none;">
    <form onsubmit="save_data()">
        Reps:
        <input id="reps" type="number" name="quantity" min="1" max="12" step="1" required>Sets:
        <input id="sets" type="number" name="quantity" min="1" max="4" step="1" required>
        <input type="submit" value="Add Log" onclick="insert(this.form.reps.value,this.form.sets.value);show();">
</div>
<div class="history" style="display: none;">
    <div id="log"></div>
    <input type="button" value="Clear" onclick="clearLocal();" />
</div>

The JavaScript logic using jQuery is implemented as follows:

//JQUERY SHOW/HIDE HISTORY

$(document).ready(function() {
    $('#showHistory').click(function() {
            $('.history').slideToggle("fast");
    });
});



//JQUERY SHOW/HIDE DATA INPUT

$(document).ready(function() {
    $('#showDataInput').click(function() {
            $('.dataInput').slideToggle("fast");

    });
});

//JQUERY SHOW/HIDE INFO

$(document).ready(function() {
$(document).ready(function() {
    $('#showInfo').click(function() {
            $('.info').slideToggle("fast");

    });
});

You can view the demonstration on JSFiddle here.

Any assistance towards achieving this desired functionality would be greatly appreciated.

I came across a similar example here, however, integrating the code into my application results in all divs being displayed simultaneously.

Answer №1

Some slight adjustments

  • Include a data-target="" attribute for all buttons
  • Add the class target to all div elements

Experiment with:

<div id="buttons">  
    <a class="Smallbutton" id="showInfo" data-target=".info"><img src="img/info.png"/></a>
    <a class="Smallbutton" id="showDataInput" data-target=".dataInput"><img src="img/add-item.png"/></a>
    <a class="Smallbutton" id="showHistory" data-target=".history"><img src="img/bar-chart.png"/></a>
</div>  

<div class="info target" style="display: none;">
    <p>Place yourself on the edge of the chair and grasp the seat just below your legs. Execute the crunches by lifting yourself from the seat and bring your knees towards your chest.</p>
</div>
<div class="dataInput target" style="display: none;">
    <form onsubmit="save_data()">
        Reps: <input id="reps" type="number" name="quantity" min="1" max="12" step="1" required />
        Sets: <input id="sets" type="number" name="quantity" min="1" max="4" step="1" required />
        <input type="submit" value="Add Log" onclick="insert(this.form.reps.value,this.form.sets.value);show();" />
    </form>
</div>
<div class="history target" style="display: none;">
    <div id="log"></div>
    <!--clears all data in localstorage-->
    <input type="button" value="Clear" onclick="clearLocal();"/>
</div>

next

$(document).ready(function () {
    var $targets = $('.target');
    $('#buttons .Smallbutton').click(function () {
        var $target = $($(this).data('target')).slideToggle();
        $targets.not($target).hide()
    });
});

Demonstration: Fiddle

Answer №2

Make sure to include the .hide() function for other divs within the click function.

 $(document).ready(function() {
        $('#showHistory').click(function() {
            $('.history').slideToggle("fast");
            $('.dataInput').hide(); //hide other elements
            $('.info').hide();  //hide other elements
        });
    });

Check out the FIDDLE

Answer №3

Give this method a try,

The following is the HTML code snippet,

<div id="buttons">
    <a class="Smallbutton" id="showInfo">
        <img src="img/info.png" />
    </a>
    <a class="Smallbutton" id="showDataInput">
        <img src="img/add-item.png" />
    </a>
    <a class="Smallbutton" id="showHistory">
        <img src="img/bar-chart.png" />
    </a>
</div>
<div class="info infoContainers" style="display: none;">
    <p>Position yourself on the edge of the chair and grab hold of the seat just under your legs. Do the crunches by lifting
        yourself from the seat and bring the knees to your chest.</p>
</div>
<div class="dataInput infoContainers" style="display: none;">
    <form onsubmit="save_data()">
        Reps:
        <input id="reps" type="number" name="quantity" min="1" max="12" step="1" required>Sets:
        <input id="sets" type="number" name="quantity" min="1" max="4" step="1" required>
        <input type="submit" value="Add Log" onclick="insert(this.form.reps.value,this.form.sets.value);show();">
</div>
<div class="history infoContainers" style="display: none;">
    <div id="log"></div>
    <!--clears all data in localstorage-->
    <input type="button" value="Clear" onclick="clearLocal();" />
</div>

The Javascript part goes as follows,

//JQUERY SHOW/HIDE HISTORY
$(document).ready(function() {
    $('#showHistory').click(function() {
        $('.infoContainers').slideUp();
        $('.history').slideToggle("fast");
    });
});

//JQUERY SHOW/HIDE DATA INPUT
$(document).ready(function() {
    $('#showDataInput').click(function() {
        $('.infoContainers').slideUp();
        $('.dataInput').slideToggle("fast");

    });
});

//JQUERY SHOW/HIDE INFO
$(document).ready(function() {
    $('#showInfo').click(function() {
        $('.infoContainers').slideUp();
        $('.info').slideToggle("fast");

    });
});

You can view the demo here

Answer №4

To simplify the code, I recommend using a hideAll function and calling it on each element.

function hideAll(){
    $('.info, .dataInput, .history').slideUp();
}

After defining the hideAll function, you can call it within each click event.

$('#showInfo').click(function() {
    hideAll();
    $('.info').slideToggle("fast");
});

For more details, please refer to this JSFiddle link.

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

When the page is zoomed in, the Bootstrap navbar overlaps with

I'm currently in the process of developing a website that includes a navbar with a navbar-fixed-top class. Everything seems to be working perfectly except for when I zoom in. On mobile devices, when I zoom in, the navbar starts wrapping and goes to th ...

Guide on creating an AJAX request for a POST method

I am new to working with AJAX, and I have been trying to use it for a POST function similar to the curl command below: curl -X POST -H 'Content-type:application/json' --data-binary '{ "replace-field":{ "name":"sell-by", "type":"date", " ...

Looking for assistance in setting up a personalized slideshow to automatically play on its

Recently, I have taken responsibility for a project that was initiated by someone else. The website contains a customized slideshow on its homepage. To meet the client's requirements, I have already made some alterations to the appearance and feel of ...

Fluid Cursor Movement in the Atom Text Editor

I encountered an issue where adding a smooth caret animation in the atom editor caused the background to start blinking uncontrollably. Below is the code snippet I used to add the animation in my style.less file: atom-text-editor .cursor { transition: ...

Unable to retrieve data from the array

I am encountering an issue while trying to fetch data from an array, as I keep receiving undefined Please refer to the image for a visual representation of my problem. I'm not sure what I might be overlooking, so any help would be greatly appreciate ...

Tips for adding classes to both parent and child elements in dynamically loaded data via an ajax request

I am facing a challenge with jQuery as a beginner. I have been struggling for the past week to load data from a JSON array using an ajax call. I'm also using a swipe plugin to swipe and display all images on the same div, but I'm unsure of how to ...

`Is there a way to effectively test an @Input component in Angular?`

Despite multiple successful attempts in the past, I am facing some difficulty getting this to function properly. Within my component, I have an input @Input data: Data, which is used in my template to conditionally display certain content. Oddly enough, du ...

What is the process to transfer data from JavaScript to HTML within a Laravel environment?

I am attempting to transfer a value from JavaScript to HTML as a variable. In order to do this, I am retrieving the value from a Laravel PHP controller. JavaScript $("ul.nav-tabs > li > a").click(function() { var id = $(this).attr("href").repla ...

Ways to implement the bootstrap grid system for a dynamically expanding div rather than the browser window

I'm currently experiencing an issue applying the bootstrap grid style to a dynamically expanding div. When clicking the button, the container div expands, but the medium grid style is not being applied when it reaches the medium width. Below is my c ...

Let's get this bread: Error - Whoops! It looks like there's a hiccup with the '?' token in the mobile browser for

Have you checked for any existing problems? [X] I have searched the existing issues Package Version 0.8.6 Issue Description An error occurs when attempting to set up wagmi and use it on a mobile browser with NextJS. SyntaxError: Unexpected token ' ...

Getting stuck trying to fetch the queryset from the server and adding it to the select options using AJAX

I have managed to successfully send the value of the input field with the id datepicker to the server. In the view, I am able to filter the time slots based on the selected date. However, I am facing a challenge in sending this queryset back to the browse ...

Dismissal feature malfunctioning in Materialize CSS

I am having trouble closing the modal when the user clicks outside of it. This issue is occurring in my first project with Materialize, and I can't figure out why it's not working. Below is a snippet of the code I have implemented: Within the ...

Getting the autogenerated document ID from Firestore - A Step-by-Step Guide

When creating my document, I rely on the auto-generated ID. However, after setting it, I find that the retrieved ID is different from the one in the Firestore Database. await admin.firestore().collection("mycollection").doc().set(mydata) .then(doc = ...

Unable to retrieve a single item in NextJS

Struggling with fetching a single item in NextJS const PRODUCT_API_BASE_URL = "http://localhost:8080/api/v1/products/"; export const getStaticPaths = async () => { const res = await fetch(PRODUCT_API_BASE_URL); const data = await res.json(); ...

I am struggling to create a responsive HTML/CSS/Bootstrap file that can adapt to all screen sizes

Exploring the world of web development for the first time and seeking guidance on how to make file elements responsive to accommodate any screen size or resolution. Assistance would be greatly appreciated! Here's a snippet of my code: `\<!DOCT ...

The act of receiving becomes ineffective when it was intended to be functional - Nextjs/JavaScript

When using nextjs, I encountered an issue while trying to map my array to getstaticpaths for generating getstaticprops. Every time I attempted to map the result, I received an error stating 'mycatagoriesis not a function'. Below is a snippet fro ...

Necessary form group in html [Angular]

Is there a way to make certain form fieldsets required while allowing the user to choose which inputs to fill? My idea: Users can select what they want to fill out without having to complete all of the fieldset inputs. I have these two options: 1: < ...

Ways to enhance the capabilities of the Javascript Date object

I'm attempting to create a subclass or extension of the native Date object without making any modifications to the original object. Here's my first approach: var utilities = require('utilities'); function CustomDate() { ...

Performance lag with Three.js on a vertical phone screen

Recently, I transformed my codepen project into a fully functional website. However, I have encountered an issue where the performance is significantly slow when viewed on the Chrome browser of my Nexus 5X phone. Interestingly, the problem resolves itself ...

Styling for Ajax Forms when traditional methods don't work

I'm working on an Ajax form and I want to ensure there's a solid fallback in case the user has JavaScript disabled. Currently, the form functions without JavaScript, but the user sees the JSON string displayed as plain text without any styling du ...