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

How can I designate the file name when using Ajax to export in Excel formatting?

Can you help me with the code to set a specific filename for downloading an Excel file? if(comp_id != "Select Company") { $.ajax({ url: 'includes/export.php', data: { action: 'compreport', 'comp':comp_i ...

Webkit causing complications with straightforward CSS3 animation

I'm currently working on a website and you can check it out here: Unfortunately, I've encountered an issue where the animations aren't triggering specifically on webkit browsers like Chrome and Safari: @-webkit-keyframes slideright{ 0% {tr ...

Steps to display a variable in JavaScript on an HTML textarea

I'm working on a JavaScript variable called 'signature' var signature; //(Data is here) document.write(signature) Within my HTML document, I have the following: <div id="siggen"> <textarea id="content" cols="80" rows="10">& ...

Transferring the "key" and "values" data from a JSON object to a perl script

I am currently working on developing a shopping cart application. All the items stored in the shopping cart are kept within a JavaScript object called Cart, with data structured like {"sku"=quantity}. For instance: Cart={"5x123"=1,"5x125"=3} At this ...

What is the best way to adjust inline svg to the user viewport size?

After working on integrating my interactive SVG maps into my HTML pages, I encountered a minor issue: when inserting my inline SVG into a standard, non-responsive HTML document, it automatically adjusts itself to fit nicely within the user's viewport. ...

Using the Facebook marketing API requires a valid Instagram account ID to be provided as a parameter

I've been exploring the capabilities of the Facebook Marketing API once again. After successfully creating Facebook ads using my Node.js app, I now have my sights set on Instagram. My current call to create an AdCreative looks like this: fb.api(&ap ...

What is the best way to retrieve text from the p tag and input it into the text field?

Looking to resolve a situation where two identical IDs exist and need to implement some JQuery. The objective is for the input value to automatically update itself based on changes in the text of the p tag. $(document).ready(function(){ ...

Struggling to effectively transfer a callback function within a series of functions

I am currently utilizing the codebird library to make requests to the Twitter API. The responses from these requests are functioning as expected, but I am looking to pass that response along to my route. Below is a segment of my route.js: router.get(&apos ...

Angular version 4 is used to retrieve deeply nested JSON data

How do I extract data from a nested JSON file? Here is an example of the JSON structure: { "user1": { "name": "john", "surname": "johnsson" }, "user2": { "name": "Jacob", "surname": "Jacobsson" } } I want t ...

The Reason Behind Component Non-ReRendering in Redux

I am currently facing an issue with my component and reducer. The `componentDidMount()` method in my component is calling a server to get some data, but the component doesn't re-render after the action is performed. I have checked my code multiple tim ...

The text stubbornly refusing to conform to a single line

I am currently experiencing an issue where the text inside the anchor tag is not adjusting to a single line. Below is my HTML code: <html> <head> <link rel="stylesheet" href="style5.css" type="text/css"> </head> ...

Position elements in the center of the page at 33.3333% width

I'm facing a challenge with centering elements that are floated left and have a width of 33.33333% on the page. I want the text inside these elements to remain aligned to the left, but I'm unsure how to go about centering the items: ul.home-pr ...

What is the easiest method for querying one-to-many connections in Django?

Looking for a more efficient way to return a dictionary in JavaScript that includes data from both a Category table and Sub_category table. The desired format is 'Category1': 'Sub_cat1, Sub_cat2, ...'. Any ideas on a better approach? T ...

What is the best way to determine which section of a promise chain is responsible for an error in Javascript?

(Please excuse any errors in my English) I am currently studying JavaScript promises. Below is a simple JavaScript code snippet for node.js (using node.js version v10.0.0) that asynchronously reads and parses a JSON file using promise chaining. const fs ...

Bundling extraneous server code in client rollup

Can someone help me understand why the following code is being included at the top of my browser bundle by Rollup? It seems like these references are not used anywhere from my entry point. Could it be default includes from node builtins? import require$$0$ ...

Discover the secret to incorporating concealed text in WordPress with a hidden div through the power of JavaScript

For a while now, I've been trying to implement a functionality where clicking on a text reveals a dropdown menu with more information, similar to a "read more" feature. I have limited experience in Java or jQuery, and I can't figure out if the i ...

Interactive loading of datalist choices using AJAX in the Firefox browser

I have recently decided to replace the Jquery UI autocomplete function on my website with HTML5 datalists that load dynamic options. After researching this topic extensively, I came across various answers on Stack Overflow, such as How do you refresh an HT ...

Unable to Modify TextField Component in React

Is it possible to attach variables to TextField and have those variables deleted as a whole and not editable? Check out the Codesandbox example HERE code <CardContent> <Autocomplete value={values.variable} options={variables} ...

I am looking for a way to display multiple images when the user clicks a button. It needs to be done

After successfully implementing a draggable single circle image when clicking a button, I am now looking to add multiple circle images each time the button is clicked. I'm considering using the append function with the canvas tag for this purpose. Ca ...

Having difficulty communicating with the smart contract using JavaScript in order to retrieve the user's address and the balance of the smart contract

Hi there, I am a newcomer to the world of blockchain technology. Recently, I created a smart contract designed to display both the contract balance and user data, including the address and balance of the user. The smart contract allows users to deposit fun ...