Display and conceal the information with a hyperlink

I need to create a content DIV that includes a link to expand and collapse it.

Within this content DIV, there is an unordered list. Initially, only two list items should be displayed with an expand link. If users want to see additional list items, they must click on the expand link. Once expanded, the link text should change to Collapse. Additionally, if the unordered list only contains two items, the link should not be displayed.

NOTE: The unordered list is generated dynamically using PHP.

Here is an example of my HTML structure -

  <div id="mycontent">
    <ul>
      <li>Lorem ipsum dolor sit amet</li>      
      <li>Lorem ipsum dolor sit amet</li>      
      <li>Lorem ipsum dolor sit amet</li>      
      <li>Lorem ipsum dolor sit amet</li>      
      <li>Lorem ipsum dolor sit amet</li>      
      <li>Lorem ipsum dolor sit amet</li>      
      <li>Lorem ipsum dolor sit amet</li>      
      <li>Lorem ipsum dolor sit amet</li>
    </ul>
    <p><a href="">+ View More</a><p>
  </div>

This is the JQuery code I have implemented -

$("a").click(function(){
    $("#mycontent").toggle();
}); 

You can view the current state of my code here: http://jsbin.com/mojuteve/1/edit

If you have any suggestions on how to improve this functionality, please let me know.

Thank you!

Answer №1

$(function() {
    $("#mycontent li:gt(1)").hide(); 
    if ($("#mycontent li").length <= 2) {
        $("#showmore").hide();
    }
    $("#showmore").click(function() {
        $("#mycontent li:hidden").slideDown();
        $("#showmore,#collapse").toggle();
        return false; 
    });
    $("#collapse").click(function() {
        $("#mycontent li:gt(1)").slideUp();
        $("#showmore,#collapse").toggle();
        return false; 
    });
});

Use the given HTML:

  <div id="mycontent">
    <ul>
      <li>Lorem ipsum dolor sit amet</li>      
      <li>Lorem ipsum dolor sit amet</li>      
      <li>Lorem ipsum dolor sit amet</li>      
      <li>Lorem ipsum dolor sit amet</li>      
      <li>Lorem ipsum dolor sit amet</li>      
      <li>Lorem ipsum dolor sit amet</li>      
      <li>Lorem ipsum dolor sit amet</li>      
      <li>Lorem ipsum dolor sit amet</li>
    </ul>
    <p><a id="showmore" href="#">+ View More</a>
       <a id="collapse" href="#">- Collapse</a><p>
  </div>

And add the following CSS:

#collapse {
    display:none;
}

Answer №2

Check out this code snippet: http://jsfiddle.net/Abc123/4/

This script will help you toggle the text inside the "a" tag

$(function(){
    $(".content").hide();
    $("a").click(function(){
        $(".content").slideToggle("fast");
        $(this).toggleClass("show-more");
        if($("a").hasClass("show-more")) {
            $("a").text("- Show Less");
        } else {
            $("a").text("+ Show More");
        }
    });
});

Answer №3

How about trying this out:

CSS:

#content {
    background: #ffffff;
    overflow: hidden;
}
#content > ul {
    display: block;
    width: 400px;
}
#content > ul > li {
    display: inline-block;
    padding: 0 20px 10px 0;
}
#content > ul > li + li + li {
    display: none;
}
#content p {
    float: right;
    padding: 0 20px;
}
#content.show ul > li {
    display: inline-block;
}

jQuery:

//Check if the list items are less than 3 and remove the more link if true
(function () {
    var listLength = $('#content ul li').length;
    if (listLength < 3) {
        $('#content a').remove(); 
    }
})();

//Array for text toggle
var linkText = ['+ View More', '- Collapse'];

$('a').on('click', function (e) {
    e.preventDefault();
    var $this = $(this);
    $('#content').toggleClass('show'); 
    //Text change
    if($this.text() === linkText[0]){
        $this.text(linkText[1]);
    }else{
        $this.text(linkText[0]);
    }
})

Checking list length with PHP instead of JS when less than 3 would be more efficient.

Demo

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

Keep the button in a single color unless it is being hovered over

Is there a way to create a button that changes color on hover, then reverts back to its original color after it's clicked? I'm facing an issue where my button initially has a red gradient, then changes color when hovered over, but turns white on ...

Retrieve data using ajax within an mvc framework

I am facing an issue where I am unable to receive the data sent with AJAX jQuery to a .NET server as a parameter, modify it in memory, and then convert it to JSON. Any assistance in resolving this problem would be greatly appreciated. JAVASCRIPT document ...

How come my donut graphs are sitting outside the box while all other types of charts are properly aligned?

I am encountering an issue with my charts where all of them are positioned in the center of a div when drawn by the user, except for the donut charts. They seem to be placed outside of the top-left corner instead. Can anyone provide insights as to why this ...

Creating a div overlay triggered by the addition of a child tag

Using the Paypal zoid feature, I have a button that opens an iframe in the parent div when clicked. However, the iframe causes the other contents of the website to shift around, making it look messy. I'm wondering if there is a way to make the parent ...

Avoiding duplicate touch events with an if statement

I am currently working on a module for a responsive website that involves tapping the initial screen to reveal a panel from the right. The user can then tap a close button to hide the panel. However, there is an issue where if the user taps multiple times ...

Angular's method of one-way binding to an object

Seeking a method for one-way (not one time) binding between an attribute on a directive without utilizing attrs.$observe. Currently considering binding via &attr and invoking the variables in the template like {{attr()}}. app.controller('MainCtrl ...

"The space between the header-main section and the main-footer section is pure white

I'm facing an issue with the white space between the header-main and main-footer sections. I would like to either match their color to the rest of the website or completely remove the space. The color I want to use is #fefcf5. I hope this edited versi ...

A guide on enhancing Autocomplete Tag-it plugin with custom tags

Looking to expand the tags in the 'sampleTags' variable within this code snippet $(function () { var sampleTags = ['c++', 'java', 'php', 'coldfusion', 'javascript', 'asp', &apo ...

Using Angular directives to dynamically add event listeners with the ng-repeat directive

I am currently working with a directive that includes event listeners for an element in the link function. For example: ... link: function(scope, element) { // this gives us the native JS object var el = element[0]; el.draggable = true; ...

Conditionally displaying an input model in Vue.js using v-if

Just starting to learn vue.js and I'm looking to display table data. My idea is that when the table is in display mode, it should only show the data. However, when I click on the edit button of a table row, I want that specific row to switch to edit m ...

Elevate your designs with Bootstrap Cards featuring a clickable link. Give your

I am trying to incorporate bootstrap cards into a form without using a normal link. The intention is to send the data along with other information via POST method. However, I am facing an issue with the display. The blocks should maintain the same height, ...

The replacement of classes in ReactJS using JavaScript seems to be malfunctioning

I have been attempting to change the class of a dynamic element when clicked, but none of my solutions seem to be working. Here is what I have tried: handleClick=(event,headerText)=>{ document.getElementsByClassName('sk-reset-filters') ...

Using AJAX to dynamically load an image by setting the image path as the source of the image tag

I'm facing a challenge with my AJAX call that is used to display user details in a modal. I recently integrated an image upload feature for users, but now I'm struggling to display the uploaded image. I have tried looking for solutions online, bu ...

How come submitting a form without refreshing does not update the database with new values?

I'm encountering an issue with my form and script that is supposed to connect to the operation.php class. Despite having everything set up correctly, the data is not being added to the database and the page does not refresh. I'm perplexed as to ...

Display the accurate prompt in the event of 2 `catch` statements

elementX.isPresent() .then(() => { elementX.all(by.cssContainingText('option', text)).click() .catch(error => { throw {message: "Unable to select text in dropdown box"} ...

Troubleshooting a simple test issue with React AXIOS post in an Express environment

I have successfully created a React front end and used a basic boilerplate to connect it with Express. However, I am now faced with the challenge of setting up a simple RESTful API, and the myriad of options available is overwhelming. My goal is to establi ...

Stylish Radial Hover Effect for Images Using CSS

I am looking to create a unique effect where upon hovering over an image, color will be applied in a radial shape on a grayscaled image within a div that is pointed by the cursorhttps://i.sstatic.net/64RJv.jpg Below you can see the desired outcome compare ...

Create an interactive table in your WordPress website that adjusts to different screen sizes

Having scoured numerous posts on responsive tables in this stack, I am still unable to find a solution to my specific issue. It's quite possible that I didn't know what exactly to look for, hence my resorting to posting a question here. The crux ...

Leveraging the ng-hide property of one controller to adjust the ng-style attribute of another controller through a centralized global controller

Seeking assistance with accessing the boolean value of ng-hide from one controller in order to alter CSS properties of another controller utilizing a global controller. Here is the jsfiddle link: https://jsfiddle.net/dqmtLxnt/ HTML <div ng-controller= ...

What is the best way to navigate my Page while my Dialog Component is displayed?

Is there a way to enable scrolling on the background when a dialog component opens up? By default, scrolling is disabled when the dialog appears. How can we allow scrolling in the background? Here is the code snippet: import React, { useState } from &apos ...