Placing a JavaScript button directly below the content it interacts with

I am currently working on a button that expands a div and displays content upon clicking. I am facing an issue where I want the button to always be positioned at the bottom of the div, instead of at the top as it is now, but moving it within the parent div affects the event functionality.

 $('button, .smallx').click(function(){
  let box = $(this).closest('.container').find('.content');
  if ( box.hasClass('collapsed') ){
    box.removeClass('collapsed');
  }else{
    box.addClass('collapsed');
  }
});
.collapsible {
  border: none;
    width: 60px;
}

.container{max-width:800px;margin-bottom:20px;overflow:hidden;}
.collapsed{max-height:65px;max-width:200px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

<div class="container">
  <div class="content collapsed">
     <button class="collapsible">More</button>
    <div>Mauris dui mi, faucibus a elit id, bibendum euismod elit. Aenean pharetra laoreet quam in laoreet. Etiam interdum ligula ac gravida laoreet. Sed tempor lacus mauris, ac feugiat felis viverra eget. Donec dignissim, lacus nec congue interdum, nisl arcu pharetra sapien, id porttitor arcu odio non lectus. Aliquam pulvinar urna quis pretium facilisis. Ut elementum rutrum quam. In tincidunt dui non felis convallis, quis dictum ligula dictum. Vestibulum enim lorem, auctor a iaculis at, mattis ut leo. Sed volutpat venenatis finibus. Cras sapien mauris, ultricies vel facilisis in, pharetra sit amet lacus. Curabitur quis faucibus nibh, vestibulum rhoncus magna. Pellentesque faucibus magna sed molestie aliquam. Nullam convallis auctor diam, et rhoncus erat faucibus sit amet. Nulla quis pulvinar augue.
  </div> </div></div>

Answer №1

Insert the button after collapsing the content within the div and apply overflow:hidden; to the div text instead of the container

$('button, .smallx').click(function(){
  let box = $(this).closest('.container').find('.content');
  if ( box.hasClass('collapsed') ){
    box.removeClass('collapsed');
  }else{
    box.addClass('collapsed');
  }
});
.collapsible {
  border: none;
    width: 60px;
}

.container{max-width:800px;margin-bottom:20px;}
.collapsed{max-height:65px;max-width:200px;overflow:hidden;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

<div class="container">
  <div class="content collapsed">
     
    <div>Mauris dui mi, faucibus a elit id, bibendum euismod elit. Aenean pharetra laoreet quam in laoreet. Etiam interdum ligula ac gravida laoreet. Sed tempor lacus mauris, ac feugiat felis viverra eget. Donec dignissim, lacus nec congue interdum, nisl arcu pharetra sapien, id porttitor arcu odio non lectus. Aliquam pulvinar urna quis pretium facilisis. Ut elementum rutrum quam. In tincidunt dui non felis convallis, quis dictum ligula dictum. Vestibulum enim lorem, auctor a iaculis at, mattis ut leo. Sed volutpat venenatis finibus. Cras sapien mauris, ultricies vel facilisis in, pharetra sit amet lacus. Curabitur quis faucibus nibh, vestibulum rhoncus magna. Pellentesque faucibus magna sed molestie aliquam. Nullam convallis auctor diam, et rhoncus erat faucibus sit amet. Nulla quis pulvinar augue.
  </div> </div><button class="collapsible">More</button></div>

Answer №2

Using CSS

$('button, .smallx').click(function(){
  let box = $(this).closest('.container').find('.content');
  if ( box.hasClass('collapsed') ){
    box.removeClass('collapsed');
  }else{
    box.addClass('collapsed');
  }
});
.collapsible {
  border: none;
    width: 60px;
}
.content{
position:relative;
}
button{
position:absolute;
bottom:0px;
right:0px;
}

.container{max-width:800px;margin-bottom:20px;overflow:hidden;}
.collapsed{max-height:65px;max-width:200px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

<div class="container">
  <div class="content collapsed">
     <button class="collapsible">More</button>
    <div>Mauris dui mi, faucibus a elit id, bibendum euismod elit. Aenean pharetra laoreet quam in laoreet. Etiam interdum ligula ac gravida laoreet. Sed tempor lacus mauris, ac feugiat felis viverra eget. Donec dignissim, lacus nec congue interdum, nisl arcu pharetra sapien, id porttitor arcu odio non lectus. Aliquam pulvinar urna quis pretium facilisis. Ut elementum rutrum quam. In tincidunt dui non felis convallis, quis dictum ligula dictum. Vestibulum enim lorem, auctor a iaculis at, mattis ut leo. Sed volutpat venenatis finibus. Cras sapien mauris, ultricies vel facilisis in, pharetra sit amet lacus. Curabitur quis faucibus nibh, vestibulum rhoncus magna. Pellentesque faucibus magna sed molestie aliquam. Nullam convallis auctor diam, et rhoncus erat faucibus sit amet. Nulla quis pulvinar augue.
  </div> </div></div>

Is this the solution you're looking for?

Alternative HTML Block Approach

$('button, .smallx').click(function(){
  let box = $(this).closest('.container').find('.content');
  if ( box.hasClass('collapsed') ){
    box.removeClass('collapsed');
  }else{
    box.addClass('collapsed');
  }
});
.collapsible {
  border: none;
    width: 60px;
}
.content{
position:relative;
}
button{
}

.container div{max-width:800px;margin-bottom:20px;overflow:hidden;}
.collapsed div{max-height:65px;max-width:200px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

<div class="container">
  <div class="content collapsed">     
    <div>Mauris dui mi, faucibus a elit id, bibendum euismod elit. Aenean pharetra laoreet quam in laoreet. Etiam interdum ligula ac gravida laoreet. Sed tempor lacus mauris, ac feugiat felis viverra eget. Donec dignissim, lacus nec congue interdum, nisl arcu pharetra sapien, id porttitor arcu odio non lectus. Aliquam pulvinar urna quis pretium facilisis. Ut elementum rutrum quam. In tincidunt dui non felis convallis, quis dictum ligula dictum. Vestibulum enim lorem, auctor a iaculis at, mattis ut leo. Sed volutpat venenatis finibus. Cras sapien mauris, ultricies vel facilisis in, pharetra sit amet lacus. Curabitur quis faucibus nibh, vestibulum rhoncus magna. Pellentesque faucibus magna sed molestie aliquam. Nullam convallis auctor diam, et rhoncus erat faucibus sit amet. Nulla quis pulvinar augue.
  </div> </div><button class="collapsible">More</button></div>

Answer №3

You have the option to swap this

  if ( box.hasClass('collapsed') ){
    box.removeClass('collapsed');
  }else{
    box.addClass('collapsed');
  }

with

box.classList.toggle('collapsed')

Answer №4

To achieve the desired effect of having the button positioned right under the box or container that it will toggle the visibility for, you can utilize CSS. Here is an example:

<div class="container">
  <div class="content collapsed">
    <div class="text">Mauris dui mio</div>
    <button class="collapsible">More</button>
 </div>
</div>

In this structure, the button is placed under the content and a class is added to the div for further customization.

.content {
  display: flex;
  flex-direction: column;
  align-items: start;
}

.collapsible {
  border: none;
  width: 60px;
}

You can add additional styles as needed. Using JavaScript, you can implement a click function on the button to adjust the height of the .text div based on its current state. Alternatively, you can also use absolute positioning like so:

.content {
  position: relative;
}

.collapsible {
  position: absolute;
  left: 0;
  bottom: 100;
}

The value for bottom can be adjusted to suit your layout requirements (e.g., 100 or 0). Feel free to experiment with these settings to achieve the desired visual alignment between the button and the content box.

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

"Fixing the position of a div on the Samsung Galaxy S8 navigation bar to

Here is the HTML code I am working with: <div class="app-bar"> <a href="#'>icon</a> <a href="#'>icon</a> <a href="#'>icon</a> <a href="#'>icon</a> </div>' ...

Concealing items by placing them strategically between the camera and certain objects in Three.js

At the moment, my project involves utilizing three.js with several objects in the scene. One of the key features I am working on is the ability to select an object and have all other objects between the camera and the selected one hidden or removed. I am ...

Stop the unnecessary reloading of Ajax data when navigating back using the browser's back button in Chrome and Internet Explorer

I am currently designing a website where the main page showcases the latest 10 blog entries. As I scroll down and approach the end of the last item on the screen, another set of 10 blog entries automatically load through infinite scrolling. If a user clic ...

Multiple file uploads are causing the issue of req.file being undefined

After going through all the suggested solutions, I am still struggling to identify the root cause of my issue. The problem arises when trying to upload multiple files and form inputs - the req.file is always undefined and the image data ends up in the req. ...

`In the event that a series of criteria is unfulfilled in a JavaScript forEach() loop`

My IntersectionObserver utilizes a forEach method to invoke certain functions when a condition is met for each item in an array: const sections = document.querySelectorAll("section") function removeHighlight(id) { someElementArray[id].cl ...

"Implementing React to dynamically load and update value in component, enabling user interaction with the

As a newcomer to the world of React (16.4.2), I am trying to grasp its functionality without delving into Redux just yet; my focus is solely on understanding the core React library. In my application, there is an input component called RangeInput, which r ...

Tips for incorporating an anchor tag within an img tag in HTML?

Is it possible to add an anchor tag inside an img tag in HTML? <img src="img.jpg" alt="no img" /> I want to include the following inside the img tag: <a onclick="retake();" > Retake </a> The goal is to allow users to retake a photo by ...

Tips on personalizing the checkbox by incorporating a custom background image

Looking to spruce up the standard checkbox? We're open to any method - whether it's a background image, CSS3, or some jQuery magic. Check out this example for inspiration! ...

Encountering issues with styling the search bar using CSS and unable to see any changes reflected

I am currently working on creating a searchBar and customizing its CSS, but unfortunately, most of the styling properties seem to not be taking effect. So far, only changing colors seems to work as expected. .mainBar{ background-color: blue; width: ...

Angular.js: Applying a style to elements beyond the current scope based on the selected route

I'm looking to dynamically add classes outside of the current scope. Specifically, I need to add classes to the header, main, and footer elements as shown below: <header class="{{pageClass}}"></header> <main class="{{pageClass}}" ng-vi ...

Transferring data from an Excel spreadsheet into a structured table

I am interested in transferring specific columns of data from an excel sheet to an HTML table. My goal is to populate the table based on certain conditions rather than statically inputting fixed cells. For instance, if my excel sheet has columns for Name ...

$stateParams is not being properly defined when passed to the controller

I am currently utilizing ui-router to transfer an object to another state and controller by using $state.go() However, when I check the console.log for the $stateParams object, it appears as undefined. The object consists of x and y coordinates which ar ...

Currently working on enhancing the responsiveness of the login form

I am encountering difficulties while trying to make the page responsive. I've checked my basic code, but something seems off. Could you please take a look at the plnkr link below and give me some feedback on where I might have gone wrong? Here's ...

The CSS transition fails to function correctly once a specific function is executed

When I hover over a div, the background color changes due to a transition effect. However, if I click on a button that triggers myFunction2 to change the background color of the div before hovering over it, the transition effect no longer works. functi ...

What is the reason that jQuery does not work on HTML generated by JavaScript?

One of my JavaScript functions, named getImages, is responsible for loading the following HTML structure: // Function starts here function getImages() { $.getJSON(GETIMAGELIST, function(data) { var items = []; // Populating the HTML $.each(dat ...

What could be causing the erratic jumping behavior of the "newsletter sign-up" form within my modal dialog window?

On the homepage, there is a modal window that appears upon every pageload (it will be changed later), however, there seems to be an issue with the 'email sign up' form inside the window. The form seems to momentarily display at the top of the si ...

Limiting Firebase queries with startAt and endAt

I need to retrieve the first 100 results from my Firebase data, followed by the next 100, and so on. Despite trying multiple methods, I have not been successful. Method 1 ref.child('products').orderByChild('domain').startAt(0).endAt(1 ...

Press the button to switch between displaying one component and hiding another component within reactjs

I am working on a project with two distinct buttons: one for grid view and another for list view. <button onClick={() => setClassName('jsGridView')} title="Grid View" > <IoGrid className="active" s ...

Forcing a property binding update in Angular 2

Take a look at this particular component import {Component} from 'angular2/core' @Component({ selector: 'my-app', providers: [], template: ` <div> <h3>Input with two decimals</h3> <input type ...

Adjust the number of columns based on the minimum screen resolution using columnizer

Currently, I am utilizing the columnizer jQuery plugin to divide my content into columns on a responsive website with a fluid width container. I have implemented different JavaScript functions based on the minimum screen resolutions, similar to CSS media q ...