Unveil Secret Divs with a Click

I am in search of a way to display a hidden div when I click on a specific div, similar to the expanding images feature in Google's image search results. I have made progress with my limited knowledge of javascript, as shown in this CodePen: http://codepen.io/anon/pen/fKEgw

The basic functionality is achieved through the following code:

document.getElementById("a-section").addEventListener("click", function () {
document.getElementById("a-reveal").style.height = "300px";
document.getElementById("b-reveal").style.height = "0px";
document.getElementById("c-reveal").style.height = "0px";
document.getElementById("d-reveal").style.height = "0px";
document.getElementById("e-reveal").style.height = "0px";
document.getElementById("f-reveal").style.height = "0px";
document.getElementById("g-reveal").style.height = "0px";
document.getElementById("h-reveal").style.height = "0px";
});

I am seeking a more efficient method to achieve the same effect without explicitly setting height values. Is there a better approach to coding this functionality so that duplicate divs are not required for mobile view? Should I consider using something other than just javascript?

Your assistance is greatly appreciated!

Answer №1

If you're using jQuery, a simple way to show and hide elements is by using the following code:

$("#a-reveal").show();

and

$("#b-reveal").hide();

instead of adjusting their heights. In plain JavaScript, this involves changing the 'display' CSS attribute to 'none' to hide the element and then back to 'block' (default display).

edit:

Another approach is to modify the HTML structure like this:

<div id="a-section" class="section" reveal="a-reveal">
....

<div id="a-reveal" class="reveal">

where "reveal" contains the ID of the associated reveal div. This allows you to simplify event handling with the following code snippet:

// Attaches an event to every div with class "section"
$(".section").click(function(){
    $(".reveal").hide();
    var thisRevealID = $(this).attr("reveal");
    $("#"+thisRevealID).show();
});

There may be a more efficient way to access the appropriate reveal div without adding the reveal attribute. The goal is to dynamically determine the action based on the clicked div without hardcoding specific IDs into the script.

Answer №2

Indeed, for larger projects, opting for JQuery might be a better choice as highlighted in thogue's fantastic response. However, if you prefer sticking to pure Javascript, there is the option to tidy up the code a bit:

var reveal_func = function(section){
   var arr_a = new array("a-reveal","b-reveal","c-reveal");
   for (var i=0; i<var_a.length; i++){
      if (arr_a[i] === section){
          document.getElementById(arr_a[i]).style.height = "300px";
      }else{
         document.getElementById(arr_a[i]).style.height = "0px";
      }
   }

};

After that, you can add:

document.getElementById("a-section").addEventListener("click", reveal_func("a-reveal"))
document.getElementById("b-section").addEventListener("click", reveal_func("b-reveal"))

as required.

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

Retrieve information about a parent's data related to child events in Vue.js

I'm working with two components nested inside each other. The parent component has a click event that needs to modify the data value of the child component. <template> <div> ..... ..... <my-component :op ...

Creating a link button using JavaScript

I have integrated a Setmore code on my website to facilitate appointment booking, which triggers a popup similar to what you would see on a hotel reservation site. <script id="setmore_script" type="text/javascript" src="https://my.setmore.com/js/iframe ...

Discovering the window.scrollTop, ScrollY, or any other distance value while utilizing CSS scroll snap can be achieved by following these

I am currently utilizing css scroll snap for smooth scrolling through sections that are 100vh in height. The functionality of the scroll snap is quite impressive. However, I need to find a way to determine the exact distance the user has scrolled down the ...

Trouble aligning CSS UL/LI menu in the center

Could someone help me with centering my CSS UL menu? I've posted the code below, as I'm still learning CSS and would appreciate any guidance. I've only been able to center it by setting a fixed width and using HTML center tags, but I need t ...

Encountering a WriteableDraft error in Redux when using Type Definitions in TypeScript

I'm facing a type Error that's confusing me This is the state type: export type Foo = { animals: { dogs?: Dogs[], cats?: Cats[], fishs?: Fishs[] }, animalQueue: (Dogs | Cats | Fishs)[] } Now, in a reducer I&a ...

Create a configuration featuring filter options similar to Notion's functionality

The objective is to create a system that can establish certain constraints, similar to the way Notion handles filter properties. https://i.sstatic.net/plctW.png System A sets up the constraints and System C evaluates them, both using Typescript. However, ...

Codeigniter displays a view with an empty variable

After submitting data from another form, I am able to successfully retrieve and print the ID with `print($id)`. However, when I try to pass it to the view, the value returned is null. Below is the code snippet: Jquery post function viewAccount(orId) { ...

Error message thrown by node express.js indicating that response headers cannot be reset once they have been sent

As a newcomer to both node and express, I may be making a silly mistake. If you want to see the complete source code, please visit: https://github.com/wa1gon/aclogGate/tree/master/server logRouter.get("/loggate/v1/listall", function(req, res) { let ...

Echo result triggers a color change in the table cell

Working on a piece of code that should change the background color of the first td element based on ping results. If success, it becomes green; if failed, it turns red. The issue I'm facing is that while I can display images or use different methods ...

What is the best way to position Scroll near a mat row in Angular?

With over 20 records loaded into an Angular Material table, I am experiencing an issue where clicking on the last row causes the scroll position to jump to the top of the page. I would like the scroll position to be set near the clicked row instead. Is th ...

Dynamic creation of HTML/Ionic checkbox leads to ng-change not binding properly

Recently, my team and I have been actively engaged in the process of handling an XML file and dynamically constructing a settings page based on the information extracted from it. Allow me to present an illustration of how these elements are dynamically cre ...

What is the best way to create square editor tabs in Eclipse without using swt-border-radius?

The design of Eclipse's rounded and/or swooshing tabs is starting to feel outdated in today's modern era. I thought that by adding the following line in my default.css file, I could get rid of the rounded corners: swt-corner-radius: 0px Howeve ...

conceal selected input during ajax request

One of the modules I'm using added a button to my site. However, when this button is clicked, the module automatically sends an ajax request (and unfortunately I can't modify the third party code). How can I dynamically hide and show this button ...

Math operations limited by boundaries: adding and subtracting

What is the proper way to implement this logic in JavaScript: Row-=21; if (Row < 1) { Row = 1; } ...

Increase the size of the textarea when it is clicked on and revert back to its original size when it

My question revolves around a text area that I am trying to manipulate through jQuery. The desired functionality is to increase the height of the text area whenever someone clicks on it, and decrease the height when clicking anywhere else on the screen. & ...

Retrieving information from a PHP script with the help of the $.get method

I need to retrieve data from a PHP script that is functioning correctly. $.post( "http://labs.*********.com/inc/ajax/till_status.php", { id:$("#potentialID").val() } ).done( function (data) { currentTillStatus = data; }); The ...

What is the best way to send an array from ajax to php?

I'm having an issue passing an array from AJAX to PHP (controller). What could be the issue with the second block of code given that var_dump($data) in the first block returns the expected content while in the second it returns NULL? FIRST. GOOD. f ...

Storing the path of a nested JSON object in a variable using recursion

Can the "path" of a JSON object be saved to a variable? For example, if we have the following: var obj = {"Mattress": { "productDelivered": "Arranged by Retailer", "productAge": { "ye ...

Displaying Errors from Controllers in React Hook Forms

Currently, I am attempting to generate required errors for my input element that is enclosed within a Controller component from react-hook-form version 7. The Input consists of a Material-UI TextField structured like this; <Controller ...

What is the process for testing and executing the code I've written on ACE Cloud 9?

I have integrated ACE on my website to enable users to code freely. My question is, how can I execute the Python code they write? I want to add a run button in the bottom left corner (which I can style using CSS), but I'm not sure how to actually run ...