Tips for inserting a button under a div when clicked

I am working on a layout where I have several div cards aligned side by side using the display: inline-block property. What I want to achieve is that when I click on a card, a button is added below the respective div.

To accomplish this, I tried using jquery's after() function, but the issue is that it adds the button to the right of the div instead of below it.

Can anyone guide me on how to achieve this desired effect?

PS: I experimented with the append function as well, but there seems to be a conflict with another function that removes the button when clicking on the div again. This creates an issue where clicking on the button (now part of the div) triggers the removal process, disrupting the functionality.

Thank you in advance for any assistance!

Edit...

A big thank you for all the responses provided so far...

My apologies for not presenting the code initially, here is the snippet:

<div class = "classOfDiv">
    Placeholder for product details
</div>

$('.classOfDiv').click(
    function() {
        var border = $(this).css("border");
        
        if (border == "0px none rgb(51, 51, 51)") { 
            $(this).css("border", "3px solid blue");
            $(this).after("<button name='btnDetalhes' class='btn btn-primary'>Detalhes</button>");
        } else {
            $(this).css("border", "0px none rgb(51, 51, 51)");
            $(this).next("[name='btnDetalhes']").remove();
        }
    }
);

Answer №1

If you're still searching for a solution, here's a basic idea on how to implement the show/hide functionality I mentioned earlier.

You'll have to decide what action will hide the button div. If clicking on the card again is the desired behavior, simply change show() to toggle

.card {
  display: inline-block;
  position: relative;
  width: 100px;
  height: 100px;
  border: 1px solid black;
  margin: 5px;
  text-align: center;
  cursor: pointer;
}

.card-button {
  display: none;
  position: absolute;
  bottom: -22px;
  left: -1px;
  width: 100%;
  height: 20px;
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="card" onclick="$('.card-button').show()">
    <p>Card Content</p>
    <div class="card-button" onclick="alert('button clicked!')">
      <span>BUTTON</span>
    </div>
  </li>
</ul>

To prevent the click event on the button from triggering its parent's events, another approach could be using event.stopPropogation() in your event handler as mentioned during our discussion.

Answer №2

$(document).ready(function() {
    
    
    $(".card").click(function () { 
    $(this).append('<a class="button" href="#">Button</a>');
});
    
  
});
.card{
  display:inline-block;
  position:relative;
  width:200px;
  height:100px;
  margin-bottom:40px;
  background-color:yellow;
}

.button{
  position: absolute;
  bottom: -30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>

<div class="card">a</div>
<div class="card">b</div>
<div class="card">c</div>
<div class="card">d</div>
<div class="card">e</div>
<div class="card">f</div>
<div class="card">g</div>

Answer №3

In the past, I have created spoiler BBCodes specifically for online forums. The basic idea behind them remains consistent; if you change things up a bit, you'll end up with:

<span>
<div onclick="var s=this.parentNode.querySelector('button');s.style.display=s.style.display==''?'none':''">
<!-- add your content here -->
</div>
<button type="button" style="display:none"><!-- include additional content here --></button>
</span>

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

Position the vertical bar directly adjacent to the form input field

Looking for assistance with creating a unique webpage layout that includes a form where the employee ID is visually separated from the rest of the content by a vertical bar extending across the entire page. However, my attempts to achieve this using a gr ...

How come the subitems of a second-level nested list do not appear when hovering over a hyperlink?

Show "News" in French when hovering over the French option. ul#topmenu li a#HyperLink:hover ul { background-color: pink; display: list-item; } <ul id="topmenu"> <li class="langHorzMenu"> <a href="#" id="HyperLink">French</ ...

Utilizing JavaScript to assign object properties (column names) from an Array of Objects to a specific row and column header

I am currently in the process of implementing a mapping function to display data from an array of objects, initially stored in localStorage, into a table using Material-UI Table. The goal is to map all the specific column names into corresponding Table Ce ...

Show off markdown formatting without the need for v-html

I run a unique type of platform that allows users to publish their own blog posts using a WYSIWYG editor, and then share them on the site. My top priority is to ensure security against XSS attacks, which is why I am looking for alternatives to using v-htm ...

Display or conceal a div depending on whether the user is on a mobile or desktop browser

In order to optimize the display on different devices, I organized my content into two divisions. The left division contains quantity, price, and item name, while the right division includes product names. For mobile browsers, I would like to hide the pro ...

What is the best way to extend an image to fill the width of a webpage?

Can you advise me on how to expand the image to fit the width of my webpage? If possible, could you take a look at this website: Poklanjam The specific image I am referring to is the one of the city on the left-hand side. What additional CSS code should ...

Quick method for handling arrays to generate waveforms

I'm currently working on optimizing the code for my web application. While it functions, the performance is a bit slow and I am looking to make improvements: The main concepts behind the code are: The function retrieves the current buffer and conve ...

Striking a line through the hyperlink tag

I am attempting to create a crossed-out line above the content of an a tag for decorative purposes. The line should stretch across the entire width without intersecting with the actual text within the tag. This is my desired outcome: This is my current p ...

I need some help with adjusting the number of rows shown per page in MaterialReactTable

I've been utilizing MaterialReactTable and my goal is to display only 5 items on each pagination page. Despite setting muiTablePaginationProps, I still see 10 items per page. How can I resolve this issue? <MaterialReactTable columns={columns} ...

Content escapes its parent container and seamlessly transitions to the following element

I am facing an issue with the layout of my element, which includes an image and text centered inside a parent container. Whenever I try adding more elements below the existing image and text, the green text with a red border overflows the current parent . ...

In Vue, it is not accurate to measure overflow

I am working on creating an overflow effect with tagging that fades out at the beginning to provide a subtle hint to users that there is more content. Here is what it currently looks like: https://i.stack.imgur.com/fXGBR.png To achieve this, I added a fa ...

Unique rephrased text: "Varied wrapping styles in both

Feeling frustrated with a seemingly commonplace issue. Despite the thousands of times it has been asked before, I can't seem to find an answer on Google. I wanted to neatly display my text within one of my cards, but so far I've only achieved th ...

As you hover over the chosen image, the selected image will appear

I have a simple HTML code with some JavaScript where I display sets of images. All I want is for the images to pop up when hovered over, appearing in a larger size. Below is the example HTML Code: <div class="content-box-left-bootomgrid lastgrid"> ...

Converting text into HTML format using Nextjs and React

Currently, I am working on a project that involves using Next.js and React. I am considering creating my own component to parse text based on certain conditions, but I am unsure if something similar already exists. My goal is to: Format the content in HT ...

Struggling to dynamically update array values by comparing two arrays

I am faced with a scenario where I have two arrays within an Angular framework. One of the arrays is a regular array named A, containing values such as ['Stock_Number', 'Model', 'Type', 'Bill_Number'] The other arr ...

Occasionally, the system may mistakenly flag a password as invalid even though it is indeed correct

To ensure the password meets certain criteria, it must start with a Z, have at least 8 characters, and contain an asterisk *. Take a look at this validating function: function validatePassword() { var strPassword; //Prompt user to enter pas ...

Add a trash can or delete icon within every row of a table using Vue.js

I am new to vue.js and I'm struggling to implement a trash icon in each row of a table for deleting rows. Additionally, I'm trying to make the input of a cell act as a dropdown menu or list within the table rows. I recently came across this scrip ...

Display or conceal HTML content based on the input's property type

Looking to toggle the visibility of an icon on my input based on the prop type. If the type is set to password, the icon will be displayed for toggling between visible and hidden password; if the type is not password, the icon should be hidden by setting ...

Import a JSON file into Parse by reading and parsing it to store in the database

I am currently facing a challenge with parsing JSON data in my Parse Cloud function. After fetching the JSON file, I need to parse the data and populate one of my classes with the results. However, I'm having trouble figuring out how to properly parse ...

Adding a PDF generated from an HTML div to an email using Java

I am looking for a solution to convert the contents of an HTML div tag into a PDF file while preserving its associated CSS. This is essential as I will be using Java on the back-end to send emails, and I need to attach the PDF with the CSS intact when send ...