When the HTML content matches a specific value, initiate a click event to trigger

Can anyone help me troubleshoot? I've tried multiple methods but can't seem to get it right. Here's a breakdown of what I'm attempting to accomplish:

#info-NUMBER-btn shows

Click to display more information
.
#info-NUMBER CSS is set to display: none.

When #info-NUMBER-btn is clicked:
- The corresponding #info-NUMBER-btn changes to

Click to display less information
.
- The corresponding #info-NUMBER CSS is set to display: inline-block.

/* Jquery */

$(document).ready(function() {
    $("#info-1-btn").text("Click to display more information");
    $("#info-2-btn").text("Click to display more information");
    $("#info-3-btn").text("Click to display more information");
    $("#info-4-btn").text("Click to display more information");
    $("#info-5-btn").text("Click to display more information");
    
    if($("#info-1-btn").text("Click to display more information")) {
    $("#info-1-btn").click(function () {
    $(this).text("Click to display less information");
    $("#info-1").css("display", "inline-block");
    });
    } else if($("#info-1").text("Click to display less information")) {
    $("#info-1-btn").click(function() {
    $(this).text("Click to display more information");
    $("#info-1").css("display", "none");
    });
    }
    
    
    if($("#info-2-btn").text("Click to display more information")) {
    $("#info-2-btn").click(function () {
    $(this).text("Click to display less information");
    $("#info-2").css("display", "inline-block");
    });
    } else {
    $("#info-2-btn").click(function() {
    $(this).text("Click to display more information");
    $("#info-2").css("display", "none");
    });
    }
    
    
    if($("#info-5-btn").text("Click to display more information")) {
    $("#info-5-btn").click(function () {
    $(this).text("Click to display less information");
    $("#info-5").css("display", "inline-block");
    });
    } else {
    $("#info-5-btn").click(function() {
    $(this).text("Click to display more information");
    $("#info-5").css("display", "none");
    });
    }
    }); 
<!-- HTML -->
<div id="info-5" class="hire-equipment-more-information">
  <table class="hire-equipment-more-information-table" cellpadding="15px">
    <tr>
      <th>Length:</th>
      <th>Material:</th>
      <th>HP:</th>
    </tr>
    <tr>
      <td>7.5m</td>
      <td>Aluminium</td>
      <td>225</td>
    </tr>
  </table>
</div>
<br />
<a id="info-5-btn" class="hire-equipment-item-link"></a>

Answer №1

To simplify the process, consider binding to the class hire-equipment instead of individual element id's.

This way, you can avoid binding to multiple buttons that perform the same action.

Upon triggering the eventHandler, you can use the function's first argument to determine which button was clicked and proceed accordingly.

For instance, you can create the elements and set up a single event handler.

Using $(selector).click() will bind to all elements with the selector (hire-equipment in this case). Then, it will identify the originating button, locate the parent node (containing the button, title, and description), find the description element, and toggle its hidden class. The button's text will change based on its current state.

While not identical to your setup, this is a demonstration of how to make your event handlers more universal.

$('.hire-equipment').click(function(event) {
  var sourceElement = $(event.target);
  $(sourceElement).parent().find('.description').toggleClass('hidden');
  if ($(sourceElement).text() === 'Show more information') {
    $(sourceElement).text('Show less information');
  } else {
    $(sourceElement).text('Show more information');
  }
});
.hidden {
  display: none;
  visibility: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <p class="title">Title of item</p>
  <div class="description hidden">This is a description</div>
  <button type="button" class="hire-equipment">Show more information</button>
</div>
<div>
  <p class="title">Title of item</p>
  <div class="description hidden">This is a description</div>
  <button type="button" class="hire-equipment">Show more information</button>
</div>
<div>
  <p class="title">Title of item</p>
  <div class="description hidden">This is a description</div>
  <button type="button" class="hire-equipment">Show more information</button>
</div>
<div>
  <p class="title">Title of item</p>
  <div class="description hidden">This is a description</div>
  <button type="button" class="hire-equipment">Show more information</button>
</div>

Answer №2

Let's investigate this line of coding

if($("#info-1-btn").text("Click to view more details")) {

It should be revised to:

if($("#info-1-btn").text() === "Click to view more details")) {

The text function serves multiple purposes. If no value is passed, it returns the text within the element.

When a value is passed, it alters the text and returns the jQuery object again (which will be evaluated as a truthy value).

Now let's review your overall logic.

Your code evaluates the button's status only once, upon document load. It should instead evaluate the button's status within the click handler.

Refer to this complete example: http://plnkr.co/edit/Qr4LtPhYZ9AqV6t55qXd?p=preview

While it may not align precisely with your requirements, it showcases how to check the button's state within a click handler.

Additionally, it illustrates the use of a custom attribute (in this instance, data-target) to connect a button to a div block.

<!DOCTYPE html>
<html>

<head>
  <script data-require="jquery@*" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
</head>

<body>
  <button class="toggleButton" data-target="buttonOneInfo"></button>
  <br />
  <div class="toggleTarget" id="buttonOneInfo">
    Here's some information about the first item
  </div>
  <button class="toggleButton" data-target="buttonTwoInfo"></button>
  <br />
  <div class="toggleTarget" id="buttonTwoInfo">
    Here's some information about the second item
  </div>
  <button class="toggleButton" data-target="buttonThreeInfo"></button>
  <br />
  <div class="toggleTarget" id="buttonThreeInfo">
    Here's some information about the third item
  </div>


</body>

<script type="text/javascript">
  $(function() {
    $('.toggleTarget').hide();
    $(".toggleButton")
      .text("Click to view more details")
      .click(function() {
        var toggleTargetId = $(this).attr('data-target');
        var toggleTarget = $(document.getElementById(toggleTargetId));

        if ($(this).text() === 'Click to view more details') {
          $(this).text('Click to view less details');
          toggleTarget.show();
        } else {
          $(this).text('Click to view more details');
          toggleTarget.hide();
        }
      });
  });
</script>

</html>

Answer №3

Streamlined OP's jQuery code by removing unnecessary elements. The process outlined below:

  • Mainly using the toggleClass() method
  • Requires at least 2 classes to indicate the state of .info-btn
  • The benefit of utilizing classes is the ability to add more styles to enhance the state of .info-btn such as color and background-color

For more detailed information, refer to the comments in the Snippet source below:

SNIPPET

/* jQuery */

// Alternative syntax for $(document).ready(
$(function() {

  // Click on ANY element with the class .info-btn
  $(".info-btn").on("click", function(e) {

    // Prevent .info-btn from jumping when clicked
    e.preventDefault();

    /* `this` or .info-btn will switch between the 
    | classes of .more and .less
    | Refer to CSS for behaviors in different states of
    | .info-btn
    */
    $(this).toggleClass('more less');
  });
});
.info-btn {
  cursor: pointer;
}
/* Both classes use the :after pseudo-selector
| The content value will complete the 
| string: "Click to display"...
*/

a.more:after {
  content: ' more information';
}
a.less:after {
  content: ' less information';
}
button.less:before {
  content: 'less ';
}
button.less:after {
  content: ' more';
}
button.more:before {
  content: 'more ';
}
button.more:after {
  content: ' less';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- HTML -->
<div id="info-5" class="rental-info">
  <table class="rental-info-table" cellpadding="15px">
    <tr>
      <th>Length:</th>
      <th>Material:</th>
      <th>HP:</th>
    </tr>
    <tr>
      <td>7.5m</td>
      <td>Aluminium</td>
      <td>225</td>
    </tr>
  </table>
</div>
<br />
<a class="info-btn rental-link more">Click to display</a>
<br/>
<button class='info-btn less'>is</button>
<br/>

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

The peculiar effect of a CSS element's border on surrounding elements is quite unusual

I'm experiencing a strange issue that I can't quite figure out. To demonstrate the problem, I've created a fiddle. What's puzzling me is why applying a border to one of the three canvases causes my other two .headerMainDiv elements to ...

Mistake in Timestamp Separation - JavaScript

I have a Timestamp retrieved from MSSQL and displayed on a Webclient. The timestamp reads: Thu Jan 01 18:00:00 CET 1970, however, I am only interested in the time format: 18:00 or 18:00:00 (preferably the former). <script> var timestamp = ...

exciting, showcasing a dependency map using svg within an html5 environment

I am working on creating a polygon background for my menu, which needs to be responsive in design. Here is an example of what I am trying to achieve: example image. Should I use JavaScript to listen for size changes and adjust the points for the polygon e ...

What is causing the div to not update until the for loop is completed?

I have an HTML page where I am trying to update a div while a for loop is running. However, the div does not update until after the loop finishes. Why is this happening? <!DOCTYPE html> <html> <body> ...

Challenges arising from the use of 'position: absolute' in managing relationships between grandparents, parents, and children

Within my React project, all code is enclosed within the root div (grandparent). In my Project.js component, there is a separate div (parent) solely responsible for the background color. This component is then displayed in App.js without any additional d ...

Manipulating classes within ng-class in AngularChanging classes in ng-class dynamically

Featuring multiple elements with an ng-class that behaves similarly to a ternary operator: ng-class="$ctrl.something ? 'fa-minus' : 'fa-plus'" To access these elements, we can compile all the ones with fa-minus and store them in a lis ...

Exploring the usage of arrays within Angular 4 components. Identifying and addressing overlooked input

I'm struggling with array declaration and string interpolation in Angular 4 using TypeScript. When I define the following classes: export class MyArrayProperty { property1: string; property2: string; } export class MyComponent { @Input() object: ...

Function in nodejs throwing an error: Return type missing

I am facing an issue with this code snippet while trying to compile the application. public async test(options?: { engine?: Config }): Promise<any> { const hostel = new Service({ list: this.servicesList, createService ...

"VueJs and ChartJs work together to create single file components, but the computed property is only rendered in Vue Dev Tools when the component is

Currently, I am working on a single file component that utilizes Chart.Js to display a basic visualization of some hardcoded data. The Chart.Js library is being called from a CDN placed in the head section of my index.html file. The project is based on th ...

What is the best way to choose an item from a list nested inside a div?

Currently, I am facing the challenge of selecting an item from a list that is structured using a div For this task, I am utilizing WebDriver IO () <div class="selectize-dropdown demo-default select-class single" style="display: none; width: 196px; top ...

If the error state is true, MuiPhoneNumber component in react library will disable typing, preventing users from input

I am currently trying to implement the material-ui-phone-number plugin for react, using Material UI. Whenever the onChange event is triggered, it calls the handlePhone function which stores the input value in the state. However, I have encountered an issue ...

Convert the data received from jQuery $.parseJSON into HTML code

I am using $.parseJSON to retrieve data from a specific URL. The link I receive contains {"status":"ok", "message":'<form><input type="text" name="" value=""> </form>'} Now, I want to add the "message" part to my content. $. ...

Auth0 encountering issues retrieving ID token and user metadata

Currently in the process of integrating Auth0 into a Vue.js/Node.js application, I have successfully enabled user registration and login functionality (to /callback). Although the manual addition of data to the user metadata section is functional at this s ...

Transforming CSS shorthand background properties into longhand representation

I have been working on a function to convert shorthand CSS background declarations into longhand. The function I created is functional, but it does not handle cases where the background-color property includes color values like black or yellow. It also doe ...

What exactly is the purpose of the double ampersand selector, '&&', when it comes to overriding the root class with makeStyles within Material-UI React?

I recently started using Material-UI and encountered an issue where I couldn't override the root class for Avatar, specifically MuiAvatar-root. Material-Ui Version: 4.11.3 Despite following examples provided by material-ui's documentation here, ...

AngularJS Setting Default Values in HTML Pages

My goal is to set the default value for a dropdown in an Angular HTML Page. The page uses tabs, and I want the default value to load when a specific tab is clicked. <div class="col-md-9" ng-cloak ng-controller="ServiceTypeController"> <md-conten ...

Gather information on a webpage

I am attempting to extract a table from the following page "https://www.hkex.com.hk/Mutual-Market/Stock-Connect/Statistics/Historical-Monthly?sc_lang=en#select1=0&select2=0". After using the inspect/network function in Chrome, it appears that the data ...

What are the steps for implementing CORS?

I recently attempted to set up Ajax calls and stumbled upon the following code snippet: <!DOCTYPE html> <html> <body> <p id="demo">Let AJAX update this text.</p> <button type="button" onclick="loadDoc()">Updat ...

Utilize jQuery to insert a span element inside a paragraph element before it is appended to the DOM

My current task involves utilizing jQuery DOM elements to insert a few paragraphs into a div. The following code accomplishes this successfully: $('#detail_overlay').append($('<p />', { "class" : "detail_txt" }) .text( $(' ...

Creating a vibrant and mesmerizing inward spiraling rainbow of colors on canvas using JavaScript

After coming across an image that caught my eye, I was inspired to recreate it using canvas: https://i.stack.imgur.com/fqk3m.png I've attempted drawing arcs starting from the center of the screen, but I'm struggling with getting their paths acc ...