Ways to conceal a button using Javascript

Due to my limited JavaScript experience, I am struggling with understanding the event flow. This was written in haste, and further editing may be needed.

I am working on creating a stack of cards (Bootstrap cards) along with a load button. To keep it independent of any dependencies, I am using JavaScript.

I'm having trouble grasping the event flow, or I can't seem to hide the load button.

window.onload = testCards;

function testCards() {
  var col_num = document.querySelector(".col-6");
  if (col_num &< 10) {
    var loadBtn = document.querySelectorAll(".d-grid .gap-4");
    loadBtn.querySelector(".btn").classList.add("invisible");
  }
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8be9e4e4fff8fff9eafbcbbea5bba5bba6e9eeffeab9">[email protected]</a>/dist/js/bootstrap.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ef8d80809b9c9b9d8e9fafdac1dfc1dfc28d8a9b8edd">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" />
<h3>Footer card</h3>
<div class "row footer-card">
  <div class="col-6 card">
    <p>This is card</p>
  </div>
  <div class="col-6 card">
    <p>This is card</p>
  </div>
  <div class="col-6 card">
    <p>This is card</p>
  </div>
  <div class="col-6 card">
    <p>This is card</p>
  </div>
  <div class="col-6 card">
    <p>This is card</p>
  </div>
  <div class="col-6 card">
    <p>This is card</p>
  </div>
  <div class="col-6 card">
    <p>This is card</p>
  </div>
  <div class="col-6 card">
    <p>This is card</p>
  </div>
  <div class="col-6 card">
    <p>This is card</p>
  </div>
</div>

<div class="d-grid gap-4">
  <button class="btn btn-secondary py-1 my-3 mx-5" type="button">Load More</button>
</div>

How can I hide the "load more" button when the number of cards is less than 10?

Answer №1

There were a couple of issues found in the code. The first problem was related to determining the count of the .card div elements, and the second issue was with selecting the button using querySelector. To address these issues, try the following approach: start by selecting all elements with the card class, then hide the load button based on their quantity.

window.onload = testCards;
function testCards() {
    var cardElements = document.getElementsByClassName("card");
    if(cardElements.length < 10) {
        document.querySelector(".btn").style.display='none';
    }
}
<script src="https://cdn.example.com/js/bootstrap.min.js"></script>
<link href="https://cdn.example.com/css/bootstrap.min.css" rel="stylesheet"/>
<h3>Footer card</h3>
    <div class"row footer-card">
    <div class="col-6 card"><p>This is card</p></div>
    <div class="col-6 card"><p>This is card</p></div>
    <div class="col-6 card"><p>This is card</p></div>
    <div class="col-6 card"><p>This is card</p></div>
    <div class="col-6 card"><p>This is card</p></div>
    <div class="col-6 card"><p>This is card</p></div>
    <div class="col-6 card"><p>This is card</p></div>
    <div class="col-6 card"><p>This is card</p></div>
    <div class="col-6 card"><p>This is card</p></div>
    </div>
    
    <div class="d-grid gap-4">
    <button class="btn btn-secondary py-1 my-3 mx-5" type="button">Load More</button>
    </div>

Answer №2

I made a note of the changes I felt were necessary

// window.onload = testCards; It's better to use addEventListener

addEventListener('load', testCards);

function testCards() {
  // const col_num = document.querySelector(".col-6"); his returns an element, comparing it with a number is not valid
  // But what I think you mean is to find out how many .col-6 cards are out there...
  // If that's the case you use querySelectorAll and length
  const col_num = document.querySelectorAll(".col-6").length;
  const loadBtn = document.querySelectorAll(".d-grid.gap-4").querySelector(".btn");
  
  if (col_num > 10) { // changed that to > so if there are more than 10 cards, hide the button
    // When selecting classes of the same element, you select them just like you would in CSS with a period(.) and without spacing
    loadBtn.classList.add("invisible");
  } else {
    loadBtn.classList.remove('invisible');
  }
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="44262b2b30373036253404716a746a74692621302576">[email protected]</a>/dist/js/bootstrap.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0d6f6262797e797f6c7d4d38233d233d206f68796c3f">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" />
<h3>Footer card</h3>
<div class "row footer-card">
  <div class="col-6 card">
    <p>This is card</p>
  </div>
  <div class="col-6 card">
    <p>This is card</p>
  </div>
  <div class="col-6 card">
    <p>This is card</p>
  </div>
  <div class="col-6 card">
    <p>This is card</p>
  </div>
  <div class="col-6 card">
    <p>This is card</p>
  </div>
  <div class="col-6 card">
    <p>This is card</p>
  </div>
  <div class="col-6 card">
    <p>This is card</p>
  </div>
  <div class="col-6 card">
    <p>This is card</p>
  </div>
  <div class="col-6 card">
    <p>This is card</p>
  </div>
</div>

<div class="d-grid gap-4">
  <button class="btn btn-secondary py-1 my-3 mx-5" type="button">Load More</button>
</div>

Answer №3

The issue here lies in the flow not entering the if condition correctly due to a problem with obtaining the length accurately. Give this solution a try as it should address the issue.

window.onload = testCards;
function testCards(){
var col_num =  document.querySelectorAll(".col-6");

if(col_num.length < 10){
var loadBtn = document.querySelector(".d-grid");
        loadBtn.querySelector(".btn").style.display = 'none';
}
}

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

Simply modifying a custom attribute source using jQuery does not result in it being refreshed

Introduction: Utilizing jQuery.elevateZoom-3.0.8 to display zoomed-in images. The SRC attribute contains the path to the smaller/normal image The DATA-ZOOM-IMAGE attribute holds the path to the larger image used for zooming. Here is the HTML Code: ...

Acquiring data within a jade template in order to generate static HTML pages

I am struggling to pass data to a jade template in order to generate static content. While I am not well-versed in node.js and express, I use jade as a template engine for creating static html. Many of the requests in the jade issue list pertain to includ ...

Using JavaScript, extract current date from an API data

Here is an example of how the data from my API appears: const data = [{ "id": "1", "name": "Lesley", "creationDate": "2019-11-21 20:33:49.04", }, { "id": "2", "name": "Claude", "creationDate": "2019-11-21 20:33:09.397", }, { "i ...

Rails 5 not allow user submission of bootstrap modal form

I am facing an issue with a form inside a modal in my Rails application. When I click on the submit button, nothing happens. How can I use Ajax to submit the modal form and save its content on another page? <button type="button" class="btn btn-primary ...

Employing multer in conjunction with superagent to enable file uploads from a React application

I am new to using multer and experiencing some difficulties with it. My goal is to upload an image file from a react client using the superagent library to my server. However, the req.file data always shows as undefined in my code: On the server side : ...

Encountering an issue with Vue JS axios request and filter: the function this.XX.filter is not operational

I am encountering challenges while trying to implement a basic search feature on a JSON file obtained through an API. Each component works independently: I can successfully retrieve data from the API, perform searches on non-API data, and even search cert ...

Preserve file sequence with jquery file upload

I recently came across an interesting upload script at the following link: This script utilizes jquery file upload to allow for uploading multiple files simultaneously. I'm curious about how to transmit the order in which the files were selected to t ...

Vue: update data and trigger function upon completion of animation transformation, utilizing animation transformation completion listener

Check out this straightforward Vue example: https://codesandbox.io/s/sleepy-haze-cstnc2?file=/src/App.vue https://i.stack.imgur.com/zboCb.png Whenever I click on the square, it not only changes color but also expands to 200% of its original size with a 3 ...

Discovering the process of mapping transitions in MUI

I'm struggling with mapping my products in mui and placing each one in Grow. However, I keep getting this error message: "Warning: Failed prop type: Invalid prop children of type array supplied to ForwardRef(Grow), expect a single ReactElement". Can a ...

Determine if the webpage is the sole tab open in the current window

How can I determine if the current web page tab is the only one open in the window? Despite searching on Google for about 20 minutes, I couldn't find any relevant information. I would like to achieve this without relying on add-ons or plugins, but if ...

Attempting to construct an 'or' query that relies on the combination of two distinct joined tables

Currently, I am facing a challenge with selecting rows from a PostgreSQL database through Sequelize. I need to retrieve data where the ID exists in either joined table 1 or joined table 2. In my attempts using Sequelize, I used 'include' to quer ...

Use jQuery to assign a value of "true" when a checkbox is

Can you guide me on how to use jQuery to implement a click function that sets the status value to 'true' if a checkbox is checked, and 'false' if it's not checked? If Checkbox 1 is checked, Status 1 should be set to true. Similarl ...

Encountering an issue while fetching information from a JSON file using JavaScript

I am encountering an Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data let mydata = JSON.parse("file.json"); console.log(myJSON) Here is a sample of the JSON file's data: [[1,1,0,1,1,0,0,0,1,1,1,1,1, ...

Is it possible to export multiple named exports in a single set without changing how variables are called?

In my constants file I have: export const CONSTANT1 = 'CONSTANT1'; export const CONSTANT2 = 'CONSTANT2'; export const CONSTANT3 = 'CONSTANT3'; export const CONSTANT4 = 'CONSTANT4'; export const CONSTANT5 = 'CONS ...

In the Redux framework, the reducer fails to identify the action object

I'm currently working on a React project using Redux. I've encountered an issue where my reducer is not recognizing the action type being sent to it, or even the action itself. The error message I am receiving is TypeError: Cannot read property & ...

Break down React website into distinct modules and bundle them as npm dependencies within a single package

Currently, I am developing a React website that includes distinct sections such as contact management and message management. Each of these sections is quite extensive. To navigate to these sections, we use a single dashboard for control. Since separate ...

Is there a way to cross-reference a city obtained from geolocation with the cities stored in my database, and if a match is found, send the corresponding ID

Here's the script I'm currently working with: <script type="text/javascript"> search = new Vue({ el: '#offers', data: { data: [], authType: '{{uid}}', key : '1', wi ...

Transmitting OfficeJS 2D Array via an Ajax Call

Struggling with sending a "large" table using OfficeJS: functionfile.html loaded from manifest route <script> (function (){ "use strict"; Office.initialize = function (reason) { $(document).ready(function() { $("#send-data-button").cli ...

Troubleshooting why the Angular innerHTML function is failing to render the specified

I'm encountering this problem where I am receiving a string const str = '<p>Please ensure Process Model diagram represents Functions adequately (boxes that represent an activity or group of activities that produce an outcome):</p>< ...

dc.js bar graph bars blending together

This datetime barChart is causing me some trouble. Interestingly, when I try to replicate the issue in a fiddle (check here), everything functions as expected. Please note that the data takes about 30 seconds to load from github. Below is the code for the ...