jQuery function to automatically close any other opened divs when a new div is opened

I have multiple elements that reveal a div when clicked. The issue is that if all elements are clicked, all divs open instead of just the one that was clicked.

This is my jQuery code:

<script>
$(document).ready(function() {
    $('.servicemark').click(function() {
        console.log($(this).attr('data-toggle'));
        var type =  $(this).attr('data-toggle');
        $('.'+type).slideToggle("slide");
    });
});
</script>

And here is my HTML/PHP code:

<section class="def-section home-services">
    <div class="container">
        <div class="row">
    <?php
    foreach($blocks as $block) {
      $images = json_decode($block->images);
      echo '
      <!-- === SERVICE ITEM === -->
            <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 servicemark" data-toggle="'.$block->alias.'" style="cursor:pointer;">
        <div class="service-mark-border-top"></div>
        <div class="service-mark-border-right"></div>
        <div class="service-mark-border-bottom"></div>
        <div class="service-mark-border-left"></div>
                <div class="service">
                    <div class="service-icon">
                        <img src="cms/'.$images->image_intro.'" />
                    </div>
                    <h3>'.$block->title.'</h3>
                    <div class="service-text">
                        <p>'.$block->introtext.'</p>
                    </div>
                </div>
        </div>
  ';
}
?>

 <div class="row zee-container-vervoer" style="display:none;">
    <div class="text">
        <p>Zee container vervoer Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc est neque, egestas et aliquam vitae, elementum eget neque. Donec fringilla purus nec viverra viverra. Nullam volutpat purus id risus sodales, id sodales sapien molestie. Phasellus bibendum massa et tellus aliquet rhoncus. Suspendisse accumsan, velit sed lacinia iaculis, sem neque condimentum magna, sed volutpat quam metus sed massa. Curabitur lobortis ligula sed consectetur consequat. Praesent suscipit, metus ac efficitur molestie, erat ante laoreet dolor, ut mole...
    </div>
 </div>

 <div class="row gevoelige-lading" style="display:none;">
    <div class="text">
        <p>Speciale ladingLorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc est neque, egestas et aliquam vitae, elementum eget neque. Donec fringilla purus nec viverra viverra. Nullam volutpat purus id risus sodales, id sodales sapien m...
    </div>
 </div>

 <div class="row temperatuur-gevoelige-lading" style="display:none;">
    <div class="text">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc est neque, egestas et aliquam vitae, elementum eget neque. Donec fringilla purus nec viverra viverra. Nullam volutpat purus id risus sodales, id sodales sapien ...
    </div>
 </div>

 <div class="row explosieve-lading" style="display:none;">
    <div class="text">
        <p>Gevaarlijke stoffenLorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc est neque, egestas et aliquam vitae, elementum eget neque. Donec fringilla purus nec viverra viverra. Nullam volutpat purus id risus sodale...
    </div>
 </div>
</div>
</section>

I am currently filtering everything by the alias of the correct element (class name same as alias). How can I ensure that only the currently opened element remains open while closing all others?

Answer №1

Consider this suggestion (inspired and gratitude to the feedback from Juan C.):

$('.' + option).slideToggle("slide").siblings(".line").hide();

Answer №2

Give this a shot :

$(document).ready(function() {

    $('.servicemark').click(function() {

        console.log($(this).attr('data-toggle'));


        $(".servicemark").slideUp();

        $(this).slideDown();

    })

})

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

Styling a textbox within a gridview using JavaScript

Looking for a way to format a textbox within a gridview using JavaScript? Take a look at how the gridview columns are set up: <Columns> <asp:TemplateField> <ItemTemplate><asp:ImageButton runat="server" id="imgbtnEnterAmt" ...

The process of deploying production-ready code using webpack and angular2

Currently, my Angular 2 code utilizes both webpack and grunt. During development, I rely on webpack-dev-server as a grunt task. When it comes to preparing the code for production deployment, I handle all minification tasks through Grunt which results in t ...

Having trouble with AngularJS and NodeJS routing integration?

After deciding to dive into the world of application development using the MEAN Stack, I encountered a major roadblock. For the past hour, I've been struggling to set up a basic route, only to face failure at every turn. Whenever I try to access my ...

jQuery - Modify Turn.js to exclusively implement the page Peel effect

I am attempting to implement the peel effect from turn.js into my code, where hovering over the bottom right corner of the page causes it to peel slightly and appear as if it is bending upwards. I specifically want only the peel effect and not the entire ...

$scope variables, ng-hide/show directive

There seems to be a confusion with $scope in my code. I have ng-hide/shows that use a variable in the top nav, controlled by "NavController". Inside an ng-view, controllers are linked via the app config function. The appointment setting functionality is ha ...

Issues with JavaScript causing slideshow to malfunction

I'm experiencing some issues with my image slider. It seems that during the initial loop, the slideshow keeps reverting back to 'image3'. However, after the first loop, everything appears to work correctly. I am looking for a solution to ens ...

Rails New Action fails to render HTML during AJAX GET request

Currently, I am in the midst of a project where I made an upgrade to the rails gem from version 2.3.5 to version 2.3.11. However, now I am encountering an issue with getting the controller actions to return HTML via jQuery ajax get requests. An example sce ...

The useEffect alert is triggered before the component is re-rendered

Can someone help me understand why the HP in the code below is displayed as "1" when the alert is thrown, and only set to "0" after I confirm the alert? Shouldn't the component be rerendered before the alert is thrown so that it has already been displ ...

Arranging elements on a webpage using CSS grid placements

Currently experimenting with css grid, envisioning a scenario where I have a 2x2 grid layout. When there are 4 child elements present, they would form 2 rows of 2 elements each. My challenge is when dealing with an odd number of children, I aim to avoid al ...

Dealing with an Incorrect Date in JavaScript

After working on a JavaScript logic to extract date and time from certain values, I realized that my approach needed some adjustments. Initially, I parsed the DateTime and converted it to a string. Then, I split the string to retrieve the date component. ...

Incorporate the previous page's location path into the next page using Props in Gatsby Link

My website has multiple pages with paginated lists of blog posts, each post generated from markdown using createPage(). Each page in the /posts directory displays 3 post previews and subsequent pages are numbered (e.g. /posts/2). I am trying to pass the p ...

Streamline the entire testing process of Google.Com by using Protractor to automate end-to-end testing

I need help with making Protractor navigate to google.com and search for a term. After successfully loading the non-angular page of Google, I am struggling to figure out how to make Protractor press "enter" or click the search button. Any suggestions? Ad ...

Having trouble displaying background images on GitHub pages?

I have encountered an issue with images not displaying correctly on GitHub Pages, despite trying various solutions suggested in previous posts. Strangely, the page functions perfectly on my local machine and on Netlify, but on GitHub Pages all the images a ...

Ways to set a random value to a data attribute from a specified array while using v-for in Vue.js?

In my main Vue instance, I have a data attribute that consists of an array containing 4 items: var app = new Vue({ el: '#app', efeitosAos: ['fade', 'flip-up', 'slide-up', 'zoom-in'] ...

Aligning the second heading alongside pictures and a lightbox

My issue is that I am struggling to center the "See More" link directly under each title link. Currently, it is pushed to the right and I can't seem to find a solution. Any help with this problem would be greatly appreciated. I attempted using display ...

I am searching for answers to solve issues related to a JSON file

I am currently working on a tool that searches for matches in an input field by comparing the keywords entered by the user with a JSON. During my testing phase, I focused on using a single API that provides information about different countries and fortun ...

Is it possible to schedule a periodic GET request on the server-side without utilizing the client-side or frontend?

I am currently implementing a GET request to retrieve data from a third-party API. I want to regularly check for new data every 5-10 minutes on my backend. exports.get_alerts = async (req, res) => { const alertsUrl = `https://www.g2smart.com/g2smart/a ...

Passing the results of sequelize through express after the completion of a forEach iteration

In an express route, I am running a somewhat complex sequelize query that requires me to run a second query afterward to append necessary data to the result: //Get inboxes based on passed params router.get('/:data', function(req, res, next) { ...

Incorporating HTML elements within VBScript within a single document

Here is a code snippet that mixes VBScript and HTML: IF (x.name="name") THEN n=x.value response.write("<tr>") response.write("<th>Name:</th>") response.write("<td><input name=""n2"" value=" & n & ">< ...

AngularJS text area not displaying HTML content

In my Ionic's App, I have a textarea that is used for creating or editing messages. However, I am encountering an issue where the textarea does not render HTML tags when trying to edit a message. I attempted solutions such as setting ng-bind-html and ...