How can I toggle the visibility of an item on click using jQuery?

I need to toggle the visibility of a specific div when clicking on an anchor. Here is the code I have written for this:

jQuery('.mycart').click(function(e){

            e.preventDefault();
            var target = jQuery(".basket");

            if(target.is(':visible'))

                jQuery('.basket').css('cssText', 'display: none !important');

            else

                jQuery('.basket').css('cssText', 'display: block !important');
        });

jQuery(document).mouseup(function (e){
        var container =jQuery(".basket");

        if (!container.is(e.target) // if the target of the click isn't the container...
            && container.has(e.target).length === 0) // ... nor a descendant of the container
        {
            container.hide();
        }
    });

html:

<a class="cart mycart" href="#">My Cart</a>
<div class="basket">
<span class="callout-arrow"></span>
<div class="basketcount"><span>5</span></div>
   <button type="button" class="checkoutbtn">checkout</button>
</div>

The issue I am facing is that even though the div shows onclick, it does not hide again. This is due to the second function which hides the container when the user clicks outside of it.

Answer №1

Your code is effective. I have also included two additional solutions for you to consider:

jQuery('.mycart').click(function(event){

    event.preventDefault();
    $(".basket").slideToggle(800);
});

Visit this link for more examples.

I have left one solution commented out, so feel free to experiment and choose the one that suits your needs best.

Answer №2

Implement this code within your jQuery function:

$('.store').on('click', function() {
   if($('.cart-items').is(':visible')) {
       $('.cart-items').hide();
   }
  else {
       $('.cart-items').show();
  }
})

Answer №3

By implementing a modification in the code, I managed to find the solution. Specifically, I added a condition to prevent the mouseup() function from hiding the container when the clicked target is the anchor with the class of '.mycart'. This change allows the click() function of the anchor to be executed as usual and hide the container if it is currently displayed. Below is the updated jQuery code:

jQuery('.mycart').click(function(e){

        e.preventDefault();
        var target = jQuery(".basket");

        if(target.is(':visible'))
            jQuery('.basket').css('cssText', 'display: none !important');

        else
            jQuery('.basket').css('cssText', 'display: block !important');
    });

    jQuery(document).mouseup(function (e){
        var container = jQuery(".basket");

        if (!container.is(e.target) // if the target of the click isn't the container...
            && container.has(e.target).length === 0 && !jQuery('.mycart').is(e.target)) // ... nor a descendant of the container or .mycart anchor
        {
            container.hide();
        }
    });

Answer №4

Give this a try…

jQuery('.mycart').click(function(e) {
    e.preventDefault();
    var target = jQuery('.basket');
    if(target.is(':visible')) {
        jQuery('.basket').css('cssText', 'display: none !important');
    } else {
        jQuery('.basket').css('cssText', 'display: block !important');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a class="cart mycart" href="#">My Cart</a>
<div class="basket">
    <span class="callout-arrow"></span>
    <div class="basketcount"><span>5</span></div>
    <button type="button" class="checkoutbtn">checkout</button>
</div>

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

Adding double quotes, where they haven't been added yet

I am trying to work with the following string (Very strong=="Very strong"?100:(Very strong=="Above Average"?75:(Very strong=="Average"?50:(Very strong=="Below Average"?25:(Very strong=="Cannot determine"?0:(Very strong=="Poor"?0:0)))))) My desired outpu ...

Screen resolution for the background image on the banner

I'm currently working on a website that can be found at this temporary link: The main banner of the site features a background image with fading text, which looks great on standard desktop screens. However, when viewed on wider screens like 1600x1200 ...

Guide on resolving the issue of disabled button's tooltip not appearing upon being hovered over

I have a button that looks like this: <a data-toggle="tab" href="#part4" class="btn btn-info tabcontrol mainbutton col-2 offset-8 disabled" id="part3to4" title="Please acknowledge the checkbox before going next" data-toggle="tooltip" data-html="true" d ...

svg icon hover effect not displaying color properly

Seeking expertise in incorporating social media icons with a hover effect to turn purple. Encountering an issue where the entire circle of the icon is mistakenly being painted on hover. Refer to the screenshot of the current outcome and desired result. Wo ...

Implementing a fixed search bar in Angular for a dropdown selection using mat-select

I'm currently utilizing a mat-select widget from Angular-Material in my application To enhance user experience, I am adding a search bar at the top of the select dropdown for filtering options: <mat-select placeholder="Select a store" ...

The Tab style in Mobile Angular UI does not get applied correctly when nested within an ng-repear

While working on a tabbed control with mobile-angular-ui (), I encountered an issue when trying to generate the tabs dynamically. Initially, everything looked good with the following code: <ul class="nav nav-tabs" ui-state='activeTab' ui-def ...

What is the best way to transfer information between two React.js files?

I am currently finding it inefficient to pass data from App.js to another .js file within React by constantly reading and writing from local storage. I would prefer to only retrieve data from local storage once when the App.js component mounts. App.js: ...

"Create a div element with resizable capabilities, similar to a

Is it possible to resize elements like divs in browsers without using jQuery or other libraries like draggable or resizable? I know text-areas can be resized by default, but I'm curious if this functionality can be extended to other elements through p ...

The ng-repeat-start feature is not functioning properly across different levels

I am attempting to utilize the ng-repeat-start directive in order to construct a table that resembles the following: https://i.sstatic.net/Qgc91.png The structure of my JSON data is as follows: [ { "name": "Chapter 1", "parts": [ { ...

trouble with react-table's default height and flexible design

I am facing an issue with my React table configuration. I have set up scrollable columns and header following a similar example here: https://codesandbox.io/s/kowzlm5jp7?file=/index.js:281-310 In the table styles, I have specified a height like this: ...

Revamping JavaScript Code for Better Performance

I've been working on a lot of code in the backend section of my website, mainly dealing with CRUD operations using AJAX calls. Do you have any suggestions on how I can refactor these functions into more generic ones or possibly create classes instead ...

Utilizing jQuery to dynamically add a class based on specific criteria

I need help with the following scenario: <span class="dateStart" val="0">2016-09-16</span> | <span class="dateStart" val="1">2016-09-15</span> | Can anyone guide me on how to use jQuery to add a selected class to the <span> ...

Submitting a form and using Ajax to upload an image

Is there a way to submit an image file to php using ajax without assigning the file to a variable with onchange event? I've tried triggering the request on submit click, but keep getting the error message: "cannot read property 0 of undefined." <ht ...

Filling out the form will automatically direct you to the text input section

I'm trying to figure out if I can create an input box in HTML that directs the user to a specific HTML file based on the word they enter. For example, if they type "Doctor", it would redirect them to the page doctor.html. This is for a school project ...

Can a PHP variable be passed along with a div ID in any way?

I am attempting to transfer a PHP value through the "href" attribute from one div to another. While we can achieve this between pages, like so: <a href="somepage.php?id=<?php echo $id;?>"></a> Is there a way to accomplish this using an ...

Character count in textarea does not work properly when the page is first loaded

As English is not my first language, I apologize in advance for any grammar mistakes. I have implemented a JavaScript function to count the characters in a textarea. The code works perfectly - it displays the character limit reducing as you type. However, ...

Attempting to update an AJAX field with the returned value, but it only updates after clicking away from it

Image of form utilizing AJAX & JS The current setup involves a maintainer that uses AJAX to update the "Calc" field in response to a number entered in the "Order No" field. The issue is that the "Calc" field does not update immediately after typing in the ...

Using an onClick event along with jQuery to change the CSS class style of another div

After searching extensively without success, I decided to register and ask my first question here. Hopefully, someone can provide a solution: My goal is to create a set of five buttons (divs) with onClick events that will show five different divs. I' ...

Within jQuery lies the power to perform multiplication operations effortlessly

I'd like to accomplish this using jQuery: var menuItems = document.getElementsByTagName("li"); for (var k = 0; k < menuItems.length; k++) { if (menuItems[k].className == "menu") { var child = menuItems[k].firstChild; if ...

Ways to interact with similar dynamic controls in Javascript

I have an aspx page with a Select box control: <select name="selViewPerPage" id="selViewPerPage" style="width:30px"> To ensure consistent styling across all browsers, I am replacing this html control with a dynamic select box using "selectBox.js". ...