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="">