How can the Nth-child CSS property be modified to exclude HTML elements with the display property set to none?

I have a basic gallery set up using an unordered list.


    <h1>Projects</h1>
    <hr>

    <!-- Projects displayed as an unordered list -->

    <ul class="gallery">

      <li class="item residential">
        <img src="Projects/01-HighTorEast-EarlShilton/01-thumbnail.jpg" width="212" height="119" alt="High Tor East, Earl Shilton">
        <h2><a class="info" href="Projects/01-HighTorEast-EarlShilton/info.php">High Tor East, Earl Shilton</a></h2>
        <h3><a class="cat" href="residential">Residential</a></h3>
      </li>

      <li class="item modernisation">
        <img src="Projects/02-Hollycroft-Hinckley/02-thumbnail.jpg" width="212" height="119" alt="Hollycroft, Hinckley">
        <h2><a class="info" href="Projects/02-Hollycroft-Hinckley/info.php">Hollycroft, Hinckley</a></h2>
        <h3><a class="cat" href="modernisation">Modernisation & Domestic Extensions</a></h3>
      </li>

      <!-- More project items follow... --> 

    </ul>

  </section>

In my CSS, I adjusted the right margin value to zero for every fourth child of the .item class. This was done to display four items in a row on the page without removing margins, which would only fit three items per row.

ul.gallery { clear:both; list-style:none; margin:0; padding:0; width:940px; }
.gallery a:hover { text-decoration:underline; }
li.item { display:inline; margin:30px 20px 30px 0px; padding:0px; height:178px; width:220px; float:left; background:#ededed url('../Images/featuredline.png') repeat-x 0% 100%; overflow:hidden; }
li.item:nth-child(4n+4) { margin:30px 0px 30px 0px; }

Additionally, I implemented a small jQuery script to sort items based on category. Clicking on a specific category link will hide elements with different categories.

    $('.cat').bind('click', function(e) {
    var cat = $(this).attr('href');
    $('.item').each(function () {
    var itemClass = $(this).attr('class');
    if (itemClass != 'item '+cat) {
        $(this).css({"display":"none"});
    };


    });
    e.preventDefault();

One challenge I encountered is that the CSS property .item:nth-child still counts elements with a display property set to none after sorting them with the jQuery script. I am uncertain how to resolve this issue. I need the .item:nth-child property in CSS to count only visible elements after applying the jQuery filter.

You can view the website here.

Answer №1

To update the layout, simply remove your nth-child CSS style and implement this script:

$("li.item:visible").each(function(i) {
    if((i+1)%4==0) $(this).css("margin","30px 0");
    else $(this).css("margin","30px 20px 30px 0");
})

I tested this solution on your website using firebug and it worked perfectly.

Answer №2

If you're looking for a solution, one option is to modify the css selector nth-child to a class and then utilize jQuery to alternate the class accordingly.

li.item.marginClass { margin:30px 0px 30px 0px; }

JS:

$(function(){
    var $items=$('li.item');
    function toggleMargin(}{
        $items.removeClass('marginClass').filter(':visible').addClass(function(index){
              return index % 4 ===0 && index !=0 ? 'marginClass' : '';
        });
    }
    /* call for page loaded items*/
    toggleMargin(};

    $('.cat').bind('click', function (e) {
        /* filtering code here*/

        /* adjust class*/
         toggleMargin(};

    })



});

Answer №3

To hide a node, add an "isHidden" attribute by using $(this).attr('isHidden'). To show the node again, remove this attribute with .removeAttr('isHidden'). This way, you can easily update your selector.

li.item:not([isHidden]):nth-child(4n+4) { margin:30px 0px 30px 0px; }

If you prefer not to use an extra attribute, you can also achieve the same result by adding it as a class name. You can find more information in Tomalak's answer.

Answer №4

Cascading Style Sheets (CSS)

instead of

li.item:nth-child(4n+4) { margin:30px 0px 30px 0px; }

you can also use

li.item.split { margin:30px 0px 30px 0px; }

jQuery Code Snippet:

reorderColumns  =   function(ev) {
    $('li.item').removeClass('split');
    $('li.item:visible:nth-child(4n+4)').addClass('split');
    ev.preventDefault();
};

$('.cat').on('click',reorderColumns);

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

Problem with Cakephp 2.2: Using Jquery Ajax with Js->link to save multiple entry ids on a single page

Is it possible that this question has already been addressed elsewhere? Despite my efforts, I have not been able to locate the answer. Cakephp is usually a reliable platform for me, but currently, it's causing me a lot of frustration. I am attempting ...

Having trouble getting the .toggle() function with classList to work on one element, despite working fine on others

I've been struggling to apply a class to an HTML element when I click on another element of the page. Despite numerous attempts, it just doesn't seem to work for me. Let's take a look at my code: HTML Code: <div class="container&qu ...

In Nodejs, the function 'require' fails to load a module when using specific filenames

Hello everyone, I am a long-time user but this is my first time asking a question. So, I have a file named file.js where I am trying to require another file called user.service.js at the beginning of the file: var userService = require('./user.servi ...

The route is redirecting to an incorrect destination

Whenever a button is clicked on my webpage, this particular function is triggered. $scope.go=function(takenAt){ var path = '/oneMinuteMetric/loadCapturedMetrics?'+'&timestamp=' + takenAt + '&tagName='+ $stateParam ...

What is the best way to incorporate a sliding effect into my cookie form?

I created a cookie consent form for my website and I'm looking to include a sliding effect when it first appears and when it disappears after the button is clicked. How can I implement this sliding effect into the form? Here's the HTML, CSS, and ...

The crash during compilation is triggered by the presence of react-table/react-table.css in the code

My code and tests are functioning properly, but I am facing a challenge with my react-table file. The react-table.js API specifies that in order to use their CSS file, I need to include import "react-table/react-table.css"; in my react-table.js file. Howev ...

Sorts through nested arrays to uncover distinctive product assortments

Currently, I am in the process of developing a website using Next.js and Shopify. My objective is to create a page that displays all collections matching a specific productType. To achieve this, I have been exploring ways to extract this data from the Gra ...

What is the best way to use checkboxes to highlight table rows in Jquery Mobile?

I have a Jquery Mobile site with a table. Each table row contains checkboxes in the first cell. I am trying to achieve the following: a) Highlight a row when the user clicks on it b) Highlight a row when the user checks the checkbox I have made progr ...

Creating mock element in React testing library to simulate document.getElementById

When working with headless UI components like Dialog and Transition, I ran into an issue while writing a test case. The error message I received was Cannot read properties of null (reading 'getElementById'). I am using React testing library to wr ...

"Creating a Typescript array by extracting items from a different const array (as seen in the official beginner tutorial

Currently, I am working through the Angular tutorial that can be found at https://angular.io/start. After successfully completing the tutorial, I decided to practice building for production locally. However, when attempting to build, I encountered this err ...

Dynamically selecting themes in an Angular application based on user input

Experimenting with an angular project where users can choose themes from a dropdown menu to modify the appearance of the application using this handy tutorial Utilizing :host-context for this purpose Encountering an issue where the selected themes are no ...

Having trouble retrieving object values from the request body during a POST request in [Node.js, MySQL]

I am currently developing a management system and working on creating POST requests for the API to add a new city to the database. However, I am facing an issue where instead of receiving the correct values from the request's body, I am getting "undef ...

Can you identify the primary parameter used in the Parse.User.signUp() method?

Utilizing Parse.com as the database for my app, I am working on streamlining the code in my signup view. user.set("username",$scope.user.email); user.set("email",$scope.user.email); user.set("password",$scope.user.password); user.signUp(null, ...

Failing to retain hyperlinks with ajax

Currently, I am utilizing ajax to transmit data from a sophisticated custom field wysiwyg editor. Within this setup, the specific div with the class 'bio' is what I'm addressing. The issue arises when the data is retrieved - all the original ...

Angular 9 - Auto-adjust the height of the text box as the user types, returning to its original size when no longer in focus

I need a solution where an input field's height adjusts to display the user's entry, then returns to normal size when they click away. It should function similar to this example image: https://i.stack.imgur.com/yKcik.png Once the user enters th ...

The communication between Ajax and PHP is experiencing some technical difficulties

Hi there! I'm currently facing an issue with my Ajax call to a PHP function. My goal is to display the server time on the input field using a PHP script. Despite following an online tutorial step by step, I keep getting the actual text from the PHP fi ...

The remove() method in AJAX function is not functioning as expected

Within a jQuery click event that uses $.post(), I have a .remove() function inside the response callback. Strangely, the alert() seems to function correctly when the code is executed, but the .remove() does not work at all, even though the alert() in the ...

Tips for resolving the jQuery code accordion issue with three levels

I created an accordion with 2 levels initially. Now, I am looking to extend it to have 3 levels, but I am facing issues in doing so. Despite numerous attempts, I have not been able to make it work as intended. If anyone can provide guidance on fixing th ...

Fetch WordPress blog entries with a specific tag in JSON form

How can I access the JSON feed of a collection of wordpress posts without utilizing the JSON Rest API? More information ...

jquery, slideToggle not behaving correctly on mouse hover

Whenever the mouse hovers over my div with the class .frame, I slideToggle a div with the class .content. And when the mouse leaves .frame, I toggle .content back again. Everything seems to be working fine except for two issues: the effect gets messed up i ...