Tips for creating a div element that closes on the second click:

On the PC version, I have three blocks that open and close perfectly when clicked. However, on the mobile version, when I click on one block, it opens but does not close unless I click on another block. Additionally, if I click again on the same block that is already opened, it just reopens without closing. I am unable to close it for some reason. Any assistance would be appreciated!

<div class="section stats tint">
                <div class="container w-container">
                    <div class="hero-overlay-row w-row">
                            <div class="stats-column w-col w-col-4">
                                <a class="hero-overlay-block-1 w-inline-block" href="#">
                                    <div class="hero-overlay-number">У</div>
                                    <div class="hero-overlay-block-title">УЗО</div>
                                    <p class="link-block-paragraph">Ги брани и прикажува ставовите на учениците.</p>
                                </a>
                            </div>
                        <div class="block-uzo">
                            <h3>УЗО</h3>
                            <p>
                                Училишната Заедница на СУГС Орце Николов претставува легитимно тело составено од претседателите на сите класови,
                                со свое посебно претседателство и организација, основано со цел да ги брани и прикажува ставовите на учениците,
                                да воспоставува легитимна врска помеѓу учениците и училишните служби. Да организира настани, и покренува иницијативи
                                за подобрување на образованието.
                            </p>
                        </div>
                        <div class="stats-column w-col w-col-4">
                        <a class="hero-overlay-block-2 w-inline-block" href="#">
                        <div class="hero-overlay-number">М</div>
                        <div class="hero-overlay-block-title">Мисија</div>
                            <p class="link-block-paragraph">Комуникација и соработка со училишните служби.</p>
                        </a>
                        </div>
                        <div class="block-misija">
                            <h3>Мисија</h3>
                            <p>
                                УЗО  ги застапува потребите и интересите на учениците, преку комуникација и соработка со училишните служби и истовремено
                                поттикнува и придонесува личен развој, преку вклучување на учениците во училишни и вонучилишни активности.
                            </p>
                        </div>
                        <div class="last stats-column w-col w-col-4">
                        <a class="hero-overlay-block-3 w-inline-block" href="#">
                        <div class="hero-overlay-number">В</div>
                        <div class="hero-overlay-block-title">Визија</div>
                            <p class="link-block-paragraph">Подобрување на образованието.</p>
                            </a></div>

                        <div class="block-vizija">
                            <h3>Визија</h3>
                            <p>
                                УЗО е самостојо рамноправно и легитимно тело составено од активни, мотивирани и амбициозни ученици, кое на демократски
                                начин е вклучено во носењето одлуки во соработка со училишните служби.
                            </p>
                        </div></div></div></div>

$(document).ready(function () {
    $(window).on("resize", function (e) {
        checkScreenSize();
    });

    checkScreenSize();

    function checkScreenSize() {
        var newWindowWidth = $(window).width();
        if (newWindowWidth < 768) {
            $(document).ready(function () {
                $('.hero-overlay-block-1').click(function () {
                    $('.block-uzo').slideToggle("slow");
                    $('block-uzo').css('display', 'block');;
                    $('.block-more-1').hide();
                    $('.block-misija').hide();
                    $('.block-vizija').hide();
                });
            });
            $(document).ready(function () {
                $('.hero-overlay-block-2').click(function () {
                    $('.block-misija').toggle("slow");
                    $('.block-misija').css('display', 'block');;
                    $('.block-more-2').hide();
                    $('.block-uzo').hide();
                    $('.block-vizija').hide();
                });
            });
            $(document).ready(function () {
                $('.hero-overlay-block-3').click(function () {
                    $('.block-vizija').toggle("slow");
                    $('block-vizija').css('display', 'block');;
                    $('.block-more-3').hide();
                    $('.block-uzo').hide();
                    $('.block-misija').hide();
                });
            });
        }
    }
});

Answer №1

I am not fluent in Russian, but I will give it my best shot...

It appears that your issue stems from an excessive registration of click handlers, leading to unexpected behavior.

Within the

$(window).on("resize", function (e) { checkScreenSize(); }
section, you are repeatedly calling the checkScreenSize function every time the window is resized. This results in the continuous registration of click handlers for each hero element, particularly noticeable on mobile devices when the resolution drops below 768.

A more efficient approach might look something like this:

$(document).ready(function() {
    $('.hero-overlay-block-1').click(function() {
        if ($(window).width() < 768) {
            $('.block-uzo').slideToggle("slow");
            $('block-uzo').css('display', 'block');
            $('.block-more-1').hide();
            $('.block-misija').hide();
            $('.block-vizija').hide();
        }
    });
    $('.hero-overlay-block-2').click(function() {
        if ($(window).width() < 768) {
            $('.block-misija').toggle("slow");
            $('.block-misija').css('display', 'block');
            $('.block-more-2').hide();
            $('.block-uzo').hide();
            $('.block-vizija').hide();
        }
    });
    $('.hero-overlay-block-3').click(function() {
        if ($(window).width() < 768) {
            $('.block-vizija').toggle("slow");
            $('block-vizija').css('display', 'block');
            $('.block-more-3').hide();
            $('.block-uzo').hide();
            $('.block-misija').hide();
        }
    });
});

By implementing this method, you only need to register a click handler once for each hero element, with the screen resolution check being performed as the click events occur.

If I have misunderstood the root of your problem, I apologize and hope this solution proves helpful.

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

Problem with object positioning in Three.js when applying rotation matrix

I am attempting to rotate an object named "moon" (which is represented as a sphere) using a matrix instead of the moon.rotation.y property. Here is the code I am using: moon.applyMatrix(new THREE.Matrix4().makeRotationY(Math.PI/100)); The rotation of the ...

No server needed reCAPTCHA

I have successfully integrated reCAPTCHA into a Contact form on my website, which includes three fields: name, email, and message. The data from this form is stored in Firebase for easy access. This implementation was done using React, with the help of th ...

Looking for a Horizontal Layout?

@foreach (var item in APModel) { <div class="row row-cols-1 row-cols-md-2 g-4"> <div class="col"> <div class="card" style="width: 18rem;"> <img src="h ...

Filtering objects in AngularJS is a complex task, especially when you need to be able to search for a specific value but also consider if that value exists

Struggling to convey my thoughts in English, but here it goes. Imagine two objects linked by colorid: $scope.fruits = {{name:"apple",colorid:"1"},etc}; $scope.colors = {{id:"1",value:"red"}; I've created a table with search and filter function ...

Creating an XPath expression for selecting multiple siblings of a div tag

Currently, I am working on writing an XPath expression for a specific section of code: <div class="line info"> <div class="unit labelInfo TextMdB">First</div> <div class="unit lastUnit"> <div clas ...

Ask the controller for information, then send it to the appropriate route before displaying it in

Within my HomeController, there is a method that requires specific arguments to function properly. public function mcQuery($ip, $port){ $Query = new MinecraftQuery(); try { $Query->Connect( $ip, $port ); return ...

Issues observed with the functionality of the fixed position menu bar

Is it strange that the menu bar remains fixed at the top of the page while scrolling down, but ends up going under another div making it impossible to click on the menu? #cssmenu { position: fixed; left: 0; top: 0; height: 40px; width: 100%; ...

Oops! We couldn't locate or access the file you're trying to import: ~bootstrap/scss/bootstrap

Following the steps outlined on getbootstrap.com, I assumed that everything would function smoothly. Unfortunately, that hasn't been the case so far. All seems well until I attempt to load the page, at which point my Express.js app throws a: [[ ...

Converting Plain JSON Objects into a Hierarchical Folder Structure using Logic

Looking at the data provided below: [ {name: 'SubFolder1', parent: 'Folder1'}, {name: 'SubFolder2', parent: 'SubFolder1'}, {name: 'SubFolder3', parent: 'SubFolder2'}, {name: 'Document ...

Tips for resizing the MUI-card on a smaller screen

Is there a way to adjust the width of the card on small screen sizes? It appears too small. You can view my recreation on codesandbox here: https://codesandbox.io/s/nameless-darkness-d8tsq9?file=/demo.js The width seems inadequate for this particular scr ...

Position the div within a flex container to the right side

How can I position the album cover div to the right within the card? I attempted using the align-self: end property, but it did not work. Can someone please assist? .card { border: 1px red solid; width: 450px; height: 150px; border-radius: 5px; ...

Combining Java for the back-end and JavaScript for the front-end: a comprehensive guide

Looking for advice on integrating a Java back-end with a JavaScript, HTML 5 front-end in my web application. Any tips on passing content between the two languages? ...

Learn how to display JSON data sent from the server on a webpage

I'm just starting out with jquery. I have an api called '/categories' that gives me a json object of categories. The response looks like this: [ { name: "Laptop deals", slug: "laptop-deals", imageURL: "image.jpg", id: 1 }, { name: "Fashion ...

I am searching for a tool in ThreeJS that functions similar to AxisHelper, possibly a Helper class or utility

While working with Three.js, I have come across many helpful Helper classes that greatly simplify displaying and modifying the scene. However, there is one particular tool that I am struggling to find again. It is similar to the AxisHelper, but it includes ...

Send error messages directly to the client side or retrieve status codes and messages

When responding to an AJAX request, encountering an app error like data validation failure can be tricky. How can we effectively communicate this to the user? 1. Returning a Status Code and Fetching Message with JS $.ajax(options).done(function(response) ...

Is there a way to customize the ::selection style using mui createTheme?

I'm looking to globally change the color and background color of ::selection in my app. Can anyone advise on how to achieve this using createTheme()? ...

After refreshing the page, RouterLinkActive in Angular 6 fails to work

Scenario In my application, there is a menu with various items. The selected item is distinguished by adding the selected class to it, which changes its appearance. https://i.sstatic.net/JEPHH.png Problem While navigating between routes works smoothly, ...

Console output shows that the function results in undefined

When I pass a string parameter to a function, I expect the console to display "reff", but it is showing "undefined" instead. Here is the code snippet: var _ref; function foo(_ref='reff') { var bar = _ref.bar; return console.log(bar); } foo ...

Is there a benefit to using middlewares instead of the standard built-in functions in Express.js?

Express.js offers a wide range of middlewares that replace built-in functions. One example is body-parser, which parses HTTP request bodies, replacing the built-in function express.bodyParser. body-parser replaces the built-in function express.bodyParse ...

Combining Bootstrap navbar with React Router for seamless navigation

I am new to using React and I am having trouble linking pages with Bootstrap navigation. I am attempting to use React Router DOM to navigate to different pages on click, but the app is not compiling because BrowserRouter is not being imported properly. I c ...