Toggle the visibility of multiple divs depending on a specific attribute value

I previously inquired about this issue, but I believe my wording was unclear and the responses focused on how to display or hide a group of divs when clicking a button. While I understand that concept, my specific challenge is slightly different. Let me provide a more detailed explanation:

I have multiple divs containing images

<div ng-controller='PhotoController'>
  <button>SHOW ALL</button>
  <button>SHOW FILTERED</button>
  <div ng-repeat="photo in photos" ng-show='isShowImage' class='image-container'>
     <img ng-src ='{{photo.src}}' data-show='{{photo.filtered}}'>
     <br/>
 </div>
</div>

The {{photo.filtered}} value is retrieved from the database and will be an integer. My goal is for the SHOW FILTERED button to only display divs with the class image-containers that contain images where the data-show attribute is not zero.

When clicking SHOW ALL, all images should be displayed regardless of the data-show value.

I am aware that by adding ng-show={{photo.filtered}} to the image-container div, I can show images with a non-zero data-show attribute. However, I am unsure how to adjust this criteria when the SHOW ALL button is clicked.

Any suggestions would be greatly appreciated.

Answer №1

ng-show and ng-hide directives require an expression, so you can include a condition like showAll || photo.filtered

<div ng-controller='PhotoController'>
  <button ng-click="showAll = true;">SHOW ALL</button>
  <button ng-click="showAll = false;">SHOW FILTERED</button>
  <div ng-repeat="photo in photos" ng-show='showAll || photoFiltered' class='image-container'>
     <img ng-src ='{{photo.src}}' data-show='{{photo.filtered}}'>
     <br/>
  </div>
</div>

With this code, clicking on show all will make all divs visible regardless of whether the photo.filtered property is true or false. However, setting showAll to false will only show divs with a photo.filtered property that is true.

Answer №2

If this response does not provide the required assistance, please provide feedback in the form of a comment. I have included additional image-container div elements to replicate the full scenario for testing and deployment purposes. The rationale behind fetching the image-container every time the button is clicked is to ensure that all are accounted for when the program executes, especially in cases where frequent AJAX updates are involved. As the nature of this program suggests potential AJAX usage without specific details, I have taken necessary precautions. Feel free to reach out if further assistance is needed.

To assign custom attributes using JavaScript, utilize the following functions... elem.getAttribute('attr-name');//retrieve attribute value elem.setAttribute('attr-name','attr-value');//assign attribute value

window.onload = function() {
  var showAllButton = document.getElementById('showAllButton');
  var showFilteredButton = document.getElementById('showFilteredButton');
  showAllButton.onclick = function() {
    var containers = document.getElementsByClassName('image-container');
    for (var i = 0; i != containers.length; i++) {
      containers[i].style.display = 'block';
    }
  };
  showFilteredButton.onclick = function() {
    var containers = document.getElementsByClassName('image-container');
    for (var i = 0; i != containers.length; i++) {
      if (containers[i].children[0].getAttribute('data-show') > 0) {
        containers[i].style.display = 'block';
      } else {
        containers[i].style.display = 'none';
      }
    }
  };
};
<div ng-controller='PhotoController'>
  <button id="showAllButton">SHOW ALL</button>
  <button id="showFilteredButton">SHOW FILTERED</button>
  <div ng-repeat="photo in photos" ng-show='isShowImage' class='image-container'>
    <img ng-src='{{photo.src}}' data-show='14'>testing
    <br/>
  </div>
  <div ng-repeat="photo in photos" ng-show='isShowImage' class='image-container'>
    <img ng-src='{{photo.src}}' data-show='5'>testing
    <br/>
  </div>
  <div ng-repeat="photo in photos" ng-show='isShowImage' class='image-container'>
    <img ng-src='{{photo.src}}' data-show='0'>testing
    <br/>
  </div>
</div>

Answer №3

Set up a variable to control the display mode and create a function to determine if an image should be shown, like so:

JavaScript:

.controller('ImageController', function($rootScope, $scope) {

    $scope.ShowAll = true;

    $scope.canShowImage = function(image) {
        return ($scope.ShowAll || image.filtered == 1);
    };

});

HTML:

<div ng-controller='ImageController'>
  <button ng-click="ShowAll = true">SHOW ALL</button>
  <button ng-click="ShowAll = false">SHOW FILTERED</button>
  <div ng-repeat="image in images" ng-show='isShowImage' class='image-container'>
     <img ng-src ='{{image.src}}' ng-show='canShowImage(image)'>
     <br/>
 </div>
</div>

I hope this information is useful.

Answer №4

Here is an example of a possible solution

 $('.filter_button').click(function(){
      $('.filtered_items').hide();
      $.each($('.filtered_items',function(i,v){
           if($(v).find('img:first()').data('visible')) $(v).show();
      });
 });
 $('.show_all_items').click(function(){
      $('.filtered_items').show();         
});

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 jQuery AJAX request is not returning a truthy value when parsing

On my website, I am dealing with a large form and using the serialize() method to process it. However, I have encountered an issue: After completing the form, the result always returns false. I checked this using Firebug. Even though data.ok == true has ...

Tips for achieving a static background image while allowing scrolling on a webpage in asp.net

I am struggling to implement this on my website. The background image needs to be fixed while the content of the webpage should scroll in asp.net <head runat="server"> <title></title> <style type="text/css"> body { backgr ...

What could be causing getStaticProps to receive an incorrect slug value?

Currently, I am encountering an issue with obtaining the correct slug in getStaticProps(). My goal is to retrieve the translated slug for a specific page (for example: the about page). The getStaticPaths() function is able to generate the correct object. ...

Create an HTTP service using promises in AngularJS

Upon accessing a specific page of the application via its URL, I aim to verify whether the page can be loaded by making an API call. If allowed, the page should load; otherwise, it should redirect to a different page within the application. To achieve th ...

Converting user IDs to usernames in discord.js

I'm currently developing a bot and I want to implement a feature where every time a command is used, it logs the action in the console. Here's the code snippet I've been working on: console.log(message.author ++ ,`used the comman ...

Displaying a JQuery notification when hovering over a link

I am having trouble getting an alert to pop up when I hover over a hyperlink using JQuery and Javascript. The hyperlink is inside an anchor within the main section of the HTML. Any assistance would be much appreciated. Here is my current code snippet: &l ...

Save all dynamically received data from a form in PHP as an array

I have developed a PHP form that dynamically adds new text variables in this manner: <form action="" enctype=”multipart/form-data” method="post" action="<?php echo $_SERVER['REQUEST_URI'];?>"> <div id="div"> va ...

Codeigniter displays a view with an empty variable

After submitting data from another form, I am able to successfully retrieve and print the ID with `print($id)`. However, when I try to pass it to the view, the value returned is null. Below is the code snippet: Jquery post function viewAccount(orId) { ...

Building and executing an Angular 2 program on the Windows platform: Step-by-step guide

After successfully installing npm and related packages including TypeScript and Angular 2, I am encountering difficulties running Angular 2 in my browser on a Windows platform. Can someone provide a step-by-step guide to help me create and run Angular 2 ...

Tips for storing arrays in AngularJS with JavaScript

I am new to using JavaScript. I have a function that stores objects in an array to an Angular model. Here is an example: function getSpec(){ debugger var i; for(i=0;i<main.specifications.length;i++){ main.newProduct.Specification= ( ...

Is there a way to modify the button's color upon clicking in a React application?

I am a beginner in the world of React and currently exploring how to utilize the useState hook to dynamically change the color of a button upon clicking. Can someone kindly guide me through the process? Below is my current code snippet: import { Button } ...

Adding middleware to the res.render() function can be extremely helpful when dealing with a large number

Recently, I put together a webpage for local use and it involves many routes. Specifically, I have 31 .ejs files and 3 .html files all neatly stored in the "views" folder. //app.js - using node and express app.get('/page1', function(req, res ...

Dealing with a jQuery/JavaScript issue involving thumbnail images

I am facing an issue with smooth transitions between thumbnail images in HTML list tags. I have Jquery listeners set up for mouseenter and mouseleave events that update a parent image when a thumbnail is hovered over. The problem arises when scrolling fro ...

Ensuring Package Security in NodeJS and NPM

Given the immense popularity of NodeJS and how NPM operates, what measures can be taken to prevent the installation of insecure or malware-laden packages? Relying solely on user feedback from sources like StackOverflow or personal blogs seems to leave a si ...

Activate animation when a user clicks on a link

Hey there, I'm a bit unsure about how to word this and I'm still getting the hang of StackExchange so I hope I've posted in the correct place. Currently, I am developing a mobile HTML5 app that utilizes Phonegap/Cordova (as well as Bootstra ...

How to update the selected autocomplete item in Vue using programming techniques?

Although I am still learning Vue, consider the following scenario: <v-autocomplete v-model="defaultUser" :hint="`User: ${defaultUser.username}`" :items="users" :item-text="item =>`${item.firstName} - $ ...

Extract branch, path, and URL from the .gitmodules file by utilizing JavaScript Regex

Is there a way to extract branch, path, and URL details from the .gitmodules file using JavaScript Regex? .gitmodules [submodule "PATH"] path = <PATH> url = <URL> [submodule "PATH"] path = <PATH> url = <URL> ...

Adjust the path of an element as it decreases in size

Sorry for the weird title, but that's likely why I can't find the solution on my own. I'm experimenting with CSS animations and I want the form element to decrease in height from 100px -> 0, but I want it to collapse from the top to the ...

Utilize Jquery to send a POST request and obtain a corresponding reply from the Node

I'm encountering a minor challenge. I want to make a simple HTTP POST request using AJAX jQuery to a Node.js server and have the server respond accordingly. Unfortunately, I haven't been successful in retrieving the response from the server. I wo ...

Stop the ngRepeat after completing one iteration, by utilizing the "in" directive

My goal is to gather additional information about the van by using its unique id to retrieve data from the fleet it belongs to. Currently, my code successfully retrieves information about the van. However, when I uncomment certain lines of code, it breaks ...