Fade in and out list items while adjusting the height of the container

Check out this code snippet I put together in Codepen:

<div class="slider">
  <ul>
    <li id="S1">
      <div class="txt"><p>First slogan</p></div>
      <div class="img"><img src="http://placehold.it/800x180" /></div>      
    </li>
    <li id="S2">
      <div class="txt"><p>First slogan</p></div>
      <div class="img"><img src="http://placehold.it/800x280" /></div>
    </li>
  </ul>
  <a href="#S1">1</a>
  <a href="#S2">2</a>
</div>

I want to achieve the following functionality with JQuery:

  1. Initially, only the first LI item should be visible.

  2. When an A tag is clicked and its href value does not match the ID of the visible LI:

    • Fade out the current LI;
    • Resize the Slider container DIV Height to the height of the LI to be displayed;
    • Fade in the LI to be displayed.

Can someone help me implement this with JQuery?

Thanks, Miguel

Answer №1

Here is a swap function that should do the trick:

To begin, add the currentStory class to both the first LI and A tags:

<li id="S1" class="currentStory">
<a href="#S1" class="currentStory" id="S1">1</a>

It's important for the links to have the same ID as their corresponding <li> items in order for this function to work correctly.

<a href="#S1" class="currentStory" id="S1">1</a>
<a href="#S2" id="S2">2</a>

$(document).ready(function() {

  function switchStory(storyName){
$('.slider li.currentStory').hide();
$('.slider li.currentStory').removeClass('currentStory');
$('.slider [id = ' + storyName + ']').addClass('currentStory');
$('.slider [id = ' + storyName + ']').fadeIn("slow");
  }

  $(function() {

     $('.slider li:not(".currentStory")').hide();
        $('.slider a').click(function(){
            switchStory($(this).attr("id"));
            return(false);
        });
   });

});

I hope this helps with what you're trying to achieve.

Answer №2

Check out this sample I created, simplifying CSS rules with jQuery.

Remember to add your media queries back in.

The jQuery code:

$(document).ready(function(){
    $('a').click(function(e){
       var id = $(this).attr('href').split("#").pop();
       var li = $('.slider ul li');
       $('.slider ul li').each(function(key,v){
           //show hidden linked li
           if($(this).is(':hidden') && id == $(this).attr('id')){
                $(this).fadeIn(500).slideDown("fast");
            }
            //do nothing if already visible
            else if($(this).is(':visible') && id == $(this).attr('id')){
            }
            else{
               $(this).fadeOut(100,function(){$(this).slideUp("fast")});
            }
        });
    });
});

DEMO

Answer №3

If you're facing issues, consider giving the jQueryUI accordion a try.

Here's a helpful link: Accordion

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

Round progress indicator with directional pointer

I've been working on creating a round progress bar that features an arrow at the front. This is my current progress: HTML Code: <!-- Container --> <ul class="progress"> <!-- Item --> <li data-name="Item 1& ...

Restricting the number of lines within a paragraph in Angular 2

Is there a method to limit the number of lines in a <p> tag and add an ellipsis (...) at the end? Using character count for truncation doesn't work well as the width of the element varies according to device screen size. ...

Images and videos are not appearing on GithubPages when viewed online, but they are visible

Check out my GitHub repository: https://github.com/Snipervuk/ChristianMilicevic I'm encountering an issue where my HTML images or videos are not displaying on my GitHub pages online, but they do display locally. I've attempted several solutions ...

Transform HTML into a PDF document using ABCpdf

Currently, I am working on developing a web application that involves the use of ABCpdf to convert HTML pages into PDF files. The HTML pages in question contain dynamic elements implemented using JavaScript. In an attempt to address this issue, I have exp ...

series of lines including <ListItemText>

https://i.sstatic.net/L8FUC.png I have been using Material-ui with react. Currently, I am working on creating a list in React that contains long text. However, when the text is too long, it is displayed as a single line which is not what I want. I would ...

What is the best way to keep horizontal divs aligned in a row with margins between them within a wrapper?

I have arranged three divs in a row with a 10px margin between them within a responsive layout. Currently, the divs have margin-left: 10px; margin-right: 10px; to create spacing. However, I aim to align them perfectly within the wrapper without any extra ...

Increment the name field automatically and track the number of auto-increment variables being sent through serialization

I am trying to implement a functionality where users can add more inputs by pressing a button, each representing an additional 'guest'. The issue I am facing is with auto-incrementing the JavaScript so that new inputs are added with an incremente ...

Calculate the number of characters in one line inside a contentEditable DIV using Jquery

Can you accurately count the number of characters in a single line? For example, if we have a paragraph with 5 lines, is there a way to count the characters in each individual line? All the information I've come across only seems to tally the total ch ...

Created a notification for when the user clicks the back button, but now looking to remove it upon form submission

My survey is lengthy and I don't want users to accidentally lose their data by clicking the back button. Currently, I have an alert that warns them about potential data loss, but the alert also pops up when they submit the form. Is there a way to disa ...

Identifying the method of navigation using PerformanceNavigationTiming

Previously, I was able to determine if a user had arrived on the page by clicking the back button in the previous page using window.performance.navigation.type like this: if (window.performance.navigation.type === 2) { window.location.reload() } Howe ...

I am looking to develop a customizable table where the user can input their desired information

Looking to create an HTML page featuring a 10x10 table with alternating red and green squares. After loading the page, a pop-up window will prompt the user to input a word, which will then appear only in the red squares of the table. While I've succes ...

Is there a way to display multiple rows in the responsive view of Datatables.net?

Here is a screenshot of my table in desktop mode: https://i.sstatic.net/3Fe8C.png In responsive or mobile view, users can currently only see the country name without clicking on the + button. However, I want to display the (name, buy price, sell price) wi ...

Retrieving and storing data between a database and text fields

Trying: Extracting information from the database to text fields (the database contains infinite data so it is not feasible to name each field individually), then modifying the data and updating it back to the database. Issue: Unable to assign names to th ...

When converting HTML to PDF using Dompdf, Font Awesome icons may not appear as expected

I am currently using Dompdf for exporting an HTML page to PDF. The issue I am facing is that when the HTML file contains Font Awesome icons, in the resulting PDF there are question marks instead of the icons. Below is a snippet of the HTML code: <!DOC ...

Manipulating the ng-model linked HTML element's value with jQuery

My form contains various input fields such as select boxes, text inputs, and number type inputs. I want to implement a feature where when the user submits the form, any empty fields will automatically be filled with dummy values. This way, when I review th ...

Adjusting the Bootstrap button block to match the width of the screen

Can anyone help me with this issue? My Bootstrap button is extending outside the screen and I'm not sure how to fix it. Here is the link to my plunker <div class="bigone"> <div class="mybar">Nav bar</div> <div class="m ...

Generate a fresh array from the existing array and extract various properties to form a child object or sub-array

I am dealing with an array of Responses that contain multiple IDs along with different question answers. Responses = [0:{Id : 1,Name : John, QuestionId :1,Answer :8}, 1:{Id : 1,Name : John, QuestionId :2,Answer :9}, 2:{Id : 1,Name : John, QuestionId :3,An ...

Creating a dropdown menu that seamlessly populates elements without any empty spaces

My team at the company is using a menu created by another developer. I recently added a dropdown selection to the first item on the menu, but I've run into an issue where the dropdown box does not fully fill the item, and I can't seem to fix it. ...

Tips on effectively integrating the onSelectChange() function with queries in ColdFusion 9 using Ajax

I currently have a dropdown menu that displays different choices for the user. I want the selected option to populate a text area based on the user's selection. The data is already stored in my database, and I need to be able to execute a query depend ...

Bootstrap popover fails to function without any visible errors

Currently in the process of developing a website with the latest version of Bootstrap, I'm looking to implement a feature where a popover appears upon clicking a specific button. After including the necessary jQuery and popper.js files in my project, ...