Is there a way to streamline the jQuery code provided below?

I have programmed 6 buttons and successfully implemented jQuery to display a block of data upon clicking each button. Is there a way to condense the jQuery code? If so, what is the best approach to achieve this?

$("#button1").click(function() {
  $("#text1").show();
  $(".close").show();
  $(".close").click(function() {
    $("#text1").hide();
  });
});

... (repeated for all buttons) ...

});
#header {
  width: 640px;
  height: 480px;
  background-color: grey;
}

... (CSS styling continues) ...

};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="header">

  <div>
    <div class="block" id="text1">
      ... (HTML structure repeated for all buttons) ...
  </div>
  
  ... (more HTML structure for other buttons) ...

</div>

Answer №1

$("button.button").click(function() {
  $(this).prev('.block').show();
  $(".close").show();
  
});
    


$(".close").click(function() {
    $(".block:visible").hide();
  });
#header {
  width: 640px;
  height: 480px;
  background-color: grey;
}

div button {
  width: 100px;
  height: 100px;
  font-size: 16px;
  margin: 50px;
  float: left;
  cursor: pointer;
}

.block {
  position: absolute;
  background-color: #000;
  width: 640px;
  height: 480px;
  font-size: 14px;
  color: white;
  text-align: center;
  display: none;
  opacity: 0.7;
}

.block h1 {
  margin-top: 160px;
}

.close {
  width: 50px;
  height: 50px;
  border: 2px solid white;
  border-radius: 50px;
  display: none;
  margin-top: -220px;
  margin-left: 560px;
}

.button{color:red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="header">

  <div>
    <div class="block" id="text1">
      <h1> Button1 </h1>
      <h5> Displays block of elements </h5>
      <button class="close"> Close </button>
    </div>
    <button id="button1" class="button common-class"> Button_1 </button>
  </div>

  <div>
    <div class="block" id="text2">
      <h1> Button2 </h1>
      <h5> Displays block of elements </h5>
      <button class="close"> Close </button>
    </div>
    <button id="button2" class="button common-class"> Button_2 </button>
  </div>

  <div>
    <div class="block" id="text3">
      <h1> Button3 </h1>
      <h5> Displays block of elements </h5>
      <button class="close"> Close </button>
    </div>
    <button id="button3" class="button common-class"> Button_3 </button>
  </div>

  <div>
    <div class="block" id="text4">
      <h1> Button4 </h1>
      <h5> Displays block of elements </h5>
      <button class="close"> Close </button>
    </div>
    <button id="button4" class="button common-class"> Button_4 </button>
  </div>

  <div>
    <div class="block" id="text5">
      <h1> Button5 </h1>
      <h5> Displays block of elements </h5>
      <button class="close"> Close </button>
    </div>
    <button id="button5" class="button common-class"> Button_5 </button>
  </div>

  <div>
    <div class="block" id="text6">
      <h1> Button6 </h1>
      <h5> Displays block of elements </h5>
      <button class="close"> Close </button>
    </div>
    <button id="button6" class="button common-class"> Button_6 </button>
  </div>

  <div>

  1. Add a common class to each button
  2. use this context to tell the clicked button
  3. Use prev() to get the previous div that needs to be shown
  4. use selector .block:visible to select the visible block to hide

Answer №2

Give this a shot:

$('button').on('click', function() {
    $(this).prev('.section').show();
    $(this).prev('.section').find('.exit').show();
});

$('.exit').on('click', function() {
    $(this).parent('.section').hide();
});

Answer №3

Here's a simple way to achieve the same functionality while keeping the class names intact:

$("button").click(function() {
  if ($(this).is(".close")) $(this).closest('.block').hide();
  else {
    $(this).prev().show();
    $(this).prev().find('.close').show();
  }
});
#header {
  width: 640px;
  height: 480px;
  background-color: grey;
}

div button {
  width: 100px;
  height: 100px;
  font-size: 16px;
  margin: 50px;
  float: left;
  cursor: pointer;
}

.block {
  position: absolute;
  background-color: #000;
  width: 640px;
  height: 480px;
  font-size: 14px;
  color: white;
  text-align: center;
  display: none;
  opacity: 0.7;
}

.block h1 {
  margin-top: 160px;
}

.close {
  width: 50px;
  height: 50px;
  border: 2px solid white;
  border-radius: 50px;
  display: none;
  margin-top: -220px;
  margin-left: 560px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="header">

  <div>
    <div class="block" id="text1">
      <h1> Button1 </h1>
      <h5> Displays block of elements </h5>
      <button class="close"> Close </button>
    </div>
    <button id="button1"> Button_1 </button>
  </div>

  <div>
    <div class="block" id="text2">
      <h1> Button2 </h1>
      <h5> Displays block of elements </h5>
      <button class="close"> Close </button>
    </div>
    <button id="button2"> Button_2 </button>
  </div>


  <div>

Answer №4

To achieve this functionality, you can utilize the following jQuery script:

$("button").on("click", function() {
    $(this).prev().show();
    $(this).prev().find('.close').show();
});

$(".close").on("click", function() {
    $(this).closest('.block').hide();
});

Answer №5

Perhaps it could be wrapped in a function that can be reused multiple times.

customFunction("button1","text1","close");
customFunction("button2","text2","close");
customFunction("button3","text3","close");

function customFunction(buttonId,textId,closeClass){
  $("#"+buttonId).unbind("click").bind("click",function() {
      $("#"+textId).show();
      $("."+closeClass).show();
      $("."+closeClass).unbind("click").bind("click",function() {
          $("#"+textId).hide();
    });
  });
 }

 // The use of unbind("click").bind("click") helps prevent unnecessary events as mentioned in the feedback

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

Updating class on elements in arrays

There are multiple elements, each with a unique ID "xxx_view_ch_&&&" within an outer div with the ID "xxx_view_&&&". The goal is to change the class of the element with the ID "xxx_view_ch_&&&" when the user clicks on the entire element ("xxx_view_&&&"). ...

Unable to display images for Wordpress posts within list items

I am currently using this code to retrieve all images uploaded to a post within a specific category. The intention is to have these images displayed in a slider as list elements, but the current implementation looks like this: <li> <img...> &l ...

Customize Nivo LightBox to apply to only one video separately on the page

I've recently implemented the Nivo LightBox script on my website for a video popup effect. However, as a newcomer to jQuery, I'm struggling to customize the lightbox to only trigger when clicking a specific link for my video, rather than every li ...

Utilizing drop-down pagination with Jquery

<select multiple> <option></option> <option>a1</option> <option>b1</option> <option>c1</option> <option>d1</option> . . . . . <option>u100</option> < ...

What are some different methods for avoiding the default submission behavior of a form?

As someone with some experience in PHP, I am interested in learning Ajax jQuery. I have been exploring various tutorials on how to submit a form without refreshing the page. I've noticed that different techniques are used to prevent the form from subm ...

I am looking to continuously update the progress bar as the AJAX responses are being received

In order to update the progress bar with every response individually, I encountered an issue where multiple responses were being received at once and only the last one would update the progress bar. Despite trying async:false, the progress bar would only u ...

What is the best way to handle jQuery events within an AngularJS application?

Currently in the process of transitioning a jQuery application to AngularJS. Taking it one step at a time, but running into some challenges when it comes to listening to jQuery events within AngularJS. For instance, I have a $(document).trigger('doSo ...

Retrieve the data stored within an [Object Promise] for further use

Having trouble utilizing a value retrieved from an API call. Below is my TypeScript code: private async fetchPersonName() { let fullName = await Api.getName('Data($select=FullName)', `personId eq ${currentPersonId}`); ...

What is the best way to expand a scrollbar's width with CSS?

Can the width of a scrollbar on a <div> element within the <body> be increased? I mean the scrollbar specifically on the inner <div> element, not the default browser scrollbar since this page is in full screen mode and does not display t ...

"Utilizing a background image within a component to completely cover the entirety

Hey everyone, I need some help with a confusing issue. I'm currently working on an AngularJs project and I am struggling to set a background image for a specific component without affecting the entire application. My goal is to have the image cover t ...

Tips for effectively using the Susy +pad mixin

How can I use the +pad method to add padding on a p element without extending it past a certain point? I've tried using +pad, but the p always goes beyond the desired stopping place. Take a look at this screenshot for reference: The issue arises when ...

The JSON/jquery call to the second div yields an undefined error

When I fetch a row of data from a MySQL server using PHP, I then encode it into a JSON array. After that, I try to display the information by using the provided PHP script. However, I encountered a strange issue where if I send "vname" to its own div, I ...

Tips for limiting a website to load exclusively within an iframe

I am managing two different websites: https://exampleiframe.com (a third-party website), https://example.com (my own website) My goal is to limit the loading of https://example.com so that it only opens within an iframe on https://exampleiframe.com To a ...

Issue encountered while attempting to transfer data via the $.ajax method

I created a poll form using radio buttons. To submit the form, I utilized $.ajax. However, when I tried using $("#polling").serialize() to gather the data, nothing was sent or requested... Could the issue be related to the radio buttons? $(function( ...

How can we prevent extra data from showing up in print when using CSS media for printing?

While working on a Laravel project, I implemented CSS media print in one section. Although it works well, the Chrome Print Dialog displays additional data as shown in the image I marked below. I want to prevent this data from showing up when printing. Can ...

Creating a website with an iframe that adjusts to different screen sizes

Currently, my website features an iframe as the primary content with some graphs displayed in a sidebar. However, I am facing layout issues when the screen size is adjusted. I have been struggling to ensure that the iframe fits properly within the website ...

Utilizing Webpack to emulate the @apply functionality of Tailwind CSS and shift away from using @extend in SASS

I am currently developing an internal CSS 'framework' / methodology that falls somewhere in between ITCSS and Tailwind. We heavily rely on utility classes, but sometimes the length of the actual class name becomes too much and we feel the need t ...

The alignment of buttons is not defined for ASP buttons and Bootstrap dropdowns

I'm having an issue with the placement of my ASP button and button dropdown list. The dropdown always appears below the other buttons, but I want it to be in the same row as the other buttons. Below is a screenshot showing the current layout of the b ...

Use Jquery to verify whether a specific Div element does not have any children elements with a particular

Here is my HTML code: I'm looking to use JQuery to check if the divChatWindow element does not have any child elements with the id of li. How can this be accomplished? ...

Guide to implementing CSS3 transitions with prefixes using JavaScript

Is there a way to apply CSS styles using JavaScript when I don't have access to the CSS file? #fade div { -webkit-transition: opacity 1s; -moz-transition: opacity 1s; -o-transition: opacity 1s; -ms-transition: opacity 1s; transition: ...