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

What methods can be used to limit URL abbreviations on my website?

I need a simple solution that I have been struggling to figure out. What I want is for anyone attempting to access any webpage directly on my website to be automatically redirected to the home page. For instance, if someone tries to access www.domain-name ...

When attempting to pass data to another page by clicking on a row, the result is that the data appears to be empty

I have been using the MUI-Datatable component, which is able to navigate to the next page. However, when I try to view the data on the History page, nothing appears. How can I resolve this issue? Data transfer to another page: Even though I can see the d ...

Discover the Magic Trick: Automatically Dismissing Alerts with Twitter Bootstrap

I'm currently utilizing the amazing Twitter Bootstrap CSS framework for my project. When it comes to displaying messages to users, I am using the alerts JavaScript JS and CSS. For those curious, you can find more information about it here: http://get ...

What is the process for defining an outcome when a draggable element is placed into a droppable area using Jquery?

Currently, I am working on a task where I need to increase the value of a counter (var counter = 0;) every time a draggable image is dropped into a dropzone, which is also an image rather than a div. $( "#goldbag" ).draggable({ revert: "invalid", containm ...

Is the concept of LinkedList index applicable in the field of Data Structures and Algorithms (DSA)?

Is there an index feature in LinkedList that allows for accessing elements like in arrays? If so, can you explain how the indexing works within the LinkedList concept? Thank you I am new to LinkedList and would like to grasp the fundamental concept behin ...

Is it possible to refresh resources in Node.js without the need to restart the server?

Is there a middleware or library that allows access to files added after the server starts without requiring a restart? I currently use koa-static-folder, but it seems unable to handle this functionality. ...

What steps should I take to resolve the issue of my endpoint failing to accept POST requests?

I am in the process of developing a customized API, with an endpoint that is specified as shown below: https://i.stack.imgur.com/sZTI8.png To handle the functionality for this endpoint, I have set up a Profiling Controller. Inside my controller directory ...

Is it possible to schedule a periodic GET request on the server-side without utilizing the client-side or frontend?

I am currently implementing a GET request to retrieve data from a third-party API. I want to regularly check for new data every 5-10 minutes on my backend. exports.get_alerts = async (req, res) => { const alertsUrl = `https://www.g2smart.com/g2smart/a ...

What is the best way to divide multiple event handlers in jQuery?

Is there a way to organize the code below more effectively by splitting the multiple events into separate lines? $document.find('body').on( 'click dblclick mousedown mousemove mouseout mouseover mouseup mousewheel keydown keypress keyup ...

Algorithm for Filling Tiles in a Gaming Environment

Background: In my current project, I'm developing a unique tile-based game in Javascript. The game involves a character who can freely move around the map without taking diagonal paths - only left, right, up, or down movements are allowed. As the cha ...

The lightbox feature on the page is not functioning properly

On my website, I have a beautiful lightbox created using fancybox.net. You can check it out here: I also use gallery codes to display images in a gallery format. Below is the jQuery code I am using: $(document).ready(function() { $(".gallery").fancy ...

How can I retrieve the value from req.body following an AJAX POST request on the server side with Express?

Currently, I am utilizing AJAX to send JSON data: app.use(express.json()); app.use(bodyParser.urlencoded({extended:true})) app.use(express.urlencoded({ extended: true})); const rowObject=JSON.stringify(rowData) $.ajax({ type: "POST&q ...

Validating the presence of a value and displaying an error message prior to submitting the form using jQuery

Is there anyone who can assist with verifying the existence of values? I am in need of a way to validate that the fields for name, telephone number, email address, and enquiry contain values before submitting the form upon clicking the button. If any fiel ...

Angular2 - Error: The view has been destroyed and cannot be updated: detectChanges

My application keeps encountering this persistent error: extensions::uncaught_exception_handler:8 Error in event handler for runtime.onMessage: Attempt to use a destroyed view: detectChanges at ViewDestroyedException.BaseException [as constructor] (chrome ...

Problem with logging in using ajax

I'm attempting to implement an on-page login feature. It functions perfectly without the use of ajax. Below is my login.php code; if($_POST) { $username =$_POST["username"]; $password =$_POST["password"]; $query = $handler->query("SE ...

Error message reading "Unexpected type error in jQuery for Node. Argument 'context' required."

Currently facing an issue with deploying my node.js server online. While everything functions properly on my local machine, I encountered an error when attempting to run the server online using node: node.js:201 throw e; // process.nextTick error, ...

In search of an improved scoring system for matching text with JavaScript

For many of my projects, I've relied on String Score to assist with sorting various lists such as names and countries. Currently, I am tackling a project where I need to match a term within a larger body of text, like an entire paragraph. Consider t ...

Can the ThreeJS element be seen?

I am facing a challenge in my ThreeJS application where the view automatically centers on an object if it is close to the center of the view and closer than a specified distance. While I have information about the latitude and longitude of all objects and ...

Animate internal navigation buttons to fade in with the use of jQuery

I have a webpage with a gallery of images displayed in an unordered list format. My goal is to create a hover effect where up and down arrows fade in when I hover over an image, allowing the user to click on the arrows to navigate between photos. The curr ...

The boundary extends fully to the right

Recently, I created a calculator to convert kilograms to pounds and encountered an issue when trying to add a border to a p element. The problem was that the border extended all the way to the right side of the page. Here is the corresponding HTML code: &l ...