Tips for optimizing Jquery selectors to streamline recurring functions

I have 9 "service node" divs in my HTML code, each containing a hidden div and a button that triggers the rotation of the button by 45 degrees and reveals the hidden div. The challenge I am facing is that I have been using repetitive functions for each service node div, assigning arbitrary classes to them as clicking one button affects all buttons and hidden divs. To address this issue, I am experimenting with using the 'this' selector for rotating the button and implementing the parent > child selector instead of relying on arbitrary classes. However, I am struggling with the 'servicedescription' selectors for toggleClass since 'this' does not work for the hidden div when the button is clicked. Below is the current code where modifications have only been made to the first servicenode function.

$(".servicenode > Button").click(function(){
    $(".servicedescription1").toggleClass('servicedescriptionhide servicedescriptionshow');
    $("this").toggleClass('buttonrotate');
  });
   
  $(".button2").click(function(){
    $(".servicedescription2").toggleClass('servicedescriptionhide servicedescriptionshow');
    $(".button2").toggleClass('buttonrotate');
  });
  
  $(".button3").click(function(){
    $(".servicedescription3").toggleClass('servicedescriptionhide servicedescriptionshow');
    $(".button3").toggleClass('buttonrotate');
  });
  
  $(".button4").click(function(){
    $(".servicedescription4").toggleClass('servicedescriptionhide servicedescriptionshow');
    $(".button4").toggleClass('buttonrotate');
  });
  
  $(".button5").click(function(){
    $(".servicedescription5").toggleClass('servicedescriptionhide servicedescriptionshow');
    $(".button5").toggleClass('buttonrotate');
  });
  
  $(".button6").click(function(){
    $(".servicedescription6").toggleClass('servicedescriptionhide servicedescriptionshow');
    $(".button6").toggleClass('buttonrotate');
  });
  
  $(".button7").click(function(){
    $(".servicedescription7").toggleClass('servicedescriptionhide servicedescriptionshow');
    $(".button7").toggleClass('buttonrotate');
  });
  
  $(".button8").click(function(){
    $(".servicedescription8").toggleClass('servicedescriptionhide servicedescriptionshow');
    $(".button8").toggleClass('buttonrotate');
  });
  
  $(".button9").click(function(){
    $(".servicedescription9").toggleClass('servicedescriptionhide servicedescriptionshow');
    $(".button9").toggleClass('buttonrotate');
  });
<div class="services">
 
  
  <div class="servicenode"><button class="button1" type="button">></button><p class="servicetitle">Tree Removal</p><p class="servicedescription1 servicedescriptionhide">From big to small, we have the tools and expertise for all your needs</p>
  <img class="a beforetoggle" src = "images/beforeafter/treeremovalflip_300x400.jpg">
  </div>
  
  <div class="servicenode"><button class="button2" type="button">></button><p class="servicetitle">Tree Trimming</p><p class="servicedescription2 servicedescriptionhide">From big to small, we have the tools and expertise for all your needs</p>
  <img class="b beforetoggle" src = "images/beforeafter/treetrimmingflip_300x400.jpg">
  </div>
  
  <div class="servicenode"><button class="button3" type="button">></button><p class="servicetitle">Stump Grinding</p><p class="servicedescription3 servicedescriptionhide">From big to small, we have the tools and expertise for all your needs</p>
  <img class="c beforetoggle" src = "images/beforeafter/stumpgrindingflip_300x400.jpg">
  </div>
  
  <div class="servicenode"><button class="button4" type="button">></button><p class="servicetitle">Hedge Trimming</p><p class="servicedescription4 servicedescriptionhide">From big to small, we have the tools and expertise for all your needs</p>
  <img class="d beforetoggle" src = "images/beforeafter/hedgetrimmingflip300x400.jpg">
  </div>
  
  <div class="servicenode"><button class="button5" type="button">></button><p class="servicetitle">Fruit Tree Pruning</p><p class="servicedescription5 servicedescriptionhide">From big to small, we have the tools and expertise for all your needs</p>
  <img class="e beforetoggle" src = "images/beforeafter/fruittreeflip_300x400.jpg">
  </div>
  
  <div class="servicenode"><button class="button6" type="button"></button><p class="servicetitle">Wood & Brush Removal</p><p class="servicedescription6 servicedescriptionhide">From big to small, we have the tools and expertise for all your needs</p>
  <img class="f beforetoggle" src = "images/beforeafter/treeremovalflip300x400.png">
  </div>
  
  <div class="servicenode"><button class="button7" type="button"></button><p class="servicetitle">Lot Clearing</p><p class="servicedescription7 servicedescriptionhide">From big to small, we have the tools and expertise for all your needs</p>
  <img class="g beforetoggle" src = "images/beforeafter/lotclearingflip300x400.jpg">
  </div>
  
  <div class="servicenode"><button class="button8" type="button"></button><p class="servicetitle">Cabling & Bracing</p><p class="servicedescription8 servicedescriptionhide">From big to small, we have the tools and expertise for all your needs</p>
  <img class="h beforetoggle" src = "images/beforeafter/cablingbracingflip_300x400.jpg">
  </div>
  
  <div class="servicenode"><button class="button9" type="button"></button><p class="servicetitle">Storm Damage</p><p class="servicedescription9 servicedescriptionhide">From big to small, we have the tools and expertise for all your needs</p>
  <img class="i beforetoggle" src = "images/beforeafter/stormdamageflip_300x400.jpg">
  </div>
 
 </div>

Answer №1

To easily navigate to sibling elements using a common class on buttons, add a click listener that utilizes this for dynamic navigation.

Consider the following HTML structure:

<div class="servicenode">
  <button class="mybutton" type="button">></button>
  <p class="servicetitle">Tree Removal</p>
  <p class="servicedescription servicedescriptionhide">From big to small, we have the tools and expertise for all your needs</p>
  <img class="a beforetoggle" src="images/beforeafter/treeremovalflip_300x400.jpg">
</div>

You can achieve this behavior by adding the following script:

$('.mybutton').click(function() {
  $(this)
    .siblings('.servicedescription')
    .toggleClass('servicedescriptionhide servicedescriptionshow');
  $(this).toggleClass('buttonrotate');
});

This approach can be applied to all similar .servicenode elements.

I suggest avoiding having both classes servicedescriptionhide and servicedescriptionshow. Instead, opt for one class such as:

.servicedescription {
  /* properties for servicedescriptionshow */
}
.servicedescription.hide {
  /* properties for servicedescriptionhide */
}

By doing so, it will simplify your JavaScript code and reduce repetition in both HTML and JS.

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

There are a few issues with certain Bootstrap elements such as the Navbar-collapse, p- classes, and small column images

I wanted to express my gratitude for all the incredible resources shared here. I have been working on sorting out some issues over the past few days. While Bootstrap seems to be functioning well in certain areas, it's not working as expected in oth ...

In search of the precise locator for conducting Selenium tests

During my project work, I've encountered the challenge of finding the correct locator for Selenium testing. Despite trying various combinations, I can't seem to locate the right one to click on a specific link. Every attempt results in a "No Such ...

It appears that the jQuery $.get and $.post methods are not functioning as expected

Hey everyone, I'm facing an issue with two PHP session variables that I need to clear on click. I've attempted using both $.get and $.post AJAX methods to trigger an external PHP script that should reset the values of these session variables. How ...

CSS overflowing issue causing inability to reach bottom of div with scroll bars not functioning as anticipated

My objective is to create a layout featuring a sticky header and left sidebar, with a non-sticky DashboardBody (the green-bordered box) that can be scrolled through. When scrolling, I want the content at the top to disappear "under" the sticky header. The ...

"Concealing specific choices in Autocomplete with reactjs: A step-by-step guide

I am looking for a way to hide the selected option in a Dropdown menu so that it does not appear in the next dropdown. For example, if "Hockey" is selected in the first dropdown, it should not be displayed in the second dropdown; only "Baseball and badmint ...

Using the power of jQuery to organize an array of random elements within the console

Although it may seem like a simple question, it's not something I do often. However, I need to help a classmate by writing a jQuery script that will randomly sort and display numbers in the console each time the browser is refreshed. The array of num ...

Restrict the amount of decimal places allowed in input text

Another question on Stack Overflow addresses limiting the number of characters allowed in a form input field. I am specifically looking to restrict the number of digits that can come after the decimal point to 2 digits. <input type="text" maxlength="2 ...

Is there a way to substitute all underscores in HTML tag IDs and classes with a hyphen symbol?

I recently realized that I used underscores instead of hyphens in some of my CSS class and id names. To correct this, I want to replace all underscores with hyphens using the sublime text replace feature (ctrl + H). Is there a way to change underscores to ...

Show side by side using javascript

My dilemma lies in having a set of cards that are meant to be displayed inline, but I have to initially hide them using "display: none". When a specific button is clicked, I aim to reveal these cards; however, upon doing so, each card seems to occupy its o ...

The Github page is continuously loading without displaying any content

Recently, I created a web-map application using the OpenLayers library and published it on Github Pages. You can access it through this link: . However, when I try to load the page, the content doesn't show up and it just keeps loading indefinitely. ...

What is the best way to manage a group of checkboxes using EJS?

I am currently utilizing ejs for my website pages and on one particular page, I have an array of objects. The number of objects in the array is not known when the page initially loads. This page allows me to edit a series of announcements and I would like ...

Leveraging Global SCSS Variables in Next.JS with SASS

In my Next.js Application, I have a global CSS file named main.scss imported in the pages/_app.js file. _app.js import '../global-styles/main.scss' export default function MyApp({ Component, pageProps }) { return <Component {...pageProps} ...

How to perfectly align an element within a div using Bootstrap

Utilizing bootstrap here. Currently trying to center the h1 element within the div, but so far I have been unsuccessful. It consistently remains aligned to the left. Attempts have included using bootstrap's center-block helper class, as well as the fl ...

Display only the spans that contain text or are not empty

I need a solution to hide only those spans that are empty. <div class="img-wrapper"> <div class="showcase-caption" style="display: block; "> <span id="MainContent_ImageCaption_0">This one has caption</span> </div> ...

Positioning CSS icons beside text

I'm having trouble aligning a close button I created in CSS with regular text. Although the containing span element seems to align with the adjacent text, it doesn't align properly with the child divs. <a class="event-filter button" href="#"& ...

Leveraging Jquery for parsing XML data retrieved from a PHP script

For enhanced security, I am utilizing a PHP script to obtain XML data from an external server. The code in the PHP file appears like this - <?php include_once 'utilityCurl.class.php'; $uri = 'http://OURSITE/feeds/?feedID=99&c&apo ...

What is the process for setting up a banner on one page that will automatically be reflected on all other pages?

Is there a way to have a banner in a div and display it on the home page so that it automatically appears on all other pages without needing to place the code on each page individually? Any assistance would be greatly appreciated :) ...

Increasing the font size on a document

Once again, faced with my own silly problems. This time I stumbled upon the following page: http://jsfiddle.net/g3VBT/ I am trying to style the "enter your U.R.L here" text with the following properties: font-weight: 600; font-size: 1.5em; The issue ...

Allowing CSS to break long words but not spaces for better readability

Imagine you have the following paragraph: thisisaverylongwordthatneverbreaks Applying word-wrap:break-word; results in: thisisaverylongwordthat neverbreaks This works well, but what if I try: this is avery long word that has spaces The output becom ...

conceal elements created with JQuery within an AJAX function

Is it possible to use jQuery and the $.ajax() method to submit a form, displaying only the result while hiding other elements on the page? I am looking to add a conditional in the Ajax method that will show the result if successful, hiding certain elements ...