Conceal (and reveal) hyperlinks as the div's size changes dynamically

Is there a way to resize a div based on the user's decision to hide or show specific content? For example, take a contents page like this one (https://jsfiddle.net/4b1g5jp9/1/). When a user clicks 'hide', I want the div to adjust its size accordingly by hiding all content except for the actual Contents title.

In addition, I only want the 'Show' link to appear if the content is hidden and vice versa.

I attempted to modify some JavaScript code from a similar issue I found online. Here is what I tried:

<script language="javascript">
            function toggle() {
                var ele = document.getElementById("contents-list");
                if (ele.style.display == "block") {
                    ele.style.display = "none";
                } else {
                    ele.style.display = "block";
                }
            }
        </script>

However, the above solution did not work as expected. Any advice or alternative solutions would be greatly appreciated.

Answer №1

Using the event target allows us to determine what should be shown or hidden, making it possible to use this function multiple times on a single page without interfering with each other.

I've also implemented toggle(), which essentially takes care of the if() condition in your code for you.

Check out the code snippet here

$(document).ready(function() {
$('.toggle').click( function(event) {
  $(event.target).parents('.contents-list').find('ul').toggle();
  var newText = $(event.target).text() === '[Hide]' ? '[Show]' : '[Hide]';
    $(event.target).text(newText);
  });
});
 
.contents-list{
    width: 300px;
   
    background-color: #f4f6f9;
    padding: 15px;
    border: 1px solid #b3b4b5;
}

.contents-list ul{
  list-style-type: none;
  margin: 0;
  padding: 0;
  font-size: 14px;
}

#contents-list ul li{
    text-decoration: none;
}

.contents-list ul li a{
    padding-bottom: 2px;
    text-decoration: none;
}

.contents-list a:visited { 
    text-decoration: none; color:blue; 
}
.contents-list ul li a:hover{
    text-decoration: underline;
}

.centerContents{
    text-align: center;
}

.toggle{
    font-size: 12px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="contents-list">
  <div class="centerContents"><b> Contents </b> 
    <a class="toggle" href="#hideContents">[Hide]</a>
  </div>
  <br/>
  <ul>
    <li> <a href="#jumpQ1"> 1.  What is Mobility? </a> </li>
    <li> <a href="#jumpQ2"> 2.  Why Mobility is important </a> </li>
    <li> <a href="#jumpQ3"> 3.  Other </a> </li>
  </ul>
</div>

<div class="contents-list">
  <div class="centerContents"><b> Contents </b> 
    <a class="toggle" href="#hideContents">[Hide]</a>
  </div>
  <br/>
  <ul>
    <li> <a href="#jumpQ1"> 1.  What is Mobility? </a> </li>
    <li> <a href="#jumpQ2"> 2.  Why Mobility is important </a> </li>
    <li> <a href="#jumpQ3"> 3.  Other </a> </li>
  </ul>
</div>

Answer №2

Implement the given HTML structure:

<div id="list-of-contents">
    <ul>
        <li id="centerContents"><b> Table of Contents </b> 
            <a class="hideLinks" href="#">[Hide]</a>
            <a class="showLinks" href="#">[Show]</a>
        </li>
    </ul>
    <ul class="submenu">
        <li> <a href="#jumpQ1"> 1. What is Communication? </a> </li>
        <li> <a href="#jumpQ2"> 2. Why Communication matters </a> </li>
        <li> <a href="#jumpQ3"> 3. Other Insights </a> </li>
    </ul>
</div>

Utilizing jQuery for functionality:

<script type="text/javascript">
    $("#list-of-contents ul li a.hideLinks").click(function(){
        $("ul.submenu").css("display", "none");
    });

    $("#list-of-contents ul li a.showLinks").click(function(){
        $("ul.submenu").css("display", "block");
    });
</script>

Remember to place your jQuery script immediately after the HTML code, or close to the </body> tag. Additionally, ensure you include the jQuery CDN in the head section:

<script src="jquery-4.0.0.min.js" type="text/javascript"></script>
.

NOTE: Instead of manipulating CSS display properties, you can also make use of the Show() and Hide() functions provided by jQuery. More information on these functions can be found Here.

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

Javascript coding for monitoring health status using a three.js health bar

After updating to version r127, my health bar stopped working. I'm not sure what changes I need to make to get it working again. There seems to be an error with the shader in this version. Here is the code: Code: import * as THREE from './thre ...

What could be the reason for the Deeplink not functioning properly with my customized Host and schema?

When I attempted to open my app by clicking a link from the browser, I found that it worked perfectly fine and even received the pathPrefix when using the host and schema provided on test sites. However, when I changed the host to that of my own applicatio ...

Can we attach multiple event handlers to JqGrid events without replacing existing ones?

One technique I use is to always call my default settings whenever a page loads, and then attach a function to loadComplete that handles basic formatting tasks for my grids. However, there are times when I need to execute extra logic simultaneously. Unfor ...

jQuery Carousel: Adjusting the Displayed Items

I've been experimenting with the jQuery Roundabout plugin and I'm curious if there's a way to control the number of images displayed. I have a total of ten pictures, but I only want three of them visible at a time, similar to what is shown i ...

Getting creative with jQuery: Adding a random class using addClass()

The html/css: <style> div.myWords p { display: hidden; } p.show { display: block; } </style> <div class="myWords"> <p>Hello</p> <p>Hola</p> <p>Bonjour</p> </div><!-- myWords --> Is ther ...

In Vue.js, the v-model connects a value that can be easily changed to a different value

I just connected the second input box to v-model of changedPrice.c1 Currently, it is set to display roundFee as $5000. However, the second input box allows for new input numbers. In this scenario, I am unsure which method to use. Should I go with compute ...

How to eliminate spaces while preserving line breaks in a textarea using JS or jQuery

I have been trying to figure out how to remove extra spaces from the beginning and end of lines while keeping the line breaks intact. Here's what I attempted: function removeSpaces(string) { return string.split(' ').join(''); } ...

Centering a div vertically within another div

Can you help me insert the flight duration in the middle-left section of each blue line? I've tried some methods but haven't been successful so far. This is the current layout: https://i.sstatic.net/edOfg.png Example on CodePen HTML structure ...

Tips for determining the presence of a query string value using JavaScript

Is there a way to detect the presence of q= in the query string using either JavaScript or jQuery? ...

Challenges with Selenium Web Scraping

I'm currently in the process of creating a web scraper that extracts data from the Beatport top 100 chart. However, I've encountered an issue where some items are successfully located while others result in errors. def scrape_beatport(): user ...

Trouble with $scope.currentPage not updating correctly in Angular UI Pagination

Recently, I've been working on this codepen project. In it, I'm utilizing the function '$scope.pageChanged' to monitor page changes. $scope.pageChanged = function() { $log.log('Page changed to: ' + $scope.currentPage); }; H ...

How can I hide a div using Ajax and show success in the following div?

I'm utilizing ajax to implement search functionality onkeyup. The goal is to display all results if the textbox is empty, but when the textbox contains text, only show results that match. <input type="text" onkeyup="searchme()" id="search_id" /&g ...

Fixing CreateJS in Adobe Animate HTML5 Advertisement for Internet Explorer versions 9 and 10

As I work on creating an HTML5 ad using Adobe Animate CC, I encounter a minor setback. While testing the ad, I notice that it displays perfectly in most browsers except for Internet Explorer versions 9 and 10. It's interesting to see that according ...

What is the most effective way to view all globally installed npm packages on my device?

While it's easy to check local dependencies in the package.json file, I'm curious about how one can identify the global packages that are currently installed on a Windows machine using npm. ...

The JQuery command to set the display property to "block" is not functioning as expected

When trying to toggle the visibility of my TextBox based on a selected value in a RadiobuttonList, I initially wrote the following code: $("#<%= rbtnIsPFEnabled.ClientID %>").click(function () { pfno = $("#<%= txtPFNo.ClientID %&g ...

Looking for the optimal method to display numerous lines of text in HTML, one by one, at intervals of 60 seconds?

I'm working on a display page for my website. The main text in the center needs to change every 60 seconds. I have over 150 individual lines of text that I want to cycle through on the page. What would be the most efficient way to load all these te ...

What is the functionality of Nodejs EventEmitter.once() method?

Exploring the nodejs source code (LOC 179), we come across the following scenario: EventEmitter.prototype.once = function(type, listener) { /** ... **/ function g() { /** ... **/ } g.listener = listener; // => ??? this.on(type, g); return ...

Steps for adding a React Class Component into a Modal that is not within the React Tree

Our project is built using PHP MVC Framework and we initially used jQuery as our main JavaScript framework for handling UI activities. However, we have now transitioned to using React.js. My query is about how to inject or append a React Functional/Class-b ...

What is the importance of setting up an HTTP server?

Can anyone explain why, in nodeJs programming with javascript, it is necessary to establish a server using the http module, even though one could simply utilize the fs module for reading, writing, and updating data stored in a json file? ...

Is there a way to activate a function when clicking on the "View larger map" option within the Google Maps

I am currently in the process of creating a cordova application with ionic and angularjs, where I am using the google maps embed API to include a map within the app. https://developers.google.com/maps/documentation/embed/guide https://i.sstatic.net/TOd ...