What is the best way to create divs that can close and hide themselves when clicked from inside the div itself?

I have a situation in my code where clicking a link reveals a div, and then the same link must be clicked again to hide it. However, I want to modify this so that any link within the div can also hide it when clicked. I currently have eight divs set up like this. How can I achieve this functionality? Below is the code I am working with.

Despite some syntax error messages present, the code functions correctly. Please disregard these errors as they are unrelated to the question at hand.

Appreciate your assistance!

Answer №1

Is your issue addressed in this solution?

Here's a snippet of the code provided:

$('.toggle').click(function () {
    var targetId = $(this).data('target');
    $('#' + targetId).toggle();
});

$('.close').click(function () {
    $(this).parent().hide();
});

Answer №2

Assign a specific class to each <div> element to indicate they should be grouped together (with only one open at a time). Then, when a link is clicked, hide all elements with that class before revealing the content of the clicked link.
To enhance this functionality by adding a toggle feature, first determine the toggle status before hiding all elements. This way, you can maintain the previous state (open or closed) if it was already open.

Answer №3

After putting in the effort, I have successfully completed the bins on codebins. Make sure to take a look at the demo link provided.

Demo:

HTML

<div id="links">
  <a class="openlink" href="javascript:void(0);">
    Open
  </a>
  <a class="openlink" href="javascript:void(0);">
    Open
  </a>
  <a class="openlink" href="javascript:void(0);">
    Open
  </a>
  <a class="openlink" href="javascript:void(0);">
    Open
  </a>
  <a class="openlink" href="javascript:void(0);">
    Open
  </a>
  <a class="openlink" href="javascript:void(0);">
    Open
  </a>
  <a class="openlink" href="javascript:void(0);">
    Open
  </a>
  <a class="openlink" href="javascript:void(0);">
    Open
  </a>
</div>
<div id="boxes">
  <div class="box">
    <p>
      Dig into this content..!! 
    </p>
    <p>
      <a class="closelink" href="javascript:void(0);">
        Close
      </a>
    </p>
  </div>
</div>

jQuery

$(function() {
    var boxClone;

    $(".openlink").click(function() {
        //Duplicate Dialog Box
        boxClone = $("#boxes").find(".box:eq(0)").clone(true, true);
        var boxOffset = $("#boxes").find(".box:last").position();
        //Establish Dialog Position
        if (boxOffset.top == 0) {
            boxOffset.top = 5;
        }
        if (boxOffset.left == 0) {
            boxOffset.left = 60;
        }
        $(boxClone).css('top', (boxOffset.top + 20));
        $(boxClone).css('left', (boxOffset.left + 20));
        $(boxClone).appendTo($("#boxes"));
        $(boxClone).show(500);
    });

    //End Dialog Box
    $(".closelink").click(function() {
        $(this).closest(".box").remove();
    });

});

CSS

#links{
  float:left;
  width:50px;
  border:1px solid #92a3a7;
  padding:1px;
  background:#88ddfa;
}
#links a{
  dispslay:block;
  text-decoration:none;
  color:#3543ff;
}
#links a:hover{
  text-decoration:underline;
  color:#fd2211;
}
#boxes{
  float:left;
  margin-left:10px;
}
#boxes p{
  text-align:center;
  display:block;
  color:#ccc;
}
#boxes a.closelink{
  text-decoration:none;
  color:#ff2211;
  background:#99cd9a;
  width:40px;
  text-align:center;
  padding:3px;
  font-size:14px;
}
#boxes a.closelink:hover{
  text-decoration:underline;
  background:#a5d9a3;
  color:#2222ff;
}

.box{
  position:absolute;
  width:200px;
  height:200px;
  vertical-align:top;
  border:10px solid #888;
  background:url('http://www.lovehatecreate.net/iqhomes/jquery-show-hide-plugin-2/popupbg.png') #333;
  display:none;

}

Demo:

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 issue with Open Sans and sans-serif fonts not rendering properly in all web browsers

I am having trouble with websites that use the Open Sans font appearing with a strange handwriting style. I'm not sure where this issue is originating from. Here are some things I have tried: Using In-Private browsing Disabling all extensions Testin ...

What methods can be employed to prevent a custom CSS from overriding my personal styles?

Issue I've created a website with unique styles that I really like. However, I want to enhance its functionality by incorporating a custom dialog box from the BootBox library. The problem is that the extensive style sheet that comes with BootBox com ...

How to print a file with the .aspx extension in an Asp.net

While attempting to print the contents of an HTML DIV using the provided code, everything worked smoothly. However, upon integrating an Ajax Control into an Aspx page, an error message surfaced: "Extender control 'CalendarExtender2' is not a r ...

What is the best way to calculate the total of all the prices listed in the span class="total"?

On my webpage, I have two sections - one for processors and the other for RAM. To retrieve prices from the database through AJAX, how can I total up all the prices listed within the span elements with the "total" class? <td> <span class="m ...

Extracting text within quotation marks from HTML using Java and Selenium WebDriver

I encountered a piece of code that resembles the following: https://i.stack.imgur.com/gaX1J.png Although I am able to retrieve the link using the command System.out.print(link.getText()); it only returns the value "Saab". However, I also require the da ...

What is the best way to coordinate text and photos within Bootstrap?

Currently, I am working on a bootstrap website that features a slideshow with 3 photos. The jQuery function responsible for this is as follows: $(function () { $.vegas('slideshow', { backgrounds: [{ src: 'img/ph1.jpg ...

What is the process of reading an excel file in angularjs?

I attempted to read an Excel file by following a tutorial I found at . Unfortunately, I encountered an undefined situation in the highlighted line below while trying to do so in IE11. var reader = new FileReader(); reader.onload = function( ...

Autocomplete suggestions tailored to specific categories in real-time

Having trouble creating an autocomplete feature with dynamic values based on a combobox using CodeIgniter. I've attempted using AJAX without success. Below is my AJAX code for calling items in a category: <script type="text/javascript"> $(docu ...

What is the best way to correctly showcase dynamic pages in ExpressJS?

Within my app.js file, there exists an array of objects that is defined as follows: var people = [ {name: "Henrique Melo", username: "heenrique", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7a121f1408130b0f1 ...

Basic Tallying Code in JavaScript

Hi, I am currently working on creating a basic counter using HTML / CSS and Javascript. Unfortunately, my Javascript code is not functioning correctly, even after trying various solutions found online. I attempted to include "async" but it appears that my ...

Discover automatically generated titles for dynamic hyperlinks

I am looking to generate dynamic links for a collection of documents with varying names, such as Test, Test2, and so on. I want the link text to display as "Document TestN," where N is the specific document number. Currently, I am able to create the links ...

Angular2 - HTML not displaying the response

I am currently mastering angularjs2. In my latest project, I attempted to fetch data from an API and received a response successfully. However, I encountered an issue where the response is not rendering in homepage.component.html as expected. I am unsure o ...

What is the best way to update the color of an fa icon when an error message is displayed using PHP

I am facing an issue with my form where error messages are displayed on certain input fields. The error messages show up correctly, but I want to change the color of the "fa" icon in the field when its corresponding error message appears. My goal is to ma ...

When calling canvas.getContext('2D'), the function returns a null value

After creating a canvas and calling its getContext() method, I was confused when it returned null for the context. Below is the code snippet that I used: <script> window.onload = initializeCanvas; function initializeCanvas(){ ...

The functionality of ngModel is not functioning properly on a modal page within Ionic version 6

Currently I am working on an Ionic/Angular application and I have encountered a situation where I am attempting to utilize ngModel. Essentially, I am trying to implement the following functionality within my app: <ion-list> <ion-item> <ion ...

What might be causing my animation to not run as expected?

I recently tried to create a bouncing arrow following a tutorial, but the code I used is almost identical with minor differences. However, when I try to incorporate it into my hero unit, the animation does not work as expected. The issue could be related ...

I'm facing a challenge with displaying data on a dynamically created table using VueJS

I'm having an issue with dynamically generating a table using VueJS. The problem arises when creating the <th> elements. In order to set them up, I have a Vue component that is called by the addRow function. This component uses templates with v ...

Is it possible to use AngularJS promises without callbacks?

Typically, when I want to retrieve data asynchronously, I would use the following approach: var promise = $http.get('/api/v1/movies/avengers'); promise.then( function(payload) { $scope.movieContent = payload; }); This scenario is quite ...

What could be causing the malfunction of the Facebook iframe like button?

Even though it functions offline, there seems to be an issue with its performance online. Here is the code that was used: <iframe src="http://www.facebook.com/plugins/like.php?app_id=125925834166578&amp;href=http%3A%2F%2Fwww.facebook.com%2FBaradei. ...

Confirm if the username is present in jQuery PHP

I am currently working on a functionality to verify if a username is already registered in my application using jQuery, Ajax, and POST method. HTML <div class="form-group"> <label for="username" class="col-md-3 control-label">Username< ...