Challenges with the Placement of Buttons

I am facing an issue with the code below:

document.addEventListener("DOMContentLoaded", function(event) {
  // Select all the read more buttons and hidden contents
  const readMoreButtons = document.querySelectorAll(".read-more");
  const hiddenContents = document.querySelectorAll(".hidden");
  // Now loop over the read more buttons 
  readMoreButtons.forEach((readMoreButton, index) => {
    // Add onclick event listeners to all of them
    readMoreButton.addEventListener("click", () => {
      // Change content of read more button to read less based on the textContent
      if (readMoreButton.textContent === "Read More") {
        readMoreButton.textContent = "Read Less";
      } else {
        readMoreButton.textContent = "Read More";
      }
      // Toggle class based on index
      hiddenContents[index].classList.toggle("hidden");
      readMoreButton.closest(".snip1311").classList.toggle("reading");
    })
  })
})
/* Projects */
@import url(https://fonts.googleapis.com/css?family=Raleway:400,500,800);
.project-container {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    color: white;
}
figure.snip1311.reading {
  overflow-y: auto;
}

figure.snip1311 {
  font-family: 'Raleway', Arial, sans-serif;
  position: relative;
  float: left;
  overflow-y: hidden;
  overflow-x: hidden;
  margin: 10px 1%;
  min-width: 230px;
  max-width: 360px;
  max-height: 256px;
  width: 500rem;
  color: #ffffff;
  text-align: left;
  background-color: #07090c;
  font-size: 16px;
  -webkit-perspective: 50em;
  perspective: 50em;
  border: 5px solid #555;
}
figure.snip1311 * {
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  -webkit-transition: all 0.6s ease;
  transition: all 0.6s ease;
}
figure.snip1311 img {
  max-width: 110%;
  -webkit-transition-delay: 0.2s;
  transition-delay: 0.2s;
  backface-visibility: hidden;
  height: 258px;
}
@media all and (max-width: 500px) {
figure.snip1311 img {
  border: none;
  }
}
figure.snip1311 figcaption {
  position: absolute;
  top: 50%;
  left: 0;
  width: 100%;
  -webkit-transform: rotateX(90deg) translate(0%, -50%);
  transform: rotateX(90deg) translate(0%, -50%);
  -webkit-transform-origin: 0% 0%;
  -ms-transform-origin: 0% 0%;
  transform-origin: 0% 0%;
  z-index: 1;
  opacity: 0;
  padding: 0 30px;
}
figure.snip1311 h3,
figure.snip1311 p {
  line-height: 1.5em;
}
figure.snip1311 h3 {
  margin: 0;
  font-weight: 800;
  text-transform: uppercase;
}
figure.snip1311 p {
  font-size: 0.8em;
  font-weight: 500;
  margin: 0 0 15px;
}
figure.snip1311 .read-more {
  border: 2px solid #ffffff;
  padding: 0.5em 1em;
  font-size: 0.8em;
  text-decoration: none;
  color: #ffffff;
  display: inline-block;
}
figure.snip1311 .read-more:hover {
  background-color: #ffffff;
  color: #000000;
}
figure.snip1311 .read-more1 {
  border: 2px solid #ffffff;
  padding: 0.5em 1em;
  font-size: 0.8em;
  text-decoration: none;
  color: #ffffff;
  display: inline-block;
}
figure.snip1311 .read-more1:hover {
  background-color: #ffffff;
  color: #000000;
}
figure.snip1311:hover img,
figure.snip1311.hover img {
  -webkit-transform: rotateX(-180deg);
  transform: rotateX(-180deg);
  opacity: 0;
  -webkit-transition-delay: 0;
  transition-delay: 0;
}
figure.snip1311:hover figcaption,
figure.snip1311.hover figcaption {
  -webkit-transform: rotateX(0deg) translate(0, -50%);
  transform: rotateX(0deg) translate(0, -50%);
  opacity: 1;
  -webkit-transition-delay: 0.35s;
  transition-delay: 0.35s;
}
.hidden{
display:none;
}
.read-more{
cursor:pointer;
}
<figure class="snip1311"><img src="https://www.thespruce.com/thmb/tClzdZVdo_baMV7YA_9HjggPk9k=/4169x2778/filters:fill(auto,1)/the-difference-between-trees-and-shrubs-3269804-hero-a4000090f0714f59a8ec6201ad250d90.jpg" alt="sample98"/>
  <figcaption>
    <h3>Lorem ipsum</h3>
    <p>Lorem ipsum dolor sit amet [...]<br />
  </figcaption>
</figure>

After running the code snippet above, I noticed that when clicking the read more button, it suddenly disappears due to the lengthy text pushing it upwards. How can I ensure that the read-more button remains at the top regardless of the text length?

Desired Output

The main goal is to maintain the same margin between the read more button and the top of the card as shown in the desired output image. The alignment should stay unchanged, only ensuring that the button always appears with a consistent margin-top, irrespective of the text length. Any suggestions on achieving this result would be greatly appreciated.

Answer №1

Your element is undergoing a center flip, causing it to overflow towards the top of the scrollable section and positioning the text at a mid-top location from the center based on the content within the element once it becomes visible.

UPDATE: There are two instances in your CSS where you have applied translate(0%, -50%). The second one affects the Y axis, pushing the content 50% upwards and leading to the issue of the top not being visible.

To determine the clientHeight of the flipped element, first add a class, shown, to the element after removing the hidden class. Then use a timeout of 10 to ensure that the DOM is properly set before fetching the clientHeight of the added class shown. Divide this value by 2, subtract half of the parent element's height, including padding, and locate the top position of your content.

Next, pass this unit as a variable to your CSS using the root element =>

document.documentElement.style.setProperty('--distTrans', 'distance')
. This action will establish a CSS variable for setting the distance to position the top of your flipped content. In the CSS, adjust the transform property of the shown selector to translateY(var(--distTrans)), which will move the text to the top of the content excluding padding.

// JavaScript functions for handling showing and hiding content
function showLess(e) {
  document.querySelectorAll('.showBtn').forEach(btn => {
    if (e.target === btn) {
      btn.closest(".snip1311").classList.toggle("reading");
      btn.parentNode.classList.toggle('shown')
      btn.parentNode.classList.toggle('hidden')
    }
  })
}

// Parse the content upon DOM load
function parseContent(event) {
  // Select all the read more buttons and hidden contents
  const readMoreButtons = document.querySelectorAll(".read-more");
  const hiddenContents = document.querySelectorAll(".hidden");
  // Loop over the read more buttons 
  readMoreButtons.forEach((readMoreButton, index) => {
    // Add onclick event listeners
    readMoreButton.addEventListener("click", function(e) {
      setTimeout(() => {
        // Calculate the distance to translate
        document.documentElement.style.setProperty('--transDist', document.querySelector('.shown').clientHeight / 2 - document.querySelector('.snip1311').clientHeight / 2 + 'px');
      }, 10);
      // Toggle classes
      hiddenContents[index].classList.toggle("hidden");
      hiddenContents[index].classList.toggle("shown");
      
      let shown = document.querySelectorAll('.shown')
      if (shown) {
        shown.forEach(item => {
          item.addEventListener('click', showLess)
        })
      }
      readMoreButton.closest(".snip1311").classList.toggle("reading");
    })
  })
}

// Call the parseContent function upon DOM content load
document.addEventListener("DOMContentLoaded", parseContent)
/* Styling code for projects */

:root {
  --transDist: 100px;
}

@import url(https://fonts.googleapis.com/css?family=Raleway:400,500,800);
.project-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  color: white;
}

figure.snip1311.reading {
  overflow-y: auto;
}

/* Rest of the CSS styling rules for figure.snip1311 ... */
<figure class="snip1311"><img src="sample-image.jpg" alt="Sample Image" />
  <figcaption>
    <h3>Lorem ipsum</h3>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi sed orci interdum, eleifend nisl suscipit, ornare urna. Curabitur vel maximus lacus.</p>
    <button class="read-more">Read More</button>
    <br>
    <p class="hidden">
        /* Content inside the hidden section */
    </p>
  </figcaption>
</figure>

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

Unable to reveal hidden text with invisible formatting (font-size: 0)

I have a Joomla 3 website where I created a blog using a design-controll template. I made a "new-article" page but realized that some buttons were missing text. Upon inspecting with Firebug, I found that there was a font-size:0 property causing this issue. ...

Tips on updating an HTML page following the receipt of a CURL request by a PHP script

I am currently developing a unique login system with customized requirements. The HTML form will submit data to a PHP script using AJAX, which will then forward the information to another PHP script for processing through CURL. After some time has passed ...

Issues with LocalStrategy not executing in passport authentication

I am currently facing an issue with authenticating using Passport and LocalStrategy. It seems like the strategy is not being called and when I log the user object in passport.authenticate, it returns "false". Below is my client-side code: logIn = () =& ...

Retrieving Data Entries from a MySQL Database with AJAX, PHP, and JSON

I'm facing a challenge with my AJAX/PHP implementation and would greatly appreciate any assistance in identifying the error(s) I might be making. Below is a snippet from my initial file that effectively populates the select element in the HTML: < ...

Evaluating CSS Specificity

Is there a recommended approach for automatically testing css selectors? I am in the process of developing a SCSS framework and I want to integrate automated tests. Specifically, I aim to verify that the css selectors are functioning correctly. For examp ...

When clicked, verify whether the div is already open. If it is closed, open it using the .show method. If it is already

Currently, I am utilizing the jquery .show method to reveal a hidden div. While it is functioning as intended, I am grappling with how to implement a check to see if the div is already visible. If it is, I do not want the .show action to be repeated unnece ...

Conceal navigation button within react-material-ui-carousel

After successfully incorporating the React Material UI carousel, I found it to be quite simple. However, one thing that eluded me was how to hide the buttons and only display them on hover. I tried setting the props navButtonsAlwaysVisible to false, but it ...

"Unlocking the Power of jQuery: A Guide to Accessing XML Child

I'm struggling to extract the xml in its current format. While I can easily retrieve the InventoryResponse, I am facing difficulties when trying to access the child node a:Cost. Despite conducting research, I have been unable to find a solution that w ...

Executing NodeJS custom middleware to show parent function being called

Goal: Showcase the parent function of a middleware function shared = require('./RoutFuctions'); app.post('/link', shared.verifyToken, (req, res) => { ... } In the middleware function exports.verifyToken = functio ...

Convert HTML tables from Yahoo Pipes into an array of JSON objects

Currently, I am experimenting with Yahoo Pipes in an attempt to convert multiple tables within a DIV into an array of JSON objects. At the moment, the HTML is being successfully parsed. Here is my current setup on Yahoo Pipes I envision each table cell ...

Guide to finding and saving email addresses from a string output: extracting and storing each one individually in a text file

After collecting data from multiple sources, the output I obtained is as follows: "addressId":"132234","businessEntryCount":2026},{"district":"Nordend-West","districtSlug":"frankfurt-am-main- ...

What is the significance of the "#" character in the URL of a jQuery mobile

As I encounter a strange issue with my jQuery mobile page, I notice that when accessing page.php everything looks good, but once adding #someDetailsHere to the URL, it only displays a blank white page. What could be causing this and how can I resolve it? ...

Creating a stunning art exhibition using React Native

Currently, I am in the process of creating a gallery component that utilizes both the scrollview and image APIs. I'm curious about how the scrollview manages its child components when it scrolls down. Does it unmount the parts that are not currently ...

Updating Rails modal fields via AJAX on the modal index page

Currently, I am attempting to update the modal fields on the modal index page. On this particular page, there are two dropdown fields associated with each ticket. The goal is for the modal field to be updated when the value of these dropdowns changes. htt ...

What is the best way to transmit a JSON object rather than a JSON string to the browser using Rails?

Currently in my Rails code, I am using the following to send data to node.js: NodePush[].trigger('unit', 'join', {:id =>record.user_id, :name => record.user.name}, record.unit_id) The issue that I am encountering is that the con ...

Angular Material: Enhanced search input with a universal clear button

After searching for a cross-browser search control with a clear button similar to HTML5, I found the solution rendered by Chrome: <input type="search> The code that gave me the most relevant results can be found here. I used the standard sample w ...

VueJS not refreshing DOM after AJAX data modification

Utilizing Vue.js to make changes to my DOM, I have implemented the fetch_data() method. This method attempts to update data.messages to display 'Love the Vue.JS' once the AJAX call is successfully completed. The AJAX call executes successfully a ...

Using Selenium with C# to find elements within a chart

I am trying to locate and interact with the stimulusFrequency circles on this chart so that I can click and drag them. <svg class="svg-graph-content graphEventHandler ng-valid" ng-model="hearingGraph" viewBox="0 0 470 355" preserveAspectRatio="none"> ...

Changing the information of objects stored in arrays using React Three Fiber

My challenge is with an array of roundedBox geometry shapes called myShape. I am trying to figure out if it's possible to change the position of one of the shapes within the array without creating a new shape altogether. Ideally, I would like to updat ...

Using JSON in JavaScript to handle the click event of ASP.NET buttons

Here is the code that works well for me. I need to execute two different server-side functions, and they can't run at the same time as I have separated them. Default.aspx/AddCart btnUpdate Click Event The issue I'm facing is that the alert box ...