When the LI element is clicked, it triggers the display of another LI element without affecting the rest of the

New to the web development scene and trying to figure out how to create a collapsible text feature using HTML, JavaScript, and JQuery. I've got the styling down but struggling with the scripting part. Here's an example of what I'm trying to achieve:

Imagine having a list of book titles as links, and when you click on one, more information about the book expands below it. Clicking on another title collapses the previous book info. Here's a snippet of the HTML code:

<li class="parent"><a href="#">The Wheel of Prison Operations: Useful Tool for Successful
Management of Security</a></li>
<ul class="story">
  <li>Publication, authored “The Wheel of Prison Operations: Useful
    Tool for Successful Management of Security”. June/July1999 issue
    of “Correctional Security Report” a national publication on
    correctional security operations.</li>
  </ul><br>

  <li class="parent"><a href="#">Use Of Force - Current Practice and Policy</a></li>
    <ul class="story">
      <li>Book on Use of Force in Prisons, September 1998, asked to co-author a book on use of force in
        prisons to be published by the American Correctional Association on use of force in US and
        Canadian Prisons. Use Of Force - Current Practice and Policy Published November 1999.
        Advertised as ACA “Bestseller” for several years.</li>
      </ul><br>

Below are the two JavaScript attempts I've made so far:

    <script>
$(document).ready(function(){
$(".story").css("display", "none");

$("li.parent").click(function() {
$(this).next(".story").slideToggle();
});
});
</script>

I would appreciate any suggestions or feedback on how to improve my current approach. Just exploring this new territory and eager to learn more. Thank you!

Answer №1

To begin with, it is important to note that having <br> and <ul> as siblings of a <li> element is not valid HTML. It is recommended to place the BR and UL tags inside the LI elements.

Once you have corrected your HTML markup, you can consider implementing functionality using jQuery or CSS alone.

A more structured HTML markup example would look like this:

<ul id="books">

  <li>
    <h2>Book 1</h2>
    <div>
      Book 1 story goes here
    </div>        
  </li>

  <li>
    <h2>Book 2</h2>
    <div>
      Book 2 story goes here
    </div>        
  </li>

</ul>

This updated HTML structure would also require adjustments in your jQuery code for proper selection and handling of elements, especially for sliding the book content story.

Below is a quick demonstration:

jQuery(function($){

  var $allBooksStories = $("#books li > div");

  $("#books h2").click(function(){
    $allBooksStories.slideUp();
    $(this).next("div").stop().slideToggle();
  });

});
*{margin:0;}
#books div{
  display:none; /*Initially hide all stories*/
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="books">

  <li>
    <h2>Book 1</h2>
    <div>
      Book 1 story goes here
    </div>        
  </li>

  <li>
    <h2>Book 2</h2>
    <div>
      Book 2 story goes here
    </div>        
  </li>

</ul>

Answer №2

Here's a suggestion: Make sure to toggle only the story ul under the clicked parent li, without affecting all other story ul elements. I also noticed that you didn't mention a visibility CSS class in your original post, so I utilized toggle() instead.

 $(document).ready(function() {
      // Hide all story ul elements by default when the page loads
      $('.story').hide();

      $('.parent').click(function() {
          // Find the specific story under the clicked parent (referenced as $(this))
          $(this).find('.story').toggle();
      });
    });

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

How do you obtain the string name of an unknown object type?

In my backend controllers, I have a common provider that I use extensively. It's structured like this: @Injectable() export class CommonMasterdataProvider<T> { private readonly route:string = '/api/'; constructor(private http ...

"Upon refreshing the browser, an Angular map loses its positioning and appears blank

I have implemented a LeafLet map in my Laravel 9 system, which is functioning properly with some exceptions. Here's how it looks like: https://i.stack.imgur.com/kcuVr.jpg The code in the controller (CompetitionsMapController.php) is as follows: ...

How to change class names dynamically in Vue.js?

I am looking for a way to dynamically change the background color based on a review rating using Vue.js. Ideally, I would like to achieve this with the following code: <div class="review" :style="reviewColor(hotel.average)"> In my methods section, ...

The bug in Polymer 1.0 where a custom element is causing issues when clicking under the toolbar

Issues have arisen with a custom element I created, named <little-game></little-game>. Here is the template code for <little-game></little-game>: <template> <a href="{{link}}"> <paper-material elevation=& ...

WordPress is consistently returning 0 when using ajax, however in certain instances it should be returning a value of

I have developed an AJAX function within WordPress for my plugin. In the plugin construct, I am setting up the AJAX callback: public function __construct() { return $this->register(); } /** * Register all new files in WooCommerce hooks */ public ...

Unable to dynamically populate Bootstrap select with real-time search and multiple options using jQuery

How can I dynamically populate a select statement with options retrieved from PHP code? <select name='friends[]' id='friends' class='selectpicker show-tick form-control' data-live- search='true' multiple& ...

Using jQuery, how can I dynamically change the stacking order of an element when clicked?

I'm struggling to change the z-Index on button click. I have a static image and a dynamic div, and I want to send the #imgDiv1 behind the static image. Unfortunately, despite trying everything, I haven't been able to achieve this. You can check ...

Guide to directing a user through an Ajax call to a particular Controller and action

Here is a custom JavaScript function that updates data when the Update button is clicked. function UpdateData() { var obj = { "testData": $("#hdn_EditdsVal").val(), "feature": $("#hdn_EditdsVal").val() }; $.ajax({ url: ...

Oops! Next.js Scripts encountered an error: Module '../../webpack-runtime.js' cannot be located

Looking to develop an RSS script with Next.js. To achieve this, I created a script in a subfolder within the root directory called scripts/ and named it build-rss.js next.config.js module.exports = { webpack: (config, options) => { config.m ...

CSS Malfunction in Chrome: Some Code Not Displaying Properly

Below is the content of my main.css file: body { font-family: josefin; } .splash-content { text-align: center; } .register-button { color: #6A136C; width: 300px; height: 100px; border: 5px solid #6A136C; } .btn { padding: 1 ...

Leveraging an external TypeScript library in a TypeScript internal module

Imagine you find yourself in a situation where you need to utilize a typescript/node library within an internal module that is spanned across multiple .ts files. ApiRepositoryHelper.ts import * as requestPromise from "request-promise"; module ApiHelp ...

Height not being generated by Div element

I am encountering an issue with a div element that contains an h2 and three nested div elements. Despite not explicitly setting a height for the container div, it is not expanding to accommodate the varying heights of the inner divs. This problem is causin ...

Experience the power of Kendo UI Date Picker combined with AngularJS. When the datepicker is initialized, it starts

Check out my code snippet below: When the datepicker loads initially, it appears empty. However, if you remove ng-model from the directive template, the datepicker displays its initial value correctly. Yet, changing the selected date does not mark the fo ...

Ways to transition to an iframe window

I am having difficulty selecting an iframe popup window as it is not coming into focus. Below is the image of the popup window along with the button I am attempting to click: https://i.stack.imgur.com/VzkOX.png This is the code snippet that I have been ...

What is the best way to update a local variable in JavaScript using Ajax requests?

function validate_authentication(){ var is_authenticated = false; $.ajax({ type: "POST", url: "/account/islogin/", data: "", async: "false", success: function(data) { if (data == "null") { ...

Unusual outcome observed when inputting a random number into HTML using JavaScript

In my HTML file, I am trying to input a number within 50% of a target level into the "Attribute" field. Here is the code: <!DOCTYPE html> <html> <body> <input type = "number" name = "playerLevel" onchan ...

Struggling to connect CSS and JavaScript files to index.html on Heroku while utilizing Node.js

Trying to set up a Tic Tac Toe game in my app.js file, but encountering some issues with linking files in index.html. app.set('port', (process.env.PORT || 5000)) //serve static files in the public directory app.use(express.static('public& ...

Dependencies in Scala.js for CSS styling

I am currently having an issue implementing Scala.js with the bootstrap library. Including the js file was a simple and straightforward process: jsDependencies +="org.webjars" % "bootstrap" % "3.3.7-1" / "bootstrap.js" minified "bootstrap.min.js" However ...

Utilizing jQuery TableSorter Scroller: How to Achieve Scrolling with Keydown Focus

Apologies for any language barriers. I am currently utilizing tablesorter 2.0 along with scroller functionality. On my page, the table scrolling function works when I interact with the table directly. However, I want the scrolling to happen automatically ...

Is there a Container with a Heading in Material UI?

Does anyone know how to create a container with a top title like the one shown in this screenshot: I've attempted using Box or Paper components, but I can't seem to find the option for a top title. Any suggestions? Thanks in advance for any ass ...