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

Is there a way to create a scroll down and scroll up button that is located outside of the scroll box

A game designer challenged me to create a custom scrollbar with unique up and down button styles, as well as a custom-looking scrollbar. I wanted to achieve this without using the native browser scrollbar on Windows in Google Chrome. I attempted the follo ...

Having trouble loading popper.js using Laravel mix and webpack

I have been working on my project with Bootstrap 4 beta and Laravel 5.4, using npm and Laravel mix to load my JavaScript dependencies. Everything was going smoothly until I encountered an error while trying to use Bootstrap JavaScript methods. The error me ...

As the user types, automatically format the input field for a seamless and intuitive experience

My current application is running on Angular 1.3.10 I have implemented a jQuery function to automatically add a backslash to the expiration input field once the user types the third number. Although it was a quick fix, I now aim to move this functionality ...

Can anyone shed some light on why the CSS code is not functioning properly within my HTML file?

My CSS doesn't seem to be working in my HTML. I have linked it correctly, but it's not displaying properly - even showing empty in the CSS tab of Chrome Inspector. The links are there, so I'm not sure why it's not functioning correctly. ...

My efforts to resolve the issues in my code have been ongoing, but unfortunately, I have been unable to find a solution

I'm struggling to insert my contact form code into the contact tab without it interfering with the tab bar. I want the form to appear in the middle of the page when the tab is clicked. I've tried various placements for the code but none seem to ...

jCarousel jQuery plugin malfunctioning on iPhone devices

I am currently implementing a vertical carousel to showcase video thumbnails using sorgalla.com/projects/jcarousel/. When the thumbnails are clicked, the source of the larger video changes accordingly. My website has two versions - one with Flash navigati ...

Adjust the size of items using a background image that covers the element

I'm struggling with a seemingly simple task here. I've been experimenting with different methods, but I just can't seem to grasp it. On the front page of my website, there is a cover section that contains a logo and a button: <section i ...

Replace HTML elements with AJAX and JavaScript

Working with MySQL data in pyramid presents a challenge as I need to dynamically change an HTML if statement based on the results from JS ajax calls. The main page receives data from views.py and passes it to the .mak script. The key views here are the ma ...

Tips for capturing all mobile events in Angular

Trying to capture all mobile events like touch and swipe, I have added event listeners at the document level: document.addEventListener('tap', trackTouchActivity, false); document.addEventListener('swipe', trackTouchActivity, false ...

Having trouble retrieving react environment variables from process.env?

When developing my React App, I utilized a .env file to securely store some essential API keys. However, as I attempted to access these variables using process.env, I encountered an issue where the values appeared to be set as undefined. To launch the app ...

Loading screen featuring an outlined blueprint of design elements

Can anyone identify the technology or language used to create the preloader screen on websites like the one shown in this link? The elements have a sweeping shine effect while loading. This style of preloader screen can be seen on popular websites such as ...

Sending a JavaScript value to PHP after a quiz has been completed

I've created a web page where users can take quizzes. These quizzes dynamically generate questions using JavaScript each time they are accessed. Disclaimer: I'm fairly new to JavaScript. Once the user completes the quiz, they receive their fina ...

Identifying the Back Button in Vue-Router's Navigation Guards

For my specific situation, it is crucial to understand how the route is modified. I need to be able to detect when the route changes due to a user clicking the back button on their browser or mobile device. This is the code snippet I currently have: rout ...

Tips for utilizing the GROUP BY Clause in Sequelize along with associations

How can I properly utilize the GROUP BY clause in Sequelize to combine data from two tables? This is the SQL query I am attempting to translate into Sequelize: SELECT products.product_name, SUM(order_list.quantity) FROM products JOIN order_list ON prod ...

Utilize JSON data in d3.js for creating a scatterplot visualization

I have recently started working with d3.js and I'm facing some challenges. From what I understand, the second parameter passed in d3.json() is used to process data from a JSON file. Here is my code: d3.json(base_url() + "data/data.json", clean_data) ...

Unusual occurrences observed with the table

While working with tables, I've noticed an unusual effect. Take a look at the two fiddles below. http://jsfiddle.net/v5co5uy7/ (why are the cells in the left column pushed down?) http://jsfiddle.net/v5co5uy7/1/ (the cells in the left column are posi ...

Angular fails to include the values of request headers in its requests

Using Django REST framework for the backend, I am attempting to authenticate requests in Angular by including a token in the request headers. However, Angular does not seem to be sending any header values. Despite trying various methods to add headers to ...

A guide to implementing div wrapping in HTML

I'm in the process of using flexbox on my website. I have 10 div elements that I want to wrap around each other closely without any gaps between them. My goal is to have "4" positioned to the right of "1", instead of creating a new row and moving dow ...

Observing the innerHTML of a Vue component

Currently, I am utilizing an npm package called vue3-markdown-it to display markdown within some of my content. When the component renders, I need to access its innerHTML and make customized modifications before displaying it in my div. However, there is ...

"Utilizing Node.js and Express to return JSONP data based on

For some reason, my Express application is giving me a strange result when using res.jsonp. It looks like this: /**/ typeof jsonp1406719695757 === 'function' && jsonp1406719695757({"published":true,"can_add_to_cart":true,"updated_at":"20 ...