Toggle a jQuery bar based on the presence of a specific CSS class

I am working on a feature where I can select and deselect images by clicking on a delete button. When an image is selected, a bar appears at the top. If I click the same delete button again, the image should be deselected and the bar should disappear. This behavior should also work for multiple selections and removals.

To achieve this functionality, I have implemented logic to add a "selected" class on click and remove it when clicked again.

Subsequently, I count the number of elements with the "selected" class to determine if the top bar should be hidden or shown.

However, I always get a count of 0 regardless of the selected images.

If you could help me identify what I am missing in my code, that would be greatly appreciated!

var bar = $('#bar');
var deleteBtn = $('.delete');
var selected = $('.selected');
var selection = 0;



deleteBtn.click(function() {

  if ($(this).hasClass("selected")) {
    $(this).removeClass("selected");
  } else {
    $(this).addClass("selected");
  }

  var selection = selected.length;

  if (bar.hasClass("hide")) {
    bar.addClass("show");
  } else {
    if (selection === 0) {
      bar.removeClass("barShowY");
    }
  }
  console.log(selection + " selected images");

});
#bar {
  height: 100px;
  width: 100%;
  background-color: firebrick;
  color: white;
}

.hide {
  margin-top: -100px;
}

.show {
  margin-top: 0;
}

.delete {
  width: 50px;
  height: 50px;
  background: yellow;
  cursor: pointer;
}

.selected {
  border-bottom: 3px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="bar" class="hide">delete selected images?</div>

<div class="delete">delete</div>
<img src="https://apollo2.dl.playstation.net/cdn/UP2131/CUSA01736_00/Ll2fJdBTPQylZO0Z4JQ9rtsIJsojwBxn.png" alt="">

<div class="delete">delete</div>
<img src="https://apollo2.dl.playstation.net/cdn/UP2131/CUSA01736_00/lYG2Mgzz878Z8rU3yvlx9MwmR5dhDsyy.png" alt="">

<div class="delete">delete</div>
<img src="https://apollo2.dl.playstation.net/cdn/UP2131/CUSA01736_00/Zp2VXCJxT764bqDPyyIy0Yf2ZRFHzr3g.png" alt="">

Answer №1

It is recommended to utilize the following code snippet:

 var selection = $('.selected').length;

Instead of using:

var selection = selected.length;

This is because the statement var selected = $('.selected'); will store all elements with the 'selected' class in the variable selection. If there are no elements with this class, it will result in a count of zero.

var bar = $('#bar');
var deleteBtn = $('.delete');
var selection = 0;

deleteBtn.click(function() {

  if ($(this).hasClass("selected")) {
    $(this).removeClass("selected");
  } else {
    $(this).addClass("selected");
  }

  var selection = $('.selected').length;

  if (bar.hasClass("hide")) {
    bar.addClass("show");
  } else {
    if (selection === 0) {
      bar.removeClass("barShowY");
    }
  }
  console.log(selection + " selected images");

});
#bar {
  height: 100px;
  width: 100%;
  background-color: firebrick;
  color: white;
}

.hide {
  margin-top: -100px;
}

.show {
  margin-top: 0;
}

.delete {
  width: 50px;
  height: 50px;
  background: yellow;
  cursor: pointer;
}

.selected {
  border-bottom: 3px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="bar" class="hide">delete selected images?</div>

<div class="delete">delete</div>
<img src="https://apollo2.dl.playstation.net/cdn/UP2131/CUSA01736_00/Ll2fJdBTPQylZO0Z4JQ9rtsIJsojwBxn.png" alt="">

<div class="delete">delete</div>
<img src="https://apollo2.dl.playstation.net/cdn/UP2131/CUSA01736_00/lYG2Mgzz878Z8rU3yvlx9MwmR5dhDsyy.png" alt="">

<div class="delete">delete</div>
<img src="https://apollo2.dl.playstation.net/cdn/UP2131/CUSA01736_00/Zp2VXCJxT764bqDPyyIy0Yf2ZRFHzr3g.png" alt="">

Answer №2

Before applying the class on the element causing the error, make sure to move the selection of the .selected class inside the delete button as shown below:

var bar = $('#bar');
var deleteBtn = $('.delete');

var selection = 0;

$(document).ready(function() {

  deleteBtn.on('click', function() {
    console.log($('.selected').length);
    if ($(this).hasClass("selected")) {
      $(this).removeClass("selected");
    } else {
      $(this).addClass("selected");
    }

    var selection = $('.selected').length;

    if (bar.hasClass("hide")) {
      bar.addClass("show");
    } else {
      if (selection === 0) {
        bar.removeClass("barShowY");
      }
    }
    console.log(selection + " selected images");

  });
})
#bar {
  height: 100px;
  width: 100%;
  background-color: firebrick;
  color: white;
}

.hide {
  margin-top: -100px;
}

.show {
  margin-top: 0;
}

.delete {
  width: 50px;
  height: 50px;
  background: yellow;
  cursor: pointer;
}

.selected {
  border-bottom: 3px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="bar" class="hide">delete selected images?</div>

<div class="delete">delete</div>
<img src="https://apollo2.dl.playstation.net/cdn/UP2131/CUSA01736_00/Ll2fJdBTPQylZO0Z4JQ9rtsIJsojwBxn.png" alt="">

<div class="delete">delete</div>
<img src="https://apollo2.dl.playstation.net/cdn/UP2131/CUSA01736_00/lYG2Mgzz878Z8rU3yvlx9MwmR5dhDsyy.png" alt="">

<div class="delete">delete</div>
<img src="https://apollo2.dl.playstation.net/cdn/UP2131/CUSA01736_00/Zp2VXCJxT764bqDPyyIy0Yf2ZRFHzr3g.png" alt="">

Answer №3

The selected state needs to be defined within the event handler function. Here is an example of how you can handle this in your JavaScript file:

var bar = $('#bar');
var deleteBtn = $('.delete');
var selection = 0;

deleteBtn.click(function() {

  if ($(this).hasClass("selected")) {
    $(this).removeClass("selected");
  } else {
    $(this).addClass("selected");
  }

  var selected = $('.selected'); // Make sure to include these lines
  var selection = selected.length;

  if (bar.hasClass("hide")) {
    bar.addClass("show");
  } else {
    if (selection === 0) {
      bar.removeClass("barShowY");
    }
  }

  console.log(selection + " images are currently selected");
});

To see it in action, visit CodePen https://codepen.io/anon/pen/zPMNeX?editors=1111
or try it on JSBin http://jsbin.com/cifekojasu/edit?js,console,output

Answer №4

I have made adjustments to the code and it seems to be producing the desired results

var selection = $('.selected').length;
if (bar.hasClass("hide")) {
  bar.removeClass("hide");
  bar.addClass("show");
} else {

  if (selection === 0) {
     bar.removeClass("show");
     bar.addClass("hide");
  }
}

Did you mean for barShowY to be simply show?

Check out the Codepen snippet here : https://codepen.io/anon/pen/dZQNxM

Answer №5

Upon loading the document, the quantity of selected images is captured and cached. Consequently, this results in always obtaining the same number (0). To ensure live updates, it's essential to recalculate the quantity upon each click.

var bar = $('#bar');
var deleteBtn = $('.delete');

deleteBtn.click(function() {
  var selected;
  
  $(this).toggleClass('selected');
  
  selected = $('.selected').length;
  
  if (!selected) {
    bar.removeClass('show');
  } else {
    bar.addClass('show');
  }

  console.log($('.selected').length + " selected images");
});
#bar {
  height: 100px;
  width: 100%;
  background-color: firebrick;
  color: white;
}

.hide {
  margin-top: -100px;
}

.show {
  margin-top: 0;
}

.delete {
  width: 50px;
  height: 50px;
  background: yellow;
  cursor: pointer;
}

.selected {
  border-bottom: 3px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="bar" class="hide">delete selected images?</div>

<div class="delete">delete</div>
<img src="https://image-url-1.png" alt="">

<div class="delete">delete</div>
<img src="https://image-url-2.png" alt="">

<div class="delete">delete</div>
<img src="https://image-url-3.png" alt="">

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

Creating a primary index file as part of the package building process in a node environment

Currently, I have a software package that creates the following directory structure: package_name -- README.md -- package.json ---- /dist ---- /node_modules Unfortunately, this package cannot be used by consumers because it lacks an index.js file in the r ...

Create a nested array of subcategories within an array object

Currently, I am working on integrating Django Rest and Angular. The JSON array received from the server includes category and subcategory values. My goal is to organize the data such that each category has its related subcategories stored as an array withi ...

No invocation of useEffect

I am facing an issue with my React app at the moment. My high-level useEffect is not being triggered, although it works in another project with similar code. Typically, the useEffect should be called every time I make an HTTP request from the app, but noth ...

Using Laravel: Validate username existence with jQuery AJAX before form submission

After creating a registration form with numerous fields, I encountered an issue when submitting data and receiving validation errors. The user would have to refill empty inputs, causing unnecessary delays. To streamline the process, I am looking to impleme ...

Creating a seamless user experience with Jquery validation, ajax, and php without the need for

I have been struggling with a problem solution for quite a few days now. I am trying to implement jQuery validation and AJAX calls without page refresh simultaneously. Interestingly, when I use either of them separately, the code works perfectly fine. Howe ...

Tips for uploading an image to a .NET Webservice with Ajax on Internet Explorer 8

Check out this post about sending images to a PHP file using Ajax: How to send image to PHP file using Ajax? I was able to successfully implement the solution mentioned in the post, but I'm encountering issues with Internet Explorer 8. Is there a wa ...

Unlocking the potential of input values in Angular.jsDiscovering the secret to

I'm currently experimenting with the angular date picker directive. My goal is to retrieve the entered date value from the date picker and log it to the console. However, all of my attempts so far have been unsuccessful. Here's a snippet of my c ...

What is the best way to customize the MenuProps of Material UI Select component using createTheme?

I'm trying to update the dropdown menu style of my Material UI Select component using createTheme, but I'm having trouble getting it to work. https://i.sstatic.net/zpVjW.png Here is the code I have so far. Can you spot what might be causing the ...

After attempting to install @mui/system, I encountered an error. I decided to uninstall it, but now I am consistently facing this

ERROR in ./node_modules/@mui/material/Unstable_Grid2/Grid2.js 6:14-25 export 'createGrid' (imported as 'createGrid2') was not found in '@mui/system/Unstable_Grid' (module has no exports). Encountering an issue after installin ...

The button in Bootstrap 4 that triggers the modal stays in a highlighted or clicked state even after the modal has been

I am currently utilizing the button below to trigger the opening of a modal window However, upon closing the modal, it seems to maintain a highlighted or clicked appearance with a shadow effect. Initially, I assumed I could address this issue by implement ...

Is it possible to use a Proxy-object instead of just an index when changing tabs in material-ui/Tabs?

Using material-ui tabs, I have a function component called OvertimesReport with Fixed Tabs and Full width tabs panel: const TabContainer = ({children, dir}) => ( <Typography component="div" dir={dir} style={{padding: 8 * 3}}> {children} & ...

Retrieving selected option value in React

I am currently using Material UI for my React application and I am encountering an issue with getting the value of a select form. Initially, I had success with the following code snippet: <select name="role" value={props.role} onChange={props.handleIn ...

Create a responsive DIV element within a website that is not originally designed to be responsive

I am looking to optimize the positioning of an ad div on my non-responsive website. The current setup has the ad displayed at 120x600 pixels, always floating to the right of the screen. While this works well for desktop or large devices, the display become ...

Using Jquery to toggle a class on click, and dynamically change based on the screen size

I am trying to figure out how to toggle a CSS class on an element by clicking on a div using jQuery. I know how to do it, but I also want the toggle to only happen when the screen size is less than 800px. I'm not very familiar with JavaScript, so I co ...

Trigger javascript function with a button click

Is there a way to trigger a JavaScript function from an HTML button that is not functioning properly? REVISED To see the issue in action, please visit this jsfiddle link: http://jsfiddle.net/winresh24/Sq7hg/341/ <button onclick="myFunction()">Try i ...

Troublesome code with Ajax, Jquery, and PHP is causing issues

I've been trying to send an array from php to js using ajax, but for some reason it's not working no matter what I try. I'm convinced it must be a simple fix, but I seem to have exhausted all my options. <!doctype html> <html lang= ...

What is the method for displaying data from a JSON file that is associated with the wallet address of the authenticated user in next.js?

I am currently working on a claim page using next.js, where logged in Metamask addresses can perform the following tasks: Access data from a local .json file to check eligibility for claiming an item and display the claim page. Submitting a form to update ...

How to hide or remove an element in jQuery depending on an attribute change

I am currently working on my website and exploring ways to utilize jQuery to display or add the element div#content1 when the #nav-home-tab has aria-selected=true, and to hide or remove the element if aria-selected=false. This is what I have tried so far: ...

Ever since updating my Node JS, the functionality of the MaterializeCSS carousel methods has ceased to work

Recently, I encountered some issues with my React project that features a materialize-css carousel. The problem arose after updating my nodeJS version from 14.8.1 to 16.13.0. Specifically, these errors kept popping up: TypeError: Cannot read properties o ...

Is there a specific event in Angular.js that triggers when the $scope digest cycle is completed or when the view is refreshed?

Currently, I am making an AJAX request to retrieve data that is needed in the view to generate a list. My goal is to determine when the $scope has been updated and when the view has finished rendering after receiving a successful response. This will allow ...