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

Capturing JSON response in Jquery

I'm struggling to figure out what's going wrong with this code. I can't seem to get any response in the status field... <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"> </script> <input typ ...

The audio must start playing prior to being forwarded to a new page

As I delve into the world of website development on my own, I have encountered an interesting challenge. At the top of my webpage, I have embedded an audio file within a button. If the user chooses to mute the audio, the navigation links will remain silent ...

The styling of the CSS is tailored to various breakpoints

source: Display helpers How can I dynamically change CSS styles based on the current breakpoint size? For example, can I set different sizes, positions, and colors for elements when the window is on xs compared to md or other breakpoints? ...

Assistance with the Chakra UI Range Slider in React

I could use some help figuring out where exactly to implement my OnChange and Map functions for mapping JSON data into a Range Slider. Everything seems to be rendering correctly, but I keep encountering an error when I try to move the slider: Unhandled Ru ...

Guide to building a dual recursion menu in AngularJS using both functional and template methods

I'm currently working on developing a menu in AngularJS using template and functional recursion. The code I have written involves quite a bit of recursion, so I could really use some assistance. Below is the menu data represented in JSON format: var ...

Failure to receive results from $.getJSON request

I am currently working on developing a web page that allows users to search and retrieve Wikipedia pages based on their search results. Below is the relevant HTML code for the search feature: <form class='search-form' onsubmit='return f ...

Tips for sending an XML string in an ajax request to an MVC controller?

I have a challenge with posting an XML string to an MVC controller using an Ajax call. The MVC controller only accepts a string parameter, and I'm struggling to successfully process the request. How can I effectively send the XML string to the Control ...

Typescript struggling to load the hefty json file

Currently, I am attempting to load a JSON file within my program. Here's the code snippet that I have used: seed.d.ts: declare module "*.json" { const value: any; export default value; } dataset.ts: import * as data from "./my.json" ...

Arrange jQuery UI elements in descending order

I need to rearrange a list in descending order, starting from the highest value down to the lowest. The values are currently listed as 10,9,8,7,6,5,4,3,2,1 and I need to update the data-ids accordingly. jQuery('.photos').sortable({ stop: f ...

Is there a way in MVC3 / .net4 to convert a JSON formatted JavaScript array into a C# string array?

I am facing a challenge with my MVC3/.Net service where it is receiving arguments in the form of a JSONified Javascript array. I want to convert them into a C# array of strings. Is there a built-in solution available for this task, or do I need to create ...

Disappearance of Dom Css following implementation of jQuery Pagination in Wordpress widget

After developing a Wordpress widget for showcasing portfolios, I have successfully integrated features such as pagination, filter categories, and customizable post count per page. Everything works seamlessly with a custom PHP pagination system that I have ...

Is there a way to confirm if the target has been successfully removed from the element using jQuery?

$(".dropdown-toggle").click(function(event) { var target = $(event.target); if (target.is(this)) { $(this).find(".caret").toggleClass("customcaret"); } }); <div class="dropdown-toggle"> <div class="caret"></div> </div> ...

Unraveling the mystery: How does JavaScript interpret the colon?

I have a quick question: When I type abc:xyz:123 in my GoogleChrome browser console, it evaluates to 123. How does JavaScript interpret the : symbol in this scenario? ...

Node.js: Error - Module 'html' not found

Currently, I am utilizing Node.js and attempting to exclusively serve HTML files without any Jade or EJS engines. Below is the code for my entry point (index.js): var express = require('express'); var bodyParser = require('body-parser&apo ...

expanding menu options in a dynamic design

My webpage features a logo alongside a menu: Here's the HTML code: <div id="logomenuwrapper"> <div id="logo"><img src="img/logo_light.jpg"/></div> <div id="menu"> <ul> <li><a href="#">About ...

The order of the data parameter in the $.ajax() method

Consider a scenario where my model is structured as follows: public class someModel{ public int age {get; set;} public string affiliation {get;set;} public string name {get;set;} } Now, let's assume that I am submitting a form someForm: ...

Tips for swapping images as a webpage is scrolled [using HTML and JavaScript]

Hi there, I am looking to make some changes to a JavaScript code that will switch out a fixed image depending on the user's scrolling behavior. For example, when the page loads, the image should be displayed on the right side. As the user scrolls down ...

The tally of seconds within a year has been altered

I have developed a function that converts inputted seconds into an output format of Years, Days, Hours, Minutes, and Seconds for the user. While I am still refining the various outputs and improving the syntax, I am currently focused on identifying a calcu ...

Tips for troubleshooting the error message "is not a function" in a React application

Hi there, I'm currently delving into learning React and have encountered an issue that says: (TypeError: newsData.map is not a function) in my browser when running my code. Oddly enough, Visual Studio Code doesn't flag any errors, only Chrome doe ...

Tips for capturing the Three.js model file content and assigning it to a variable

After exporting a model from Blender to Three.js, the resulting file contains JSON data. There are two methods I know of for loading this model: var loader = new THREE.JSONLoader() var material = new THREE.MeshPhongMaterial({color: '#8080a0'}) ...