Toggle the visibility of a hidden div by clicking a button

After spending several days working on this project, just when I thought it was perfect, I had to completely restructure the entire page. Now I'm feeling stuck and in need of some help. The issue is that I have three images with buttons underneath each of them. When a button is clicked, I want it to display hidden content at the bottom of the page while hiding any previously visible content. Additionally, I want the page to automatically scroll down so that the top of the div aligns with the top of the window. Here is what I currently have in terms of code:

$("#Template1").click(function() {
var div = document.getElementById('#content1');
if (div.style.display !== 'none') {
    div.style.display = 'none';
}
else {
    div.style.display = 'block';
}
});
.cell1 {
  display: table;
  text-align: center;
  table-layout: fixed;
  border-spacing: 10px;
  width: 100%;
}
.cell2 {
  display: table;
  text-align: center;
  table-layout: fixed;
  border-spacing: 10px;
  width: 100%;
}
(Column {
  vertical-align: top;
  width: 500px;
  display: table-cell;}
#img1,
#img2,
#img3 {
  display:inline-block;
  align:center;
  padding: 10px 20px 10px 20px;
  vertical-align:top
}
#Template1,
#Template2,
#Template3 {
  margin-top:14px;
  background-color:#cb3778;
  font-family:Arial;
  font-size:20px;
  width:260px;
  float:center;
  color:#FFF;
  cursor:pointer;
}
.Template0 {
  display:block;
  clear:both;
  width:100%;}
#content1,
#content2,
#content3 {
  display:none;
  clear:both;
  width:100%;}
@media only screen and (max-width:600px){
*[class*="mobile-only"]{
display:block !important;
max-height:none !important;}
.mobile{
display:block !important;
margin-top:14px !important;
margin-bottom:14px !important;
margin-left:0px !important;
padding:10px 0 10px 0 !important;}
.mobile-img{
display:block !important;
Width:100% !important;
align:center !important;}
.mobile-column{
display:block !important;
Width:100% !important;
align:center !important;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div align="center">
  <div class="Column mobile-column">
    <div class="cell1">
      <img width="400" height="355" border="0" src="col1-2.jpg" class="mobile-img" alt="Template 1" />
    </div>
    <div class="cell2 mobile" id="Template1">Template1</div>
  </div>
  <div class="Column mobile-column">
    <div class="cell1">
      <img width="400" height="355" border="0" src="6pack-1.jpg" class="mobile-img" alt="Template 2" />
    </div>
    <div class="cell2 mobile" id="Template2">Template2</div>
  </div>
  <div class="Column mobile-column">
    <div class="cell1">
      <img width="400" height="355" border="0" src="hero-1col.jpg" class="mobile-img" alt="Template 3" />
    </div>
    <div class="cell2 mobile" id="Template3">Template3</div>
  </div>
</div>

<div align="center">
  <div align="center" style="padding-top:150px;" id="content1">sample demo txt two 2</div>
  <div align="center" style="padding-top:150px;" id="content2">sample demo txt two 3</div>
  <div align="center" style="padding-top:150px;" id="content3">sample demo txt two 4</div>
</div>

Answer №1

After inputting the code provided into JSFiddle for experimentation, it became evident that a mixture of vanilla JS and jQuery was present, along with the absence of essential functions required for animating the window.

A crucial enhancement made to the code was assigning an ID to the div containing each hidden content block. This facilitated easy targeting of the container for JavaScript functionalities. The revised JS code looked like this:

$("div[id^=Template]").click(function() {
    //Store the ID of the clicked item in a variable
    var id = $(this).attr('id');

    //Select the hidden content with the corresponding name
    var theContent = $('#contents').find('.' + id);

    //Hide all hidden elements before displaying the clicked one
    $('#contents').children().hide();

    //Display the correct content based on the Div ID
    theContent.show();

    //Scroll the body down to the revealed content
    $('body').animate({ scrollTop: $('#contents').offset().top }, 'fast');
});

This function targets all "Template" divs designated as clickable, takes the ID of the clicked item, and executes the necessary actions (commented for clarity).

You can view the complete and functional JSFiddle here: https://jsfiddle.net/your37or/

Best of luck!

Answer №2

It appears that you are utilizing both jQuery and raw DOM manipulation in your code. I recommend choosing one method, preferably jQuery, and sticking with it for consistency. The code snippet below demonstrates how to achieve this:

$("#Template1").click(function() { $('#content1').toggle(); });
.cell1 {
  display: table;
  text-align: center;
  table-layout: fixed;
  border-spacing: 10px;
  width: 100%;
}
.cell2 {
  display: table;
  text-align: center;
  table-layout: fixed;
  border-spacing: 10px;
  width: 100%;
}
.Column {
  vertical-align: top;
  width: 500px;
  display: table-cell;
}
#img1,
#img2,
#img3 {
  display: inline-block;
  align: center;
  padding: 10px 20px 10px 20px;
  vertical-align: top
}
#Template1,
#Template2,
#Template3 {
  margin-top: 14px;
  background-color: #cb3778;
  font-family: Arial;
  font-size: 20px;
  width: 260px;
  float: center;
  color: #FFF;
  cursor: pointer;
}
.Template0 {
  display: block;
  clear: both;
  width: 100%;
}
.Template1,
.Template2,
.Template3 {
  display: none;
  clear: both;
  width: 100%;
}
@media only screen and (max-width: 600px) {
  *[class*="mobile-only"] {
    display: block !important;
    max-height: none !important;
  }
  .mobile {
    display: block !important;
    margin-top: 14px !important;
    margin-bottom: 14px !important;
    margin-left: 0px !important;
    padding: 10px 0 10px 0 !important;
  }
  .mobile-img {
    display: block !important;
    Width: 100% !important;
    align: center !important;
  }
  .mobile-column {
    display: block !important;
    Width: 100% !important;
    align: center !important;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div align="center">
  <div class="Column mobile-column">
    <div class="cell1">
      <img width="400" height="355" border="0" src="col1-2.jpg" class="mobile-img" alt="Template 1" />
    </div>
    <div class="cell2 mobile" id="Template1">Template1</div>
  </div>
  <div class="Column mobile-column">
    <div class="cell1">
      <img width="400" height="355" border="0" src="6pack-1.jpg" class="mobile-img" alt="Template 2" />
    </div>
    <div class="cell2 mobile" id="Template2">Template2</div>
  </div>
  <div class="Column mobile-column">
    <div class="cell1">
      <img width="400" height="355" border="0" src="hero-1col.jpg" class="mobile-img" alt="Template 3" />
    </div>
    <div class="cell2 mobile" id="Template3">Template3</div>
  </div>
</div>

<div align="center">
  <div align="center" style="padding-top:150px;" class="Template1" id="content1">sample demo txt two 2</div>
  <div align="center" style="padding-top:150px;" class="Template2" id="content2">sample demo txt two 3</div>
  <div align="center" style="padding-top:150px;" class="Template3" id="content3">sample demo txt two 4</div>
</div>

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

Creating a platform where your choices determine the results is my goal for a new website

My goal is to create a unique website that generates text based on responses to multiple choice questions. For instance, users can select symptoms from a list of options and receive recommended medicine at the end of the process. I'm wondering where ...

Positioning a material UI dialog in the middle of the screen, taking into account variations in its height

Dealing with an MUI Dialog that has a dynamic height can be frustrating, especially when it starts to "jump around" the screen as it adjusts to fit the content filtered by the user. Take a look at this issue: https://i.stack.imgur.com/IndlU.gif An easy f ...

Retrieving the response data from a getJson request

I am currently working on implementing a function that will perform an action based on the response text received from a specific ajax call. However, I am struggling to access the response text field in my code. Here is the snippet: var response = $.getJS ...

What's the reason for the inability to resize fieldset using both?

Can someone explain why the resize control is not enabled on the fieldset element? The documentation mentions that resize does not work with: Inline elements Block elements that have overflow set to visible fieldset { resize: both; overflow: h ...

Unable to adjust the dimensions of a Mailchimp input field

Having some trouble customizing my Mailchimp form a bit and could use some assistance. Snippet of the code: <!-- Begin MailChimp Signup Form --> <link href="//cdn-images.mailchimp.com/embedcode/horizontal-slim-10_7.css" rel="stylesheet" type=" ...

Inconsistencies in JavaScript comparison across various web browsers

Here is a snippet from my JavaScript code var dataList = eval(strArray[0]); for (i = 0; i < dataList.length; i++) { console.log(((dataList[i].isFollowed == 0) ? "Follow" : "Unfollow")); } However, this code exhibits varying behavio ...

What steps can be taken to send the user to the login page after their session token has expired

Currently, I am using a Marionette + Node application. I have noticed that when the token expires, the application does not respond and the user is not redirected to the LogIn page. My question is, how can I set up a listener to check the session token s ...

Steps to Display a JavaScript Function Two Times on a Single Page

Hey there! I'm currently working on a project where I need to display the output of my function in two separate divs. However, when I try to simply output the same ID, it messes up the whole code and the output becomes null. Here's the code snipp ...

Using an external call to trigger the revert method in jQuery UI

My draggable event setup looks like this: $(ids.label).draggable({ containment: ids.wrapper, revertDuration: 100, revert: function(event) { $(this).data("draggable").originalPosition = { top: $(this).data('origionalTo ...

What are the steps to generating and sharing 'npm create' scripts?

I am looking to develop and release a script on npm that functions similarly to: npm create qwik@latest or yarn create next-app --typescript However, I am unsure where to begin. Despite searching extensively online, I have not been able to find any helpf ...

Initialize global variables for jQuery objects

Here is an example of some jQuery code that I have been working on. In this code, variables are declared at a global scope, but I have been wondering if it is possible to declare jQuery objects in a similar way to how classes are declared with the cn prefi ...

How to Delete an Added Image from a Dialog Title in jQuery

I've tried multiple solutions from various sources, but I'm still struggling to remove an image from a dialog. Whenever I attempt to do so, I end up with multiple images instead of just one. It's important to note that I only want the image ...

A guide to testing redux API using Node.js

I'm diving into the world of nodejs and redux as a beginner. I managed to install node v7.10 on my computer. While reading through the Redux documentation, it mentioned that I should be able to test the action, reducer, and store API without a user in ...

What is the best way to ensure only one item is being selected at a time?

In the initial state, I want 'ALL' to be automatically selected. Clicking on another item should change the classes so that only 'this' has the class and the others do not. However, I am facing an issue where 'ALL' cannot be r ...

Trouble encountered when attempting to override styles in Material UI's TableRow

I am attempting to customize Material UI's default styles in order to create a margin between each TableRow. Despite my efforts, it appears that the override is not being reflected in the user interface. ...

Symfony: Enhancing array elements with updated bootstrap progress bar

I'm facing a challenging issue that I need help with. Currently, I have a command set up to send a large number of emails (around 300 or more) every 5 minutes using cron in order to distribute a newsletter. My goal is to keep track of how many emails ...

Synchronize your store by utilizing cookies in the nuxtServerInit function of NuxtJS

I am currently working with NuxtJS's auth module and attempting to retrieve the Bearer token along with a custom cookie that holds a sessionType during nuxtServerInit in order to update the store through a mutation. However, I am facing an issue where ...

Navigating through elements in the hidden shadow DOM

Can elements within the Shadow DOM be accessed using python-selenium? For example: There is an input field with type="date": <input type="date" name="bday"> I want to click on the date picker button located on the right and select a ...

Combining Arrays in AngularJS: A Step-by-Step Guide

I have two arrays with dynamic values: $scope.objectName = [{ Name: '' }]; $scope.propertiesElement = [{ Key: '', Value: '' }]; How can I concatenate these arrays to achieve the following result? [{Name:''},{ Key: ...

What is the best way to ensure that the operations are not completed until they finish their work using RX

Is there a way to make RXJS wait until it finishes its work? Here is the function I am using: getLastOrderBeta() { return this.db.list(`Ring/${localStorage.getItem('localstorage')}`, { query: { equalTo: fa ...