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

What is the best way to customize the appearance of chosen selections in the MUI Autocomplete component?

I'm currently facing an issue with changing the style of selected options in MUI when the multi option is enabled. My goal is to alter the appearance of all highlighted options. Any assistance on this matter would be greatly appreciated, thank you! ...

The H1 heading sets the stage, layered behind the captivating background image

I'm having trouble getting the h1 header to stand out over a background image with a box-like color for the header. Every time I make changes to the h1, they seem to be hidden behind the background image and only briefly show before being covered up. ...

Unable to successfully submit a form using PHP

I am currently working on a PHP page that retrieves data from MySQL. The goal is to fetch a list of objects from the database, display each object in a separate form for editing, and then save only the edited values. However, I am encountering difficulties ...

Using a ForEach iteration to loop through a table in C# and jQuery

My generated table structure is as follows: <div class="row"> <div class="col-md-12"> <div id="calendar"></div> <table id="report" class="table"> <thead> <tr> <th> ...

Preventing Users from Accessing a PHP Page: Best Practices

I'm currently focusing on a problem that involves restricting a user from opening a PHP page. The following is my JavaScript code: <script> $('input[id=f1email1]').on('blur', function(){ var k = $('inp ...

Tips for linking together AJAX requests with vanilla JavaScript

I have searched extensively for solutions using only plain JavaScript, but I have not been able to find a suitable answer. How can I tackle this issue with pure JavaScript given that my repetitive attempts haven't yielded any results? function ...

Stop the iframe video when the modal is closed

I'm currently developing a website that incorporates the code showcased in this tutorial to launch a modal window featuring an iframe for playing YouTube or Vimeo videos. The issue arises when, as mentioned in the comments on the tutorial page, there ...

Breaking Down the Process of Exporting a Next.js Static Website into Manageable Parts

I am facing memory issues while building my website using Next.js's Static HTML Export. The site has a large number of static pages, approximately 10 million. Is it feasible to export these pages in batches, like exporting 100k pages in each build ite ...

Having difficulty saving data in database using Ajax request from a Chrome extension

I am currently working on an extension that captures the page URL and saves it in a database once the user clicks the submit button. However, I have encountered a roadblock and believe there might be a missing piece in the extension setup that I cannot pi ...

Steps for referencing an autogenerated id in a Firestore collection

I need assistance updating a 'progress' field in a document with an autogenerated ID (using Firestore) every time the progress button is clicked. https://i.stack.imgur.com/hZieN.png Despite my attempts, nothing seems to work. Here is the method ...

Tips for eliminating duplicate entries in ag grid using Angular

Is there a way to eliminate the recurring assetCode entries in ag grid? The PRN and PRN1 values seem to be repeating unnecessarily. Check out the code below: list.component.ts ngOnInit() { this.rowData.push( { 'code': 'Machi ...

Looping through JSON data using jQuery's for loop

I am attempting to create a for loop in order to condense and simplify the code. The goal is to have a loop that runs 5 times, incrementing the value by +1 each time for the (filmi.Movies[0].Title). var i = (filmi.Movies[0].Title); for(i=0; i<5; i++){ ...

Could there be a more efficient method to enable support for all video formats?

I have a case statement in my video validation function that checks for specific file extensions of video formats. However, I am wondering if there is a shorter way to write the code in order to allow all video formats instead of creating a long list of al ...

Failure to Trigger AJAX Success Event

I am facing an issue while trying to retrieve a JSON string using an ajax call with JQuery. Despite getting a code 200 and success from the complete method, the success method itself is not triggering. function initialize() { $.ajax( { type ...

How can I incorporate a spinning cog from Font Awesome into a jQuery click event?

I am looking to incorporate a spinning font awesome cog while the data is being fetched and remove it once the process is complete. Here is the HTML snippet that needs to be inserted: <i class="fa fa-spin fa-cog"></i> And this is the accompa ...

ExpressJS: How to resolve the undefined error in Express session

After using express-generator to create my project, I installed the express-session package. Below is how express-session is ordered in my app: app.js var expressSession = require('express-session'); app.use(logger('dev')); app.use( ...

Transferring information to React (Native) hooks in a way similar to how it is done

Transitioning to Hooks in React Native has been a new learning curve for me, especially when it comes to passing data to child elements. In the past with class-based components, passing props was as simple as using XML-style syntax. A Simple Example using ...

Is there a solution for the continuous automatic incrementing of the jQuery UI spinner that occurs when I right-click on it?

Only Linux and Mac OS users are facing this particular issue, indicating a potential bug with the jQuery spinner. The bug also affects the spinner located at the following link: https://jqueryui.com/spinner/ <input class="spinner"/> $(".spinner"). ...

JavaScript: Efficiently Sorting a Multidimensional Array

Here is the array that needs to be sorted based on the third item: const array = [ [1, "Convention Hall", "Mumbai", 10, "XYZ Company"], [2, "Auditorium", "Delhi", 10, "ABC Company"], [3, "CenterHall", "Bangalore", 10, "ZZZ Company"], ... ...

problem with accessing a website input area

Upon clicking outside the "subheader", I need to display the words "register" and "login" again, unless something is typed into the input fields... that's all there is to it, just click outside the subheader $(document).ready(function() { $(&ap ...