Toggle the visibility of a div using JavaScript depending on the data value

I have a collection of images displayed in div tags with data attributes. My goal is to toggle their visibility using CSS based on a match with input text. I iterate through the divs with the matching class, then loop through the words in the input array, and finally, through the words in the data attribute field. The issue arises when the DOM seems to lose track of the outer index once a match is found between the inner array text values. Although the console correctly identifies the three loop index values, the JavaScript show command doesn't get executed. When I hard code the index value (0), the show command works as expected, but this approach seems overly convoluted.

HTML:

        <img
          src="images/game thumb 216px-1.png"
          alt="Photo of hotline game"
          class="gallery__photo photo1"
        />
      </div>
      <div
        class="gallery__item"
        data-new="true"
        data-top="true"
        data-value="2 neon jungle"
      >
        <img
          src="images/game thumb 216px-2.png"
          alt="Photo of neon jungle game"
          class="gallery__photo photo2"
        />
      </div>

JavaScript/jQuery:

        //building an object containing all gallery__item divs
        //let galleryitems = document.getElementsByClassName("gallery__item");
        
        //assigning search input words to a variable
        let myInputWords = $("#search").val();

        //creating an array of input words
        let myInputWordsArray = myInputWords.split(" ");

        //creating an array of gallery words
        let myGalleryItemsArray = [];
        for (let i = 0; i < galleryitems.length; i++) {
          //fetching the data-value attribute value
          let myAttributeValue = galleryitems[i].getAttribute("data-value");
          //adding it to the gallery item array
          myGalleryItemsArray.push(myAttributeValue);
        }

        //iterating through the input words array - outer loop
        //iterating through the gallery words array - inner loop
        let i, k, m = 0;
        //iterate through the input element words array
        for (i = 0; i < myInputWordsArray.length; i++) {
          //loop through gallery items array
          for ( k = 0; k < myGalleryItemsArray.length; k++) {
            //loop through each gallery item which may contain multiple words and create a new array
            let myGalleryItemArray = myGalleryItemsArray[k].split(" ");
              //iterating through each element in the gallery item array's words
              for ( m = 0; m < myGalleryItemArray.length; m++) {
              //console.log(myInputWordsArray[i]);
              //console.log(myGalleryItemArray[m]);
              //if the outer input array word matches the inner data word, change the CSS display to block; else, set it to none
              if (myInputWordsArray[i] === myGalleryItemArray[m]) {
                 galleryitems[k].style.display = "block";
                //console.log(galleryitems[k]);
              } else {
                galleryitems[k].style.display = "none";
              }
            }
          }
        }
      });

Answer №1

Upon discovering the correct word, your current gallery item will briefly appear before being hidden in the next iteration loop if the word is incorrect at that time.

To exit the current loop when the correct word is found, simply insert a break statement within the for loop. You can refer to a functional example here (https://jsfiddle.net/da7zs9wo/):

// Create an object containing all the gallery__item divs
let galleryitems = document.getElementsByClassName("gallery__item");

// Assign the search input words to a variable
let myInputWords = $("#search").val();

// Create an array of input words
let myInputWordsArray = myInputWords.split(" ");

// Create an array of gallery words
let myGalleryItemsArray = [];
for (let i = 0; i < galleryitems.length; i++) {
    let myAttributeValue = galleryitems[i].getAttribute("data-value");
    myGalleryItemsArray.push(myAttributeValue);
}

// Iterate through the input words array - outer loop
// Iterate through the gallery words array - inner loop
let i, k, m = 0;
for (i = 0; i < myInputWordsArray.length; i++) {
    for (k = 0; k < myGalleryItemsArray.length; k++) {
        let myGalleryItemArray = myGalleryItemsArray[k].split(" ");
        for (m = 0; m < myGalleryItemArray.length; m++) {
            if (myInputWordsArray[i] === myGalleryItemArray[m]) {
                galleryitems[k].style.display = "block";
                break; // End loop for this item when we found the correct word
            } else {
                galleryitems[k].style.display = "none";
            }
        }
    }
}

You may want to consider using the find ES6 method on your array to streamline the process and avoid excessive looping.

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

Have you not heard of the greatness of Selenium before?

I've been trying to automate the process of selecting my shoe size, adding it to the cart, and checking out whenever I visit a sneaker page like FootLocker or FootAction. However, each time I attempt to run the script, I encounter the following error: ...

What is the best way to customize a MaterialUI outlined input using a global theme overrides file?

I've been working on customizing my theme file with overrides, and I've encountered a strange bug while trying to style the outlined input. It seems like there are two borders appearing when these styles are implemented. https://i.stack.imgur.co ...

Determine the width of the containing element using Vue.js

I have been working on implementing a Vue.js component called CamViewMatrix. My goal is to retrieve the width of CamViewMatrix's parent element within the component itself (specifically in the created() method of CamViewMatrix), in order to perform so ...

CSS for Adjusting Parent Height Based on Child Content

I've been working on adjusting the height of the parent class to fit the child class perfectly without overflowing Here is a snippet from my CSS file: Parent &__video position: relative; width: 471px; background: red; border-radius: 12px ...

What is the best approach for writing an asynchronous function while utilizing $rootScope.broadcast within a continuous loop?

At least 10 times a second, I have a function that is called. Each time, there are approximately 100 records with variations in LastSeenTime and ReadCount. In this simulation scenario, I understand the behavior; however, in real-time, the number of records ...

Is there a way to determine if the Acrobat plugin is installed and the web viewer setting is enabled using jQuery and C#?

Is there a way in jQuery or C# (as I am currently working on an .aspx page in Sharepoint 2010) to detect if the Adobe Acrobat plugin is installed and if the web viewer setting is enabled? I understand that the plugin is usually installed with Adobe Reader ...

Updating state atoms in Recoil.js externally from components: A comprehensive guide for React users

Being new to Recoil.js, I have set up an atom and selector for the signed-in user in my app: const signedInUserAtom = atom<SignedInUser | null>({ key: 'signedInUserAtom', default: null }) export const signedInUserSelector = selecto ...

When using angular $resource.save for savings, the view is forced to redraw and reflow because of the collection watcher

One of the challenges I'm facing involves loading and storing a model using $resource in AngularJS. This particular model is an aggregate with nested collections, which are displayed in an HTML view using ng-repeat. The structure of the model looks l ...

Receive the Navigating event upon a new browser window opening with the help of the WebBrowser control in JavaScript

In my C# / .NET 4 project, I have a form containing a WebBrowser component that loads an external web page. An event handler is connected to the Navigating event which usually works well. However, there is an issue when a specific part of the loaded websi ...

Tips for managing React state when dealing with multiple axios callbacks that modify an array's state

I am currently working on a React component that allows users to upload images. In this scenario, I aim to upload 3 images. After each file is uploaded, I want to append it to the list of uploaded files. Issue: The setter method in useState is asynchronou ...

Textfield with autocomplete dropdown

I have a text field on my website that needs to work as an autocomplete box. I have included the following code in the "headerbar" section of my page: Find :<input type="text" class="input2" style="margin-bottom:0px;" id="customersearchfield"> < ...

Accessing information from a json response using an ajax request

Currently, I am making an ajax call to fetch the longitude and latitude based on a pin code. Here is how I approached it: $(document).ready(function () { $.ajax({ type: "GET", url: "http://maps.googleapis.com/ma ...

Node.js removes leading zeroes from dates

I am looking to generate a string with the current date and time in the format: "2021-06-02 09:37:38" const today = `${new Date().toLocaleDateString('sv-se')} ${new Date().toLocaleTimeString('sv-se')}`; console.log(today); ...

Align content to the bottom using Bootstrap 4

Looking for help with aligning content to the middle and bottom on a full-page bootstrap layout? The first page has a background image in the first div, and a darker layer on top in the second div. <div class="h-100 w-100"> <div class="h-100 w-10 ...

Tips for resizing a browser window using an HTML element

I decided to add a unique feature to my website - a handle in the bottom right corner that users can grab and drag to the left to see how the design adapts to different browser window sizes (Responsive Design). To implement this, I included the following ...

Struggling to input information from a web form into a MySQL database using PHP

I'm currently facing an issue with my form not being able to submit data to the MySQL database. Strangely, I'm not receiving any error messages that could help me identify the root of the problem. I experimented by changing the action method to G ...

How can I retrieve data submitted in a POST request on my Node.js server

I'm having trouble sending form data to a node/express server using AJAX. After submitting, I keep getting redirected to a 'Cannot POST /' page. Although I can log the request object on the server side, the data from the form is missing. Wha ...

How can I show or hide all child elements of a DOM node using JavaScript?

Assume I have a situation where the HTML below is present and I aim to dynamically conceal all the descendants of the 'overlay' div <div id="overlay" class="foo"> <h2 class="title">title</h2> ...

Trouble arises when emitting events in Vue using eventHub

In the development of my component, there arises a need to emit an event at a specific point in its lifecycle. This emitted event is intended to be listened to by another sibling component. To facilitate this communication, I am utilizing an event hub. H ...

Handling every promise in an array simultaneously

I am facing a problem with my array inside Promise.all. When I try to execute a function for the last iteration of forEach loop, I notice that my count_answers variable is only being set for the last object. This can be seen in the log output; the count_an ...