Hide all the div elements on the web page and only display one when a button is clicked

I have successfully set up a few buttons that can show and hide divs on click. However, I am wondering if it is possible to hide all other divs when one is showing, and also have "divone" show up on load.

Buttons:

<button class="btn btn-outline-primary" type="button" data-toggle="collapse" data-target="#divone">One</button>
        <button class="btn btn-outline-primary" type="button" data-toggle="collapse" data-target="#divetwo">Two</button>
        <button class="btn btn-outline-primary" type="button" data-toggle="collapse" data-target="#divthree">Three</button>

Divs:

<div id="divone" class="collapse">Div one content here</div> <div id="divetwo" class="collapse">Div two content here</div> <div id="divthree" class="collapse">Div three content here</div>

Answer №1

Here's a simple solution for you. By keeping your classes and HTML markup intact, you can add this custom CSS style to ensure the element is always displayed. Then, use jQuery to dynamically toggle this class based on user interaction.

.unhide{
        display: block !important;
    }

After importing jQuery, utilize this concise script to handle click events:

<script type="text/javascript">
    $(".btn").click(function(){
        $('.collapse').removeClass('unhide');
        $($(this).data("target")).addClass('unhide');
    })
</script>

To break down the process, when a button is clicked, we remove the "force to display" class first before targeting and adding it to the specified element. (note the double money signs)

If desired, feel free to get more inventive with the naming conventions of your classes!

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

Scroll up event and sticky header using jQuery

I'm working on a function $(document).ready(function () { var lastScroll = 0; $(window).scroll(function(event){ var st = $(this).scrollTop(); if ((lastScroll - st) == 5) { $("header").css("position", "fixed"); ...

Using custom class instances or objects within Angular controllers is a simple process

Using three.js, I have created a class called threeDimView that houses my scene, camera, and other elements. In my JavaScript code, I instantiate a global object of this class named threeDimView_. threeDimView_ = new threeDimView(); Now, I wish to displa ...

Loop through the <li> elements and use jQuery to update the text

Check out this HTML setup: <div class="mydiv"> <ul> <li>Text 1</li> <li>Text 2</li> </ul> <ul> <li>Text 3</li> <li>Text 4</li> </ul> <ul> < ...

Issue with Counting Digg Button Clicks

I can't figure out why the digg button counter isn't working. I followed the instructions but... The website in question is: . I implemented the code exactly as explained here: But the counter remains at 0. Has anyone encountered a similar iss ...

Unraveling the mysteries of deciphering extended JSON information

Issue with Data Interpretation I am facing a challenge in my project that is more related to understanding and interpreting data rather than writing code. The project involves using a NoSQL database, specifically MongoDB, to store information sampled from ...

Utilizing AngularJS to upload numerous independent attachments to CouchDB

My goal is to upload multiple files to a couchdb document using angularjs. Despite my efforts with an angular.forEach loop, I am facing issues as the asynchronous $http calls do not wait for the previous loop to finish before moving on to the next one. Her ...

One XMLHTTPRequest with multiple replies

My requirement is to have a consolidated XMLHttpRequest call that returns three unique items. These items consist of an HTML formatted table and two separate sets of JSON data for Google Charts. The reason behind this design is that the chart data relies o ...

HTML: Base64 image not displaying properly due to incorrect height specification

I have a straightforward base64 image that I am having trouble with. The issue is that only the upper half of the image is displaying. If I try to adjust the height using the "style" attribute in the img tag: style="height: 300px;" it shows correctly. Ho ...

Guide to showcasing console output on a Web Server

Apologies if this question is not the most suitable for this platform. I recently set up Pure-FTPd service on a CentOS server. To check current connections, I use the command pure-ftpwho, which gives me the following output: +------+---------+-------+---- ...

Ways to conceal a grid item in Material UI framework

My goal is to hide a specific grid item for a product and smoothly slide the others in its place. Currently, I am using the display:none property but it hides the item instantly. I have already filtered the products and now I want to animate the hiding of ...

Mistake made by the author while using the Google Structured Data Test

While reviewing my website, I encountered an error message stating: "Missing required hCard "author"" http://www.google.com/webmasters/tools/richsnippets?q=http%3A%2F%2Fwww.gamempire.it%2Fcastlestorm-ps-vita%2Frecensione%2F131419 Why is this happening? I ...

Execute a script when a post is loaded on a WordPress page

I am looking to have my jQuery script execute every time a post page is opened or loaded. I tried using echo in the script but it did not work. Where should I place the script to ensure it runs? single.php <script src="https://ajax.googleapis.com/aja ...

What is the best way to fetch multiple values using momentjs from firebase?

After fetching data from Firebase and storing it in an array, I am attempting to retrieve the posted_at values (timestamp of when something was posted) in a time format using Vuejs. However, I am facing difficulty as it only retrieves a single value instea ...

Best practices for utilizing child component methods within a parent component in VUE

I am working with the ImageUpload.vue component, which is a straightforward Bootstrap modal containing a few methods. I am currently exploring the best approach to utilize one of these methods. Could it be implemented like this: const app = new Vue({ ...

What is the best way to ensure the initial item in an accordion group remains open by default when using NextJS?

I've successfully developed an accordion feature in NextJS from scratch and it's functioning flawlessly. However, I am looking to have the first item of the accordion open automatically when the page loads. Can anyone guide me on how to make this ...

What is the best way to extract data from a series of nested JSON objects and insert it into a text field for editing?

I am facing a challenge with appending a group of nested JSON objects to a text field without hard coding multiple fields. Although I have used the .map functionality before, I am struggling to make it work in this specific scenario. const [questions, setQ ...

Tips on inserting javascript to modify the CSS class of a table data cell in a Flask WTF jinja2 table based on the cell's value

I have integrated Flask WTF to showcase the results of a database query. I am seeking a way to modify the cell background color to light red if the value is below 25. I am unsure about where and how to embed the JavaScript code to validate the cell value a ...

"Using jQuery to add emphasis to a table row and remove it again

I have a table with multiple rows, where I have styled each odd row in one shade of gray and the even rows in slightly different shades to make it easier to read. When clicking on a row, I am currently highlighting it with a different color to indicate wh ...

Trouble with HTTPS request in Android fragment

My app crashes and returns to the main activity whenever I try to use the search function with the Kitsu API in my fragment. I have observed through Logcat that no data is being fetched, but I am unable to determine what is causing the crash.The LogCat r ...

Tips for maintaining interactivity after a page refresh

$(document).ready(function () { $("#2").click(function () { $("#content").load("{% url 'about' %}"); }); $("#3").click(function () { $("#content").load("{% url ...