Utilize jQuery to selectively truncate a list and toggle the visibility of random list elements within a specified maximum limit

Looking to showcase only 6 out of the over 6 list elements within a <ul>, but in a random and staggered manner.

Consider the following initial structure:

<ul>
    <li>1<li>
    <li>2<li>
    <li>3<li>
    <li>4<li>
    <li>5<li>
    <li>6<li>
    <li>7<li>
    <li>8<li>
    <li>9<li>
</ul>

Using jQuery, is it feasible to hide/show elements to achieve a randomized outcome like below?

<ul>
    <li style="display:none">1<li>
    <li>2<li>
    <li style="display:none">3<li>
    <li>4<li>
    <li>5<li>
    <li>6<li>
    <li>7<li>
    <li style="display:none">8<li>
    <li>9<li>
 </ul>

Answer №1

It is recommended to try solving the problem yourself before seeking help, and when asking questions here, provide the code you have attempted to demonstrate your efforts. Nevertheless, for a straightforward issue like this, I will address your question.


Building upon this response regarding generating random numbers in JavaScript, one can utilize a while() loop to generate a random number within the range of 0 and the total elements minus 6.

To ensure that the same element is not hidden twice, we need to verify if the element corresponding to the random number index is already hidden.

  • If it's visible, hide it and decrement the remaining iterations by 1
  • If it's hidden, skip and begin a new iteration.

(Check out the demo)

var items = document.querySelectorAll("#random li"), index, i;
var min = 0;
var max = items.length - 1;
var count = items.length - 6;

while(count > 0) {
    index = Math.floor(Math.random() * (max - min + 1)) + min;
    if(items[index].style.display != "none") {
        items[index].style.display = "none";
        --count;
    }
}

Correction Update:

Remember to close HTML tags properly for your elements.

<li>2<li>

Should be

<li>2</li>

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

The dropdown menu vanishes from sight as soon as the cursor moves away from a link

Recently, I encountered an issue while trying to create a dropdown menu using Jquery. The problem arose when attempting to select the second link, as the entire menu would disappear. Additionally, is there a way to ensure that only one dropdown menu is vis ...

What steps can I take to prevent constantly re-fetching a disabled CSS file?

I'm currently in the process of implementing a dark theme on my website, and my current method involves using 2 style sheets: <link rel="stylesheet" type="text/css" href="/flatly.css"> <link rel="stylesheet& ...

Create multiple buttons with uniform width by adjusting padding in CSS

I recently attempted to create buttons using CSS and padding. Here is the HTML code for the buttons: <link rel="stylesheet" type="text/css" href="css/style-login.css" /> <link rel="stylesheet" type="text/css" href="css/font-awesome-4.0.3.css" /& ...

Ensure that all panels are set to the same width as the widest panel

Is there a way to make all the panels in my jQuery tabs have the same width as the widest panel? I know that heightStyle:"auto" works for adjusting the height, but is there a similar option like widthStyle:"auto"? I want to show you the current look compa ...

Guide to integrating various HTML files into a single HTML file with the help of Vue.js

Although I am familiar with using require_once() in PHP, unfortunately, I am unable to use PHP in my current project. I attempted to use w3-include from W3Schools as an alternative, but encountered issues with loading my scripts. Even utilizing JavaScript ...

What is the best way to implement this design using CSS or JavaScript?

I would like to enhance the appearance of my school website during these challenging times of the pandemic by adding some CSS or JavaScript elements. However, I am unsure how to go about it. ...

HTML image identifier and canvas elements

Greetings! I have a question that I've been struggling to find an answer for on Google. I'm attempting to draw an image on a canvas and initially used the "new" constructor ( ballPic = new Image(); ballPic.src = "ball.png" ) which worked fine. Ho ...

The functionality of Javascript Regular Expressions is not performing as expected

I am currently facing an issue with email validation in JavaScript as it doesn't seem to be working properly. PROBLEM: Even when entering a VALID email address, the alert still shows that my address is faulty... What could I possibly be missing he ...

Tips for preventing abusive input using jQuery

I'm currently diving into jQuery and looking to create a form that disables the submit button and clears the input if any abusive words are detected. I would appreciate some assistance with this task. Below is the code snippet I have been working on. ...

Move the DIV element to the bottom of the webpage

On my website, I have implemented a countdown timer and a responsive wallpaper. My goal now is to center the div at the bottom of the page and make sure it always stays there. I've tried some code snippets from StackOverflow, but they either gave me a ...

How can jQuery help me load a lengthy webpage with various backgrounds that change according to the vertical scroll value?

I have been given a design that is 960px wide and approximately 7000px tall, divided into five segments stacked vertically at random points. There is a fixed sidebar that scrolls to each segment when a navigation link is clicked. The layout includes slider ...

Locking the second column of a data table with CSS to prevent scrolling

We need to freeze two columns in our data table - "PPD Delivery Schedule" and "Check Opex". The first column is working fine, but we're having issues freezing the second column. We've tried various approaches but haven't been successful so ...

Warning message in ReactJS Material UI Typescript when using withStyles

I am facing an issue even though I have applied styling as per my requirements: Warning: Failed prop type validation- Invalid prop classes with type function passed to WithStyles(App), expected type object. This warning is originating from Wi ...

Troubleshooting a JQuery accordion malfunction within a table

I am populating the data dynamically. However, the Accordion feature is not functioning correctly. JSFiddle link http://jsfiddle.net/aff4vL5g/360/ Please note: I am unable to modify the HTML structure. Current table Desired output The first accordio ...

Styling elements using the nth-child selector in JavaScript

I am trying to apply a CSS class based on the combined height of the 2nd and 3rd child elements. For example, if the height of the 2nd child plus the height of the 3rd child equals a certain value, I want to add a specific class. Here is my JavaScript cod ...

Sorting Datatables using ajax method

I am using a basic datatables setup with will_paginate. <table id="users" class="display" data-source="<%= url_for(:controller => "/account", :action => :paginate, :format => :json) %>"> <thead> <tr> <th> ...

When utilizing jQuery, HTML code may fail to render correctly

My JSP page contains the following HTML code. Interestingly, when <script type="text/javascript"> $("#department").autocomplete("department.jsp",{minChars: 4}); is placed after the first input type, the other fields do not show up in Internet ...

Triggers the request for Windows authentication when accessing a webpage on a website

Whenever I attempt to access a specific page on my website, a login screen pops up asking for my username and password. Even after entering the correct credentials and clicking OK or Cancel, the page still loads as normal. I can't figure out why this ...

Execute a JavaScript function prior to initiating an AJAX request

To streamline the process of making AJAX calls in my .NET project, I have developed a function called checkConnection that checks for internet connectivity before each call. However, currently, I am manually calling this function on every button click that ...

What is the reason behind the Nexus 4 (with Chrome for Android) displaying a window size of 384x519 while the screenshot depicts it as 768x1038

Currently, I am utilizing media queries to adjust the display based on different screen sizes. However, I have encountered an issue where the screen size is not being accurately reflected in CSS. For instance, on the Nexus 4 device, the display is renderin ...