Generate a loop specifically designed to execute the code following the menu in the script

My website has the code snippet below:

let txt_com = document.querySelector(".text_user");
let num_com_user = document.querySelector(".massage_for_user");

txt_com.addEventListener("click", function() {
  if (this.classList.contains("num_com_user")) {
    this.classList = "num_com_user";
    num_com_user.style.display = "none";
  } else {
    this.classList = "num_com_user";
    num_com_user.style.display = "block";
  }

  return;
})
<div class="box_main">
  <div class="box-txt">
    <span class="text_user">click</span>
  </div>

  <span class="massage_for_user">No text found!</span>
</div>

The issue I am facing is that this code works only once and requires a page refresh for it to work again. What I actually want is for the menu to toggle open/close every time I click on the post.

Answer №1

Instead of using a loop, it is recommended not to replicate CSS functionality in JavaScript. Simply toggle a class rather than modifying the .style property.

A good practice is to create a utility class like .hidden to hide an element and then toggle that class on the desired element. Here's an example:

let txt_com = document.querySelector(".text_user");
let num_com_user = document.querySelector(".massage_for_user");

txt_com.addEventListener("click", function() {
  num_com_user.classList.toggle('hidden');
  
  // any additional code here will execute each time the menu is clicked
})
.hidden {
  display: none;
}
<div class="box_main">
  <div class="box-txt">
    <span class="text_user">click</span>
  </div>

  <span class="massage_for_user">No text found!</span>
</div>

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 dropdown menu button stubbornly remains open and refuses to close

Having an issue with a dropdown menu button where it should open when clicked on the icon and close when clicking off the icon or on the icon again, but instead, it remains open. Here is a screenshot for reference: https://i.stack.imgur.com/UX328.jpg I&a ...

I am getting NaN as the output from my function, but I am unsure of the reason behind

For pracitce, I have created this code to calculate the total amount spent on gas and food using arrays. However, I am encountering an issue where it is returning NaN. const gas = [20, 40, 100]; const food = [10, 40, 50]; function total(gas, food) { ...

What is the best way to launch a Popup window that spans from the top to the bottom of the screen?

I'm attempting to create a popup window that stretches from the top of the screen to the "applications" bar in Windows. Here's the code I'm using: function windowOpener(windowHeight, windowWidth, windowName, windowUri) { var windowHeight = ...

Where should JSON data be sourced from when developing a service in AngularJS?

Just starting out with Angular! Am I correct in assuming that when creating a service, you request JSON data from a server controlled by someone else? For example, if I wanted to develop a Weather app, where could I find the JSON data? Is there a standar ...

Retrieving device information through JavaScript, jQuery, or PHP

Looking to build a website that can identify the device name and model of visitors accessing the page from their devices. ...

Delaying loops with JQuery Ajax

I am attempting to implement a delay in my AJAX data processing so that the loop runs a bit slower. Here's the code I'm working with: $(document).ready(function (){ $('#button').click(function(){ $('#hide').show ...

Altering the dimensions of Bootstrap's default navbar for a more compact look

Currently, I am attempting to modify the size of Twitter Bootstrap's standard navbar to a smaller dimension. My goal is to have the Brand/logo on the left side, menu options in the center, and social media icons on the right side within the navbar. U ...

Challenges with differentiating between addition and concatenation in Vue computed properties

Recently diving into Vue and came across an intriguing issue, I am curious to know the reason behind it and how to prevent it. <template> <div> <input type="number" v-model="a" style="color: white" /> <input type="number" v- ...

Angular 2 ngFor generates a collection of rows and columns forming a single large column

It seems that ngfor is generating divs one by one, resulting in a poor design where they are stacked on top of each other. I would like to achieve a layout like this: [1] [2] [3] [4] [5] [6] However, the current outcome looks like this: [ 1 ] [ 2 ] [ 3 ...

Can the ::before selector be used in HTML emails?

Hey there, I have a question that might sound silly but I'm having trouble finding an answer online. My issue is with styling the bullet point before a list item in an HTML email. All I want to do is change the bullet point to a square and give it a ...

Tips for implementing a jQuery plugin on specific elements within an HTML page

I've been experimenting with the jQuery extension for searchable dropdowns available at this link. While I am impressed with its functionality, I'm looking to apply it selectively to specific elements on my webpage rather than all of them. Is the ...

Android experiencing issues with dynamically loading Border XML

I am having trouble setting a border dynamically for a RelativeLayout. Oddly enough, when I manually add the border in the activity XML file, it displays perfectly. However, when I try to generate the border dynamically, it doesn't appear. border.xml ...

Ways to widen a selected drop-down menu outside the dialog box containing it

I'm working with a Html.DropDownList that has been styled using Chosen within a jQuery UI dialog. As the list of items is quite long, when it's opened, it gets cut off by the border of the dialog window. Is there a way to extend the dropdown por ...

Ensuring a response is sent back only after a loop has completed in NodeJs

Struggling to properly format the logic in order to send back a fully populated array of objects after a GET request to a specific URL. The goal is to take the "connections" array from the user making the request, extract the connection's name and pic ...

Seeking a breakdown of fundamental Typescript/Javascript and RxJs code

Trying to make sense of rxjs has been a challenge for me, especially when looking at these specific lines of code: const dispatcher = fn => (...args) => appState.next(fn(...args)); const actionX = dispatcher(data =>({type: 'X', data})); ...

Update specific fields in a MySQL database using Express.js only if they are passed as parameters

After spending several days trying to set up a REST API, I found a helpful tutorial that explained the basics of sending requests and receiving responses. The only issue is that the tutorial uses MongoDB and Mongoose, while I'm working with MySQL. Due ...

Unable to move cursor in contenteditable section

I am currently working on developing a rich text editor in React, but I have encountered an issue that has me stuck. The problem I am facing is that as I type each character, the insertion point does not update accordingly, causing the cursor to remain stu ...

Guide for implementing onclick event for info boxes in push pins on Bing Maps using ReactJS

I have successfully placed all the coordinates on the map using pushpins, but now I want to create an event that shows an infobox when a pushpin is clicked. Could someone provide an example of how to hide infoboxes and only show them when a pushpin is cli ...

Alter the content of a div depending on the values of three different elements

Hello everyone, I am new to the world of jQuery and javascript, and I am facing a challenge that I need some help with. Within a form, there are two fields that I would like to perform calculations on. Here is what I have attempted so far: jQuery.fn.calcu ...

Determine the presence of an image by using a wildcard in the URL

I need to show an image, and if it doesn't exist I want to display a default image. The challenge is that the image can come with any extension. Can someone suggest how I can modify the $.get() function in the code snippet below to make it search for ...