Is there a way to make a button on a single div only affect that specific div

I have a PHP query that echoes a div for each row in the table. I want the div to slide up and then, when the user clicks the "read more" button, the div slides down. However, since it is echoed in a loop, all the divs have the same IDs and classes. I would like the "read more" button to affect only the div it is in, not the others.

<?php
 include 'includes/database.php';

 $results = $user->getBlogs();
?>

<html>
  <head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Dundalk Healthcare Service</title>

    <!-- Bootstrap core CSS -->


    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="css/blog.css" rel="stylesheet" type="text/css"/>
    <!-- Custom styles for this template -->
    <link href="css/modern-business.css" rel="stylesheet">

  </head>

  <body>

    <?php
      include 'includes/header.php';
    ?>
    <!-- Page Content -->
    <div class="container">

      <!-- Page Heading/Breadcrumbs -->
      <h1 class="mt-4 mb-3">Our Blog
        <small></small>
      </h1>

<!-- Image Header -->
      <img class="img-fluid rounded mb-4" src="img/blog1.png" alt="">

      <!-- Blog

      <!-- Blog Post -->
      <?php
      foreach ($results as $r) {
        echo "
      <div class='card mb-4'>
        <div class='card-body' >
          <div class='row'>
            <div class='col-lg-6'>
              <a href='#'>
                <img class='img-fluid rounded' src='img/blog2.jpg' alt='cold sore'>
              </a>
            </div>
            <div class='col-lg-6'>
              <h2 class='card-title'>".$r['b_title']."</h2>
              <p class='card-text'>".$r['b_text']."</p>
              <button class='btn btn-primary read-more-btn' id='bb' data-target='content_".$r['id']."'>Read More</button>
            </div>
          </div>
        </div>
        <div class='card-footer text-muted'>
          Posted on ".$r['b_date']." by
          ".$r['b_poster']."
        </div>
      </div>";
    } ?>

      <!-- Pagination -->
      <ul class="pagination justify-content-center mb-4">
        <li class="page-item">
          <a class="page-link" href="#">&larr; Older</a>
        </li>
        <li class="page-item disabled">
          <a class="page-link" href="#">Newer &rarr;</a>
        </li>
      </ul>

    </div>

  </div>
  <!-- /.container -->

  <!-- Footer -->

    <?php
include 'includes/footer.php';
  ?>

  <!-- Bootstrap core JavaScript -->
  <script src="vendor/jquery/jquery.min.js"></script>
  <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script>

    $(document).ready(function() {
      var now = new Date();
      var Christmas = new Date("Tuesday 25, 2018");

      if(now < Christmas) // today is before valentine
      {
        alert("Happy Christmas Everyone please keep warm in this weather!💖💖💖");
      }
      else
      {
        alert("Christmas is nearly here, dont forget your flu vaccine!💔💔💔💔💔");
      }
    });

    $('.read-more-btn').click(function() {
      var target = '#' + $(this).attr('data-target');
      $(target).find('p.card-text').slideToggle();
    });


  </script>

</body>

</html>

Answer â„–1

Initially, make sure that IDs are distinct because you cannot use the same id='bb' for every card. It is advisable to replace it with a class instead.

Next, ensure you target p.card-text within the identical container:

$(".bb").click(function() {
    var div = $(this).parent();
    div.find("p.card-text").slideToggle();
});

Answer â„–2

To access the parent div that contains a button, you can use $(this).parent()

<div class="containerDiv">
    <button onclick="expand($(this).parent())">Show More</button>
</div>

Then in your script:

function expand(div) { /* Add your code here */ }

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

Modify th:hover in CSS to alter the background color

I currently have a table structured as follows: <table class="cedvel"> <caption> count: <%:Html.Encode(TempData["RowsCount"])%></caption> <thead> <tr&g ...

Implement the Vue.js @click directive in a location outside of an HTML element

I've set up a link like this: <a href="#" @click="modal=true">Open modal</a> Here's the data setup: export default { data () { return { modal: false } } } Is there a way to trigger the cli ...

The error in React syntax doesn't appear to be visible in CodePen

Currently, I am diving into the React Tutorial for creating a tic-tac-toe game. If you'd like to take a look at my code on Codepen, feel free to click here. Upon reviewing my code, I noticed a bug at line 21 where there is a missing comma after ' ...

How to fetch database results using jQuery AJAX and PHP's JSON encoding

I am currently working on a PHP code that is triggered using jQuery AJAX to query a database and retrieve results, which are then encoded into JSON format. //$rows is another query foreach($rows as $row) { $sql = 'SELECT field1, field2 FROM tabl ...

The persistent problem with constantly polling the $.ajax request

One issue I'm facing involves a continuous polling $.ajax request. The challenge lies in initiating it immediately first, and then running it at intervals set in the setTimeout call. Take a look at the example code here. myObj = {}; var output = ...

What's the best way to rearrange Bootstrap cards from a horizontal layout to a vertical layout for improved responsiveness?

I'm currently working with Bootstrap to align two cards horizontally, but I also want to ensure that mobile users can view the cards stacked in a column layout. I've experimented with adding 'flex-direction' in combination with the @med ...

Material-UI - Switching thumb styles in a range slider

Looking for a way to style two entities differently on the Material-UI Slider? Entity A as a white circle and Entity B as a red circle? While using data-index can work, there's a flaw when sliding. Is there a better approach? if (data-index === 0) { ...

Changing the time zone of a browser using JavaScript or jQuery

After researching numerous discussions on the topic, it appears that changing the browser's timezone programmatically is not possible. Although the moment-timezone.js library allows us to set timezone for its objects, it does not affect the browser&ap ...

center text vertically in HTML list

Here at this festival, you'll find a unique menu on the sidebar. The menu is created using an HTML list with the following structure: <ul class="nav nav-pills nav-stacked"> <li class="active"> <a href="index.html"><i ...

Displaying an error in Ajax caused by PHP

I've been attempting to send a POST request to a URL using Ajax. Here's what my JS/JQuery code looks like: var params = { 'username' : '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="781d1c1c190a1c ...

Utilizing Ajax to fetch a div element from a web page

Hey there! I have a link set up that loads a page into a specific div ID, which is #ey_4col3. The issue I'm facing is that it loads the entire page along with all its contents, but what I really want to load from that page is just the content within ...

Choose a value to apply to the dropdown menus

I've encountered an issue with the following code - it only seems to work once and not every time: var selectedVal = $('#drpGender_0').find("option:selected").text(); if (selectedVal == "Male") { $('#drpGender_1').fi ...

Creating a unique custom icon by leveraging the material UI icons - a step-by-step guide

I am looking to create an arrow graphic similar to the one shown in the image below https://i.stack.imgur.com/k9TvH.png Originally, I was able to achieve this using SVG - <svg height='24' width='12' style={{ marginBottom: '-4p ...

Problem concerning the window object in a React functional component

Hey there, I am currently facing a situation where I need to access the window object within my React component in order to retrieve some information from the query string. Here is an excerpt of what my component code looks like: export function MyCompone ...

I am looking to serve static HTML files in Express.js while also retaining app.get() methods for handling server-side logic

It may sound trivial, but I am struggling with displaying HTML files within app.get() methods using Express. Most solutions I have found involve using app.use(express.static(__dirname + '/public'));, which limits server-side logic. What I want i ...

Having trouble getting Firestore/Firebase to work with Next.js?

Hey everyone, I could really use some help here. I've been working on integrating Firebase into my Next.js app for the API. Everything works well when I build and run locally, but once I deploy to Vercel for production, I encounter a 500 - Internal S ...

In the following command, where is the PORT stored: ~PORT=8080 npm App.js?

section: Let's consider the following code snippet located in the App.js file: console.log(`This is the port ${process.env.PORT}`); Is there a method to retrieve the value of PORT from outside the running process? ...

Illustrating a fresh DOM element with intro.js

I am currently utilizing intro.js to create a virtual 'tour' for my website. As I aim to provide a highly interactive experience for users, I have enabled the ability for them to engage with highlighted DOM elements at different points in the tou ...

Error in returnTo behavior. The URL is being deleted just before making the post request

I have implemented express-session and included a middleware that assigns the value of req.session.returnTo to the originalUrl. router.post( '/login', passport.authenticate('local', { failureFlash: true, failureRedirect: &ap ...

Revise for embedded frame contents

Is it possible to modify the HTML content of an iframe within a webpage? I currently have this code snippet: <iframe src="sample.html"></iframe> I am looking for a way to edit the contents of sample.html without directly altering the HTML co ...