Toggle the visibility of a div by clicking on a label

I am working with three unique labels, each with different ids and three distinct divs also with different ids.

<asp:Label ID="CA" runat="server"  Font-Bold="False" Font-Names="Arial" Font-Size="10pt" style="padding-top:6px;" ForeColor="#CCCCCC" Height="100%" Text="Current Activities" onmouseover="var b = ChangeColorCA(); this.style.cursor='pointer'; return b" onmouseout="RemoveColorCA()"></asp:Label>&nbsp;

Here is the respective div code for each label:

<div id="DIV_CA" runat=server align="center" visible="false" style="background-color:#f3f3f3; text-align: left; width: 500px; height: 470px; overflow:auto;">Some data</div>

I am looking to create a toggle function where clicking on a label will show its corresponding div while hiding the others. I am wondering if anyone can guide me on how to achieve this.

Update: Below is the script code I have been working with:

<script type="text/javascript">
  function hideshow(span) {
    var div = document.getElementById("DIV_" + span.id);
    if (div.style.display == "none")
       div.style.display = "block";
    else
       div.style.display = "none";
    }
</script> 

And here is the updated label code I am using:

<asp:Label ID="CA" runat="server"  Font-Bold="False" Font-Names="Arial" Font-Size="10pt" style="padding-top:6px;" ForeColor="#CCCCCC" Height="100%" Text="Current Activities" onmouseover="var b = ChangeColorCA(); this.style.cursor='pointer'; return b" onmouseout="RemoveColorCA()" onclick="hideshow(this)"  ></asp:Label>&nbsp;

Answer №1

If you have the knowledge of writing JavaScript languages.

Here is the breakdown:

<asp:Label ID="CA" 
               runat="server"
               onclick="hideshow(this)"
               Text="Label">
</asp:Label>
<div id="DIV_CA" 
     runat=server 
     align="center"  
     style="background-color:#f3f3f3; text-align:
            left; width: 500px; height: 470px; overflow:auto; display:none;">
         Some data
</div>

If you want to manipulate JavaScript:

 function hideshow(span) {
    var div = document.getElementById("DIV_" + span.id);
    if (div.style.display == "none")
       div.style.display = "block";
    else
       div.style.display = "none";
    }

EDIT: To hide all divs and show a specific div.

Breakdown: Place all <asp:Label/> and <div> inside another <div/>

 <div id="allDiv">
        <asp:Label ID="CA" runat="server"  Font-Bold="False" Font-Names="Arial" Font-Size="10pt" style="padding-top:6px;" ForeColor="#CCCCCC" Height="100%" Text="Current Activities" onmouseover="this.style.cursor='pointer'; "   onclick="hideshow(this)"></asp:Label>
        <asp:Label ID="CB" runat="server"  Font-Bold="False" Font-Names="Arial" Font-Size="10pt" style="padding-top:6px;" ForeColor="#CCCCCC" Height="100%" Text="Current Activities" onmouseover="this.style.cursor='pointer'; "   onclick="hideshow(this)"></asp:Label>
        <div id="DIV_CA" runat="server" align="center"  style="background-color:#f3f3f3; text-align: left; width: 500px; height: 470px; overflow:auto; display:none;">Some data1</div>
        <div id="DIV_CB" runat="server" align="center"  style="background-color:#f3f3f3; text-align: left; width: 500px; height: 470px; overflow:auto; display:none;">Some data2</div>
</div>

JavaScript: function hideDiv() set display:none to all child div.

<script type="text/javascript">
    function hideshow(span) {
        hideDiv();
        span.style.fontWeight = "bold";
        var div = document.getElementById("DIV_" + span.id);
        if (div.style.display == "none")
            div.style.display = "block";
        else
            div.style.display = "none"; 
    }
    function hideDiv() {
        var childDiv = document.getElementById("allDiv").childNodes;
        for (i = 0; i < childDiv.length; i++) {
            if (childDiv[i].tagName == "DIV") {
                childDiv[i].style.display = "none";
            }
            if (childDiv[i].tagName == "SPAN") {
                childDiv[i].style.fontWeight = "normal";
            }
        }
    }
</script>

Answer №2

Here is a JQuery example to achieve the desired functionality:

$("#<%= CA.ClientID %>").click(function(){

    $("#<%= DIV_CA.ClientID %>").toggle();

});

Answer №3

1) Start by creating two CSS classes: divClass and divVisible. The former applies to all divs, while the latter is specifically for the visible div.

2) Next, set up an OnClientClick event on the Label(s) that references a JavaScript function called showHideDiv.

3) Within the showHideDiv function, the script hides all divs with the divVisible class and identifies the correct div to display based on the Label ID.

function showHideDiv(el)
{
  var id = el.getAttribute('id');
  var div = document.getElementById('DIV_' + id);
  var hideVisibleDiv = document.getElementsByClassName('divVisible');

  for(var e in hideVisibleDiv)
  {
    hideVisibleDivs[e].className = 'divClass';
  }
  div.className = 'divClass divVisible';
}

These steps should help achieve the desired functionality...

Answer №4

Everything is set up perfectly:

<input type="text" placeholder="Enter your name" name="name" id="name"><br/>
<input type="email" placeholder="Enter your email" name="email" id="email"><br/>
<textarea placeholder="Enter your message" name="message" id="message"></textarea>

<input type="submit" value="Submit" id="submit">

<script type="text/javascript">
    $("#submit").click(function () {
        var name = $("#name").val();
        var email = $("#email").val();
        var message = $("#message").val();

        // Perform validation and submit form
    });
</script>

Answer №5

To ensure your JavaScript code runs after using an update panel on your page, make sure to include the following snippet:

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(AsyncPostback);
function AsyncPostback() { //insert your code here };
This will prevent your JavaScript code from failing to execute after a postback.
Best of luck!

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

What is the best way to link this interval service with a view component?

Exploring the AngularJS documentation for $interval, I came across an interesting example demonstrating how to utilize $interval in a controller to create a user-friendly timer in a view. The official example code can be found on the angularJS documentatio ...

Executing a JavaScript function using document.write()

When I try to click on the SWF part1 links within the document.write() function in order to call the openswf function, nothing happens. Here is my code: <html> <a href="#" onclick="Popup();">show popup</a> <script> functio ...

javascript - data needed

Currently, I am diving into practicing javascript coding on CodeAcademy. While testing out my code in Codeacademy, I rely on console.log to display strings to the built-in browser within the platform. Everything runs smoothly there. The challenge arises wh ...

React Intersection Observer Triggering Memory Leaks

Issue Description: I encountered a problem with my React app crashing on mobile. The Chrome dev tools revealed that garbage collection wasn't triggering, and upon inspecting the heap, I found that the top constructors by retained size were all linked ...

Adding JavaScript code to Rails erb snippets

I have a complex select block created using Rails erb, and I now need to convert it to jQuery using append. Here is the original select block: <select id="mission_reward" name="mission_reward" class="select_reward"> <option value="0"><%= ...

Php/JavaScript Error: Identifier Not Found

I've double-checked my code multiple times, but it still doesn't seem to be working properly. When the PHP runs, the browser console displays the following error: Uncaught SyntaxError: Unexpected identifier. I'm not sure if this is a si ...

Can I apply a universal babel configuration across all of my personal projects?

It becomes tedious to duplicate the same configuration file for each new project I start. ...

Do not proceed if the process has encountered a failure

Using PHP code, I have created a way for people to get in touch with me and share their opinions. Here is the PHP code snippet: <?php $to = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ef9b868c848a9bc19d869b8e988a8 ...

using post request axios to send parameters

I am looking to make a post request using axios with an object as the payload. employee:{ name: 'test', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0d79687e794d6a606c6461236e6260">[email ...

Obtaining the current date and time of the user's browser within a server-rendered file

I need to capture the browser/local date and time in a PDF file. The challenge I'm facing is that the PDF file rendering occurs on the server, which means I can't use JavaScript to achieve this as the rendering process is server side. Can anyone ...

Tips for adjusting the cursor position in a textBox when a button is clicked using c#:

In my Windows Form application developed in C#, I have implemented two text boxes and a button. Currently, when text is entered into txtbox1 and sent to txtbox2 on button click, the cursor automatically moves to txtbox2. However, I would like the cursor ...

Core Entity Framework with Identity implemented across multiple projects

I am currently working on two projects: First is an ASP.NET Core Web Application (.Net Core) Second is a Class Library (.NET Core) called ExternalEntityFramework.Data https://i.sstatic.net/Vsbwb.png I originally followed a tutorial on how to move Entit ...

Challenges encountered during the execution of React tests: Enzyme, Jest, and React integration

Encountered an error while running tests: FAIL src/components/common/user/UserMenu/__tests__/UserMenu.test.js ● Runtime Error Error: Failed to get mock metadata: /redacted-directory/node_modules/core-js/library/modules/_global.js See: http://facebook ...

What's the most effective method for looping through a substantial array in order to save data into SQLite using Node.js?

Let's consider a scenario where I am inserting data into a table using a for loop like the example below: ... for(let i=0;i<data.length; i++){ db.run(`INSERT INTO db (a, t, p, q, bM) VALUES (?, ?, ?, ?, ?)`, [data[i].a, data[i].t, data[i].p, da ...

Is it possible to incorporate a label within a dropdown menu (<select>)?

How can I add a label inside a select box using Bootstrap? Here is an example: Before selecting an option After selecting an option, the label should appear in a small size like this: After selecting an option : <div class="form-group"> & ...

I could use some assistance with iterating through an array that is passed as a parameter to a function

Compute the product of parameter b and each element in the array. This code snippet currently only returns 25. This is because element a[0], which is "5", is being multiplied by argument b, which is also "5". The desired output should be ...

How big is the array size in the WebAudio API data?

Exploring the visualization of waveform and FFT generated by the audio stream from the microphone through the WebAudio API. Curiosity strikes - what is the size of each data array available at a given moment? Delving into the getByteTimeDomainData, it men ...

Reactivity in Vue.js powered by ES6 classes

I am attempting to create a computed property in Vue.js that is associated with an ES6 class. Here is an example of my Vue instance setup: ... props: ['customClass'], computed: { localClass: { get() { return this.custom ...

What is the best way to manage DOM modifications in a responsive design layout?

Developing a responsive website with only one breakpoint can be challenging, especially when restructuring the DOM to accommodate different screen sizes. It's important to consider not just CSS and media queries, but also how the elements are arranged ...

There is an abundance of brief PHP documents

After conducting some initial research, I have realized that I need more information on the topic at hand. My interactive website relies on ajax calls to retrieve data from the server. Authenticated users engage with this data through various actions, whic ...