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

Utilizing 'this' in jQuery: Image swapping with thumbnails, Twitter Bootstrap framework

Is it possible for jQuery's 'this' to simplify my code? You can view the full code here. Thank you for any help or suggestions. Here is the jQuery code: /* Ref: http://api.jquery.com/hover/ Calling $( selector ).hover( handlerIn, handler ...

React-virtualized list experiencing performance problems due to react-tether integration within its elements

Description I need help with a challenging issue. I have a long list of items displayed in a react-virtualized VirtualScroll. Each item on the list contains many elements, including one that triggers a context menu. I'm using react-tether to attach t ...

The value of the ng-model checkbox does not update or change when the checkbox is clicked

There is a checkbox being used in the code snippet below: <input type="checkbox" ng-click="toggleShowOtherUserConfiguration()" ng-model="showOtherUserConfiguration" name="ShowOtherUserConfiguration" value="showOtherUserConfigurati ...

What exactly do bootstrap, javascript, jquery, and ajax entail?

Exploring the world of client-side scripting to enhance web page dynamism and data collection has piqued my interest. I have come across programming languages like JavaScript, Ajax, and jQuery. However, uncertainty clouds my understanding as concepts remai ...

Toggle the menu using jQuery on unordered list items

Below is the HTML code I am using : <ul class="main-block"> <li class="firstLevel"> <a href="#category">EXAMPLE CATEGORY 1</a> <ul class="dijete"> <li class="child"> <a href="some-sub-categ ...

Can I extract JSON data from the AJAX response?

When receiving JSON data, such as in the example below, it is often necessary to separate each value into individual variables: var reviewDate ='2015-06-01T05:00:00Z' var developers ='Ankur Shah,Srikanth Vadlakonda,Tony Liu, Qiuming Jie&ap ...

Tips on providing validation for either " _ " or " . " (select one) in an Angular application

I need to verify the username based on the following criteria: Only accept alphanumeric characters Allow either "_" or "." (but not both) This is the code snippet I am currently using: <input type="text" class="form-control" [ ...

Real-time updates for UI data in Next.js Firestore are not being reflected

I'm currently working on implementing real-time changes using nextjs and Firebase Firestore. However, I've noticed that I still need to refresh the page in order for the updates to be visible. const [getUsers, setUsers] = useState(""); const che ...

Streaming audio from a microphone to speakers on Ubuntu using HTML5

Currently diving into html5 and eager to experiment with playing back what I say on a microphone through speakers. Here is the JavaScript code I've put together: navigator.getUserMedia = navigator.getUserMedia ||navigator.webkitGetUserMedia || naviga ...

Prevent running function bodies simultaneously based on user events in JavaScript until a previously triggered execution is completed

When a user clicks on a button in my component, the doSomething function is activated. The issue I am facing is that doSomething takes between 200-1100ms to finish execution and change state. What complicates matters is that when the button is clicked rapi ...

When attempting to remove an object from an array in Vue.js, an error may occur stating that the property of the

In my project, I am working with 3 files: App, BlogList, BlogItem. The goal is to enable users to delete a post if they choose to. However, when using splice method, I encountered the following error: The property or method "removePost" is not defined o ...

Display buttons when hovering with React

Seeking assistance with implementing functionality in a React application where buttons for editing and deleting display only when the mouse hovers over the corresponding row. Currently, the implemented code displays these buttons in all rows on hover. Sn ...

Navigating the loading of information with fetch and React Hooks

As a newcomer to React and still learning JavaScript, I am facing a challenge with handling useEffect alongside an asynchronous function. My goal is to fetch data from an API and render a quote in the paragraph with id of text, along with the author's ...

Creating static HTML files for non-static pages using Next.js SSR/ISR

While troubleshooting an issue with a specific page, I noticed that a static HTML file was created for a non-static page using Next.js. Is this expected? The page, which we will refer to as "page1," does not include the functions getStaticPaths() or getSta ...

Retrieving the value of a specific image using Jquery

<div id="choose"> <div class="picked"> <img src="/def/image1.png"> </div> <div> <img src="/def/image2.png"> </div> <div > <img src="/def/image3.png"> </div> </div& ...

Utilizing the sAjaxSource property in Datatables to fetch data through Ajax from multiple tables while dynamically passing arguments

I am facing an issue with populating two datatables using data retrieved from a flask API through a GET request. My data source URL is localhost:5000/data, but for some reason, I am unable to display the data in the datatables. Interestingly, when I use a ...

The returned error object from express does not include the error message

I recently posted a question related to an error issue. I am now wondering if I should have edited that question instead. Regarding the code snippet below: app.use((err, req, res, next) => { res.status(err.status || 500); res.json({ message: e ...

Incorporating a JavaScript advertisement zone within a PHP function

Currently in the PHP template, I am trying to embed a JavaScript ad zone inside a function in order to have control over each page's ad placement. Here is what I have: <?php if(is_page('welcome-president')) { oiopub_b ...

Transmit a data element from the user interface to the server side without relying on the

I have developed a MEAN stack application. The backend of the application includes a file named api.js: var express = require('express') var router = express.Router(); var body = 'response.send("hello fixed")'; var F = new Function (" ...

Switch up the color of checkboxes with a dropdown menu option

I have an HTML dropdown code and I am trying to trigger a click event when a specific value is selected. Once this value is clicked, I want some checkboxes to change color. <select> <option value="calculate">calculate</option> ...