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

Accessing composable variables in Vue 3 without having to redefine refs from within a function

Currently, I am implementing a parent companyList component along with a reusable Table component and an useFetch composable in vue 3.2. Prior to integrating the Table component, my code looked like this: companyList <script setup> import { com ...

What is the best way for me to locate and access the initial element that has been assigned the

How do I reference the first element with the "myabilities" class in the code snippet below? <div class="span6"> <h3 class="srvc-title">Responsive Design</h3> <p class="srvc-detail">Crafting great experie ...

Ajax calls for validations are failing to trigger a response from PHP

I am currently working on validating my signup form using PHP and AJAX, but unfortunately, I am not receiving any response value. Below is the AJAX code snippet I am using: <script type="text/JavaScript"> function frmValidation(str) { ...

Refresh Django table data without the need to reload the entire page

In order to retrieve data in my view, I use the following code: order = Order.objects.filter(owner=request.user).order_by('-id')[:10] The template code below works perfectly fine. However, I am looking to dynamically update this table every 10 ...

Having trouble submitting a form in React JS

I'm facing an issue with my form where I am trying to print the data in console upon submission, but for some reason it's not working. The form is not submitting and I can't figure out why. Below is the code I have written. Any help would be ...

Encountering HTML content error when attempting to log in with REST API through Express on Postman

I'm currently in the process of developing a basic login API using Node.js and Express. However, I've encountered an error when testing with Postman: <!DOCTYPE html> <html lang="en"> <head> <meta charse ...

Cache AJAX submission on IE8

In my current project, I have implemented a function for uploading and displaying images. The main purpose of this function is to avoid reloading the entire page when uploading and previewing images using AJAX. After uploading an image, it is displayed in ...

Issue: $injector:unpr Unrecognized Provider: itemslistProvider <-

I've spent several days debugging the code, but I can't seem to find a solution. I've gone through the AngularJS documentation and numerous Stack Overflow questions related to the error, yet I'm still unable to identify what's caus ...

Unusual CSS anomalies encountered on iPhone devices

Having an issue with the animation on my homepage where the logo spins into place. It works fine on desktop and in Chrome and Firefox mobile simulators, but on actual phones it rotates an additional 90 degrees. Included are screenshots from the Firefox mob ...

Executing a function enclosed in parenthesis does not yield any output

My code is supposed to print the sender's name followed by "adopted" and then the first mentioned user. const { Client } = require('discord.js', 'async', 'discord-message-handler'); const bot = new Client(); const cfg = ...

Avoiding Backbone Routing Conflicts when Implementing CSS3 Targeting

I have implemented a CSS target to create some basic animation in my Backbone project. However, I am facing an issue where the method I am currently using adds a #banner to the URL, which Backbone tries to interpret as a route if users refresh the page aft ...

Trigger jQuery event when the value of a select element changes, with the exception

On my page, there are numerous select buttons. I am seeking a way to trigger a jQuery function whenever any select button changes, except for the one with id="Select1". While I understand that I can directly link the function to each desired select button, ...

Customizing Your WordPress Menu with HTML5 Features

Can someone assist me in creating a customized WordPress menu? I am facing issues with unnecessary classes added by WordPress and the lack of certain attributes on dropdowns. Below is the HTML code: <nav class="navbar navbar-default navbar-static- ...

Ensure that the table is padded while keeping the cells collapsed

I am currently working on creating a table with borders between each row. However, I am facing an issue where the row borders are touching the outer border of the table. Despite my efforts, I have been unable to find a solution to this problem. I feel like ...

After incorporating an additional element, the li:nth-child(odd) selector is no longer functioning correctly

I previously had a setup where items in a list would have alternate colors using jQuery: $('ul.follows li:nth-child(odd)').addClass('alternate'); Everything was functioning properly until I introduced an a tag before the list items. N ...

Issue arose following implementation of the function that waits for the event to conclude

I've encountered a problem with my HTML and jQuery Ajax code. Here's what I have: <form> <input name="name_field" type="text"> <button type="submit">Save</button> </form> $(document).on("submit", "form", fu ...

When using PHP, JavaScript, and HTML, you can trigger an image upload immediately after choosing a file using the

I currently have a small form with two buttons - one for browsing and another for uploading an image. I feel that having two separate buttons for this purpose is unnecessary. Is there a way to combine the browse and upload functions into just one button? ...

The timing of the JavaScript dialog with the AJAX call is off-kilter

Encountering an issue with a JavaScript script designed to showcase a JQUERY dialog box based on a C# ViewModel. Within a repeater, there is an ASP drop-down menu displaying 'Registration Date' details. The objective is for the JavaScript dialog ...

A step-by-step guide to displaying an image preview when hovering over a cell in a

How can I display an image when hovering over a <td> in a datatable after clicking a button to fill the table with data? Here is my code: <script> if($.fn.dataTable.isDataTable( '#example' )){ var table = $('#example'). ...

Having trouble setting the InnerHTML property of Null on my Ionic app, what could be the issue?

I'm working on a code to display the remaining time for generating a random code in the DOM. var count = setInterval(function () { var date = new Date(); var currentSecond = date.getSeconds(); ...