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

Hover background color not being applied to child elements within Button element in Firefox

Ensuring that my product is SEO-friendly, I incorporated semantic markup using the button element and schema attributes. To separate individual items, I utilized "span" elements while setting hover effects on selected items by adding display:block. This a ...

Safari Browser does not currently offer support for MediaRecorder functionality

[Log] Webcam permission error Error: MediaRecorder is not supported I am facing an issue while trying to record audio. The Chrome browser allows audio recording without any problem, but Safari is throwing an error. global.audioStream = await navigator.m ...

The timing of setTimeout within the $.each function does not behave as expected

I am looking to back up a list, delete all items within it, and then append each item one by one with a delay of 1 second between them. This is the approach I have taken: var backup = $('#rGallery').html(); $('#rGallery li').remove(); ...

Is there a way to incorporate the Indian rupee symbol into a Google chart?

I've been trying to incorporate the Indian Rupee symbol into a Google chart using the code below: var formatter = new google.visualization.NumberFormat({ prefix: '&#8377;' }); However, I'm encountering an issue where ...

Only 50% of the time does jQuery actually work

My webpage features two interactive buttons, the "liked" and "disliked" options. These buttons are represented by images attached to a link tag that triggers a database query when clicked. The outcome of this action is displayed in a #Messages section whic ...

The fixed position setting does not anchor the elements to the bottom of a container

When applying the following styles: #fullpage-menu > .gradient { position: fixed; bottom: 0; left: 0; width: 100%; height: 0.3rem; } To the element with ID #fullpage-menu, which is styled as follows: #fullpage-menu { height: 100 ...

As I embark on building my web application using next.js, I begin by importing firebase from the "firebase" package. Unfortunately, a particular error unexpectedly surfaces in the terminal

I am currently developing a next.js web application and I have decided to utilize firebase for both database management and authentication. However, when attempting to import firebase in a specific file, I encountered the following error: Error - ./firebas ...

Hide when reaching the end with d-none

One of the challenges I'm facing is aligning a button to the right side of a column while still utilizing d-none to control its display. Previously, I used d-flex justify-content-md-around justify-content-lg-end for alignment before adding d-none, but ...

adjust highcharts chart size to fit screen width

Has anyone experienced issues with setting an explicit width of 400px on a chart? I am facing difficulties as the chart gets cut off instead of scaling down to that size. My main concern is having it resized properly for an iPhone mobile site. Can anyone ...

An onClick event is triggered only after being clicked twice

It seems that the onClick event is not firing on the first click, but only works when clicked twice. The action this.props.PostLike(id) gets triggered with a delay of one click. How can I ensure it works correctly with just one click? The heart state togg ...

How to pass GetServerSideProps into Page component props in Next.js with custom _app.js

Having issues integrating GetServerSideProps into my Next.js app. Despite the network call successfully fetching data and generating the pageName.json, the response data is not being injected into the page props as expected. Below is a snippet of my page ...

div cannot be placed next to each other

My code snippet is located at http://jsfiddle.net/kXesZ/. I am trying to align the two social media icons to the bottom edge of a background image but I am having trouble getting them to display inline. I've attempted various methods such as using dis ...

What is the process for obtaining a fresh token from Cognito using the frontend?

Currently, I am working with a react app that utilizes Cognito for user authentication. My main query revolves around making a call to Cognito using the refresh token in order to receive a new token. Despite researching various examples provided by Cognit ...

Is there a way for me to convert my (TypeScript Definition) .d.ts file into a (JavaScript) .js file?

It seems that there are plenty of guides available on converting a file from .js to .d.ts, but not the other way around. Specifically, I have some code in .d.ts format and I would like to convert it into JavaScript. Can anyone offer assistance with this t ...

Enhancing the Appearance of MUI Date Calendar

I'm in the process of creating a calendar similar to mui's <DateCalendar />, and I want to customize the header from 'S M T W T F S' to 'Sun Mon...' as well as adjust the position of the arrows. Before: After: Code : ...

Passing a click event to a reusable component in Angular 2 for enhanced functionality

I am currently working on abstracting out a table that is used by several components. While most of my dynamic table population needs have been met, I am facing a challenge with making the rows clickable in one instance of the table. Previously, I simply ...

Express POST request body is required

I am starting to learn nodejs and express, and while reviewing some code I found this interesting snippet. Can someone please explain what it means and how I can send a POST request to it using cURL? There are no specified data fields. app.post('/&apo ...

jQuery autocomplete function fails to run when embedded within a dynamically loaded AJAX form on a Ruby on

In my Rails application, I am loading a compose mail form by making an AJAX request. The code in my compose.js file looks like this: $('#main').html("<%= j render :partial =>"smails/form" %>"); When implementing an autocomplete field usin ...

Knockout.js dropdown pre-selection in nested JavaScript objects is functioning smoothly in KO 2x versions, but there seems to be a compatibility issue with KO 3x versions

This is a sample data that will be loaded from the server in JSON format and constructed into the below object graph. It consists of an array of "Choice" objects, each with properties like id, name, stages, & currentStageId. The "stages" property in th ...

Thymeleaf: Expression parsing error

I am working on a Thymeleaf template that includes pagination functionality. <ul class="results_perpage" > <li th:if="${previous != null}"><a th:href="javascript:movePage(`${previous}`);" class="results_menu" th:text="PREVIOUS">< ...