Using JQuery, you can toggle a newly created DIV element by linking it to `$(this)` instead of `$(this).closest()`

In the comment section, there is a link called "Reply" that triggers a pop-up comment box when clicked. However, I want the comment box to disappear if the "reply" button is clicked again, as it currently keeps opening more comment boxes.

$('.replylink').click(function(event){ // Create comment box after clicking reply
event.stopPropagation();
var commentBox = $('<div class="comment-box"></div>');
$(this).closest('div').after(commentBox);
});

I have tried using toggle() in various ways. For instance,

$($(this).closest('div').after(commentBox)).toggle();

But this will only toggle the "reply" link, causing it to disappear while the comment box appears. I am unsure of how to toggle just the comment box. Is there anyone who can assist me with this issue? Thank you!

Answer №1

If there is no existing .comment-box, the code below will create one and if it does exist, it will be deleted for individual threads.

I have enhanced your .closest() function by adding a class. This makes it more specific, as searching just for a div is too broad. By adding a class, you can add multiple divs and wrappers between your reply link and the wrapper. It may not be necessary at present, but it adds future-proofing to your code.

The commented code below is designed to work for both single comment areas and multiple threads or comment sections on a single page.

I made a minor change by appending the comment box to .before() the reply link instead of using .after(). This change enhances the user interface from a stylistic perspective.


Demo

// Create comment box after clicking reply
$('.replylink').click(function(event) {

  // Prevent default action for click (i.e., going to top of page)
  event.preventDefault();

  // Set wrapping thread div
  // this allows for multiple threads on the same page if needed
  thread = $(this).closest("div.thread");

  // Check if thread has an opened comment box
  if (thread.find(".comment-box").length > 0) {

    // Delete any comment boxes within this comment thread
    thread.find(".comment-box").remove();


  } else {

    // Uncomment the line below if you want to close all other comment boxes
    // $(".comment-box").remove();

    // Create a coment box if it doesn't exist
    var commentBox = $('<div class="comment-box"></div>');
    $(this).before(commentBox);

  }

});
.comment-box {
  height: 20px;
  padding: 10px;
  border: 1px solid blue;
  margin-bottom: 10px;
}

.thread {
  border: 1px black solid;
  padding: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="thread">
  <h3>Thread One</h3>
  <a href="#" class="replylink">Reply</a>
</div>

<div class="thread">
  <h3>Thread Two</h3>
  <a href="#" class="replylink">Reply</a>
</div>

<div class="thread">
  <h3>Thread Three</h3>
  <a href="#" class="replylink">Reply</a>
</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

Could it be that express-session is not compatible with express 4.13?

I have followed the setup instructions for express-session as outlined in the documentation, but it seems that my cookie is not being created. According to the documentation, simply setting the request.session value should automatically set the cookie. How ...

Is it feasible to generate a fixed lighting effect overlay with HTML and CSS?

Is it possible to incorporate a static lighting effect overlay using HTML/CSS? My project consists of an HTML5/JS app with a top navigation bar and a series of cards that are transitioned through using swipe gestures. These cards are displayed in gray ove ...

Trigger modal following unsuccessful registration

I have a method in the controller for registering users. [HttpPost] public ActionResult Register(RegisterViewModel register) { if (this.IsCaptchaValid("Captcha is not valid")) { if (ModelState.IsValid) { ...

JavaScript code for sending information to the server

I am attempting to write data to a file on the server when a user clicks on a button, using JavaScript. I followed the method outlined in this Stack Overflow post: Saving a text file on server using JavaScript. Unfortunately, it did not work as expected. ...

PHP mistakenly outputs content that is not enclosed within tags

After discovering StackOverflow, I couldn't resist sharing my PHP code conundrum with the incredible community here! So, in a WordPress template, I have this chunk of PHP: echo '<div class="thumbnail">'; echo the_post_thumbnail(); ec ...

The Aurelia application encounters a "Maximum call stack size exceeded" error while trying to bind FullCalendar

I am currently working on setting up a JQuery plugin (FullCalendar) within my Aurelia application, which is built using TypeScript. I am relatively new to web development and just trying to get a basic example up and running. To start off, I utilized this ...

Retrieve the route.js directory using Node.js

My server.js file is located in the directory: /dir1. To start the server, I use the command node server.js. In the directory /dir1/app/, I have my file named routes.js. I am trying to find out the directory path of the server.js file. However, I am unc ...

Is there a way to seamlessly inject a stylesheet into a React application without causing any flickering or reloading on the website?

In my React application built with next.js, I am fetching a stylesheet via a GET request and appending it to the webpage. However, whenever this stylesheet is loaded in, the elements impacted by it re-render unnecessarily, even if there are no actual chang ...

A single Modal, Ajax, and data that is continuously refreshed

I'm currently facing a challenge in my project as I try to implement Ajax functionality. Although I'm relatively new to using it, I believe I have a basic understanding of its workings. My website involves collecting form data, posting it to a d ...

Steps to transfer the content of a label when the onclick event occurs

Seeking advice on how to send the dynamically varying value of a label upon clicking an anchor tag. Can anyone recommend the best approach to passing the label value to a JavaScript function when the anchor is clicked? Here is a sample code snippet: < ...

How can I configure my React Project to direct users to example.com/login.html when they land on the root URL?

My goal is to verify a user's identity through a third-party authentication server. The redirect_uri indicates that after the user logs in, they will be redirected to example.com/login.html. Inside the login.html file, there will be specific html/scr ...

Combining Option Value and Name Selection Using React Hooks

Currently, I am facing a situation where I need to retrieve two different values (item.id and item.name) to set the State when selecting an item from my dropdown menu. Right now, I am only able to do this for one value (item.id). Is it possible to achieve ...

Navigating the Angular Controller life cycle

I have set up my application states using ui-router: $stateProvider .state('app', { abstract: true, views: { 'nav@': { templateUrl: 'app/navbar.html', controller: 'NavbarController' ...

Using regular expressions to replace strings in JavaScript

I have a URL that resembles the following http://localhost:12472/auctions/auction-12/lots/sort/something/12 I am looking to switch it out with this new URL http://localhost:12472/auctions/auction-12/lots/sort/somethingelse/12 Here, somethingelse can be ...

Inserting a Specific Iframe into a Designated Location in HTML with the Help of Jquery

Currently, I am encountering an issue with placing a dynamically created iframe inside a specific section of my webpage. The iframe is supposed to be contained within a div element named "maps", but instead it is appearing at the bottom of the page.This ma ...

Placing a new item following the child of a different element

How can I use jQuery to add a div inside id123 after sth2, but only for one specific occurrence? I understand how to do it after every sth2, but not just once. <div class="id123"> <div class="a"></div> .. <div class="sth1">< ...

Route Handler 13 is encountering difficulties in retrieving data from the body in the (app/api/auth) endpoint

Whenever I attempt to retrieve the body from the new export async function POST( req: Request), it seems to come through as a stream instead of the expected content type. The route handler can be found in api/auth/signup See folder layout image export asyn ...

Discovering the method for retrieving JavaScript output in Selenium

Whenever I need to run JavaScript code, the following script has been proven to work effectively: from selenium import webdriver driver=webdriver.Firefox() driver.get("https:example.com") driver.execute_script('isLogin()') However, when I atte ...

Passing references in React to parent components

Struggling to adopt the react way of thinking, I'm facing an issue with invoking the .submit() method of the form component. Within a material-ui Dialog, buttons are passed via the actions property. Now, I need to trigger the .submit() method of the ...

Tips on showing binary information as images using extjs 4

As the proud owner of a valid .JPEG image's binary data, I am on a quest to convert this information into an actual viewable image using Python. Seeking advice on how to successfully transform this binary code into a visually appealing .JPEG format w ...