Increase the visibility of a div using Jquery and decrease its visibility with the "

Can anyone assist me with implementing a "show more" and "show less" feature for a specific div?

I have put together a DEMO on codepen.io

In the DEMO, there are 8 red-framed div elements. I am looking to display a "show more" link if the total number of divs exceeds 4, and when clicked, all divs should be visible on the same page. Can someone provide guidance on this issue?

<div class="container">
  <div class="post_wrap">
    <div class="pst">
      Post 1
    </div>
     <div class="pst">
      Post 2
    </div>
     <div class="pst">
      Post 3
    </div>
     <div class="pst">
      Post 4
    </div>
     <div class="pst">
      Post 5
    </div>
     <div class="pst">
      Post 6
    </div>
     <div class="pst">
      Post 7
    </div>
     <div class="pst">
      Post 8
    </div>
    <div class="test"><a href="">Show More</a></div> 
  </div>
  <div class="post_wrap">
    <div class="pst">
      Post 1
    </div>
     <div class="pst">
      Post 2
    </div>
     <div class="pst">
      Post 3
    </div>
     <div class="pst">
      Post 4
    </div>
     <div class="pst">
      Post 5
    </div>
     <div class="pst">
      Post 6
    </div>
     <div class="pst">
      Post 7
    </div>
     <div class="pst">
      Post 8
    </div>
    <div class="test"><a href="">Show More</a></div> 
  </div>
</div>

Answer №1

CSS

div.test { display:none }

jQuery

1) To start, select all elements with the class '.post_wrap'

$('.post_wrap')

2) Next, use the each() function to iterate through each .post_wrap element in the DOM and count the child divs with a class of .pst

$(this).find('div.pst').length;

Explained further

The reference $(this) points to the specific element that the each() function was used on, in this case, $('post_wrap') The find() method searches within the applied element and locates the specified content, here, it finds every div.pst element Finally, the length property tallies up the discovered elements and assigns the count to a variable named 'divNum'

If the value of divNum exceeds 4

if (divNum > 4)

Show the hidden div.test element

$('div.test').show()

$('.post_wrap').each(function() {
    var divNum = $(this).find('div.pst').length;
    if (divNum > 4) {
        $('div.test').show();
    }
}) 

Then, when dv.test becomes visible:

$('div.test').click(function() {
    // reveal more divs
})

UPDATED -> your code pen

Visit the CodePen

jQuery

$ShowHideMore = $('.post_wrap');
$ShowHideMore.each(function() {
var $times = $(this).children('.pst');
if ($times.length > 5) {
    $ShowHideMore.children(':nth-of-type(n+5)').addClass('moreShown').hide();
    $(this).find('span.message').addClass('more-times').html('+ Show more');
}
});

$(document).on('click', '.post_wrap > span', function() {
var that = $(this);
var thisParent = that.closest('.post_wrap');
if (that.hasClass('more-times')) {
thisParent.find('.moreShown').show();
that.toggleClass('more-times', 'less-times').html('- Show less');
} else {
thisParent.find('.moreShown').hide();
that.toggleClass('more-times', 'less-times').html('- Show more');
}  
});

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 make elasticX() and elasticY() only affect the upper bound in dc.js?

One question I have regarding my bubbleChart in dc.js is related to the x-axis. I want the count on the x-axis to always start at 0, but have an upper bound that adjusts based on the range I am looking at. Currently, when I use .elasticX(true), both the up ...

Tips for resolving the issue: "Encountered error loading module script..." in Angular 8 and Electron 5

I have been working on developing an Electron 5 app using Angular 8. Despite following numerous online tutorials, I keep encountering the same error. Initially, I set up a new project and ran ng serve --open, which successfully displayed the default angul ...

What is the best way to add values to a JavaScript object using jQuery or plain JavaScript?

I have an object here and I am looking to dynamically insert values into it. var mergTr={}; //object for(dd in dispID) { var dataID=displayObj[dispID[dd]]; if(dataObj[dataID]) { var flag=0; var v ...

Experiencing issues with overflowing columns in JQuery Datatables

I am currently facing an issue with my datatable where I need it to have a specific width while also displaying all its columns. The problem I am encountering can be summarized as follows: I came across solutions like Datatables Width Overflow For A ...

The .val() function in jQuery can sometimes give different results when used on input elements with placeholder text in Firefox compared to Chrome

After analyzing the given HTML code, I've noticed discrepancies in the values returned by jQuery in Firefox and Chrome: HTML: <input type="text" name="name" id="name" placeholder="Type Here"> <input type="email" name="email" id="email" plac ...

Perform a Rails Ajax request to update a like or dislike status

Is there a way to implement like/dislike functionality in my RoR application using Ajax requests? I have integer values for both like and dislike counters. How can I use Ajax requests to increment either the "like" or "dislike" counter in my methods? In ...

Nodejs and javascript are utilized to create dynamic SES emails

I have successfully implemented sending an email using node-ses client.sendEmail({ to: to_id, , cc: cc_id, , bcc: bcc_id, , subject: 'greetings' , message: 'your <b>message</b> goes here' , altText: 'plain text& ...

Building a new Vue.JS component inside of an existing parent component

Trying to create a nested component in VueJS has been a bit challenging for me. I have attempted something like this, but unfortunately, it doesn't seem to work as expected (the child component does not display anything): I am interested in exploring ...

Should jQuery be utilized in an Angular JS project?

As a newcomer to Angular JS, I am looking to develop a project with Angular JS and HTML5. In my previous projects, I utilized the jQuery framework for DOM manipulation. Now, I am unsure if it is advisable to use jQuery in an Angular JS project since many f ...

Having trouble transmitting data from the View to the Controller

Need help with this issue. I'm having trouble passing my data to the controller. Below is my ajax code. <script type="text/javascript"> $(document).on("click", "#login_button", function () { var userName = document.getElementById(" ...

Using jQuery to add a timed slide effect to an element

After the page loads, I want an element to slide left after 10 seconds without disappearing from the page completely. The goal is for it to move 200px to the left and then return to its original position when clicked. I'm unsure about how to set the ...

JavaScript taking over the HTML footer content

I'm attempting to update the content of my footer without modifying the HTML by including a class or an id. HTML: <footer> <div> Lorem ipsum dolor sit amet, consectetur adipisicing elit. </div> </footer> Java ...

How to populate an ExtJS 3.4 combobox with local JSON data in a few simple steps

I am utilizing ExtJS 3.4 and in need of populating a combobox with specific data obtained from a previous XMLHttpRequest, stored in a variable as follows: my_variable = "[{"cod_domini":"1","nom_domini":"Sant Esteve de Palautordera"},{"cod_domini":"2","no ...

Creating code that is easily testable for a unique test scenario

My function, readFile(path, callback), is asynchronous. The first time it reads a file, it retrieves the content from the file system and saves it in memory. For subsequent reads of the same file, the function simply returns the cached content from memor ...

Output the contents of a nested object

After setting up a variable containing music library data... var library = { tracks: { t01: { id: "t01", name: "Code Monkey", artist: "Jonathan Coulton", album: "Thing a Week Three" }, t02: { id: " ...

enhanced labeling for checkboxes in Vuetify

Below is a snippet of my straightforward code: <v-checkbox v-model="rodo" label="I consent to Terms and Conditions (click for more info)" :rules="termsRules" required ></v-checkbox> I am looking to keep the label simple with an option ...

The syntax in JavaScript of (0, fn)(args) is used to call

I came across an interesting piece of JavaScript code in Google's codebase that I wanted to discuss: var myVar = function...; (0, myVar)(args); Do you know what the significance of this syntax is? I'm struggling to see the difference between ( ...

What is the best way to add an element when a checkbox is selected and delete it when it is dese

How can I display the text of selected elements and remove them when unchecked from a list of orders? When an element is checked, its value is added to the sum and its text is displayed. If it is unchecked, its text should be removed. Click here for the co ...

Tips for customizing the AjaxComplete function for individual ajax calls

I need help figuring out how to display various loading symbols depending on the ajax call on my website. Currently, I only have a default loading symbol that appears in a fixed window at the center of the screen. The issue arises because I have multiple ...

Ways to incorporate line spacing using CSS

Is there a way to adjust the spacing between the drop down boxes in the sidebar so that they align neatly with the questions in my section? select { font-family: 'Courier New', monospace; color: black; font-weight: bold; font-size: 3 ...