Functionality of JQuery .show() working properly, however, encountering issues with .hide() functionality

My goal is to create a custom dropdown select box using JavaScript, as it needs to incorporate images. The issue arises when I click on the input box that triggers the jQuery code to open the dropdown list:

$('#ratingDropdownContainer').on('click', function() {
    if ($('#dropdownListContainer').css('display') == 'none') {
        $('#dropdownListContainer').show();
    }
})

Initially, everything works perfectly fine. But the problem occurs when a user selects an option and the .hide() method fails to work. Despite trying various solutions such as ensuring proper document load by wrapping in $(document).ready(function(), verifying that JavaScript recognizes the display property correctly (confirmed with console.log("okokoko");), loading jQuery before JS file, attempting vanilla JS alternatives - none have successfully resolved the issue. It's perplexing why .show() works while .hide() fails. Any insights or assistance would be greatly appreciated.

Thank you!

JS:

$('#ratingDropdownContainer').on('click', function() {
    if ($('.dropdown-list-container').css('display') == 'none') {
        $('.dropdown-list-container').show();
    }
})

$('.avg-rating-select').on('click', function() {
    var selectedRatingImg = $(this).find('img').prop('outerHTML');
    var selectedRatingText = $(this).find('p').prop('outerHTML');

    var newDiv = $("<div>" + selectedRatingImg + selectedRatingText + "</div>");
    newDiv.addClass("rating-selected-container");

    if ($('.rating-selected-container').length) {
        $('.rating-selected-container').replaceWith(newDiv);
    } else {
        $('.rating-dropdown-inner-text p').replaceWith(newDiv);
    }
    if ($('.dropdown-list-container').css('display') === 'block') {
        console.log("okokoko");
        $('.dropdown-list-container').hide();
    }
})

HTML:

<div class="col">
                          <div class="rating-dropdown-container" id="ratingDropdownContainer">
                            <div class="rating-dropdown-inner-text">
                              <p>Average Rating...</p>
                              <i class="bi bi-caret-down-fill"></i>
                            </div>
                          <div class="dropdown-list-container" id="dropdownListContainer">
                            <ul class="rating-dropdown">
                              <li class="avg-rating-select">
                                <img src="/media/main/5stars.png" alt="5stars" class="avg-rating-select-img">
                                <p class="avg-rating-select-text">5 Stars & Up</p>
                              </li>
                              <li class="avg-rating-select">
                                <img src="/media/main/4stars.png" alt="4stars" class="avg-rating-select-img">
                                <p class="avg-rating-select-text">4 Stars & Up</p>
                              </li>
                              <li class="avg-rating-select">
                                <img src="/media/main/3stars.png" alt="3stars" class="avg-rating-select-img">
                                <p class="avg-rating-select-text">3 Stars & Up</p>
                              </li>
                              <li class="avg-rating-select">
                                <img src="/media/main/2stars.png" alt="2stars" class="avg-rating-select-img">
                                <p class="avg-rating-select-text">2 Stars & Up</p>
                              </li>
                              <li class="avg-rating-select">
                                <img src="/media/main/1stars.png" alt="1stars" class="avg-rating-select-img">
                                <p class="avg-rating-select-text">1 Star & Up</p>
                              </li>
                            </ul>
                          </div>
                        </div>
                    </div>

CSS:

.rating-dropdown-container {
  display: block;
  position: relative;
  width: 100%;
  padding: .375rem .75rem;
  font-size: 1rem;
  font-weight: 400;
  line-height: 1.5;
  color: #212529;
  background-color: #fff;
  background-clip: padding-box;
  border: 1px solid #ced4da;
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  border-radius: .375rem;
  transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}

.dropdown-list-container {
    display: none;
    position: absolute;
    z-index: 100;
    border: 1px solid #ced4da;
    border-top:none;
    border-top-left-radius: 0;
    border-top-right-radius: 0;
    border-bottom-left-radius: .375rem;
    border-bottom-right-radius: .375rem;
    width: 100%;
    margin-left:-12px;
    background-color: #fff;
}

.avg-rating-select {
    padding-left: 8px;
    display: flex;
    align-items: center;
    cursor: pointer;
}

(Please note: This is a Django project utilizing Bootstrap for styling)

Answer №1

It seems that the issue could be related to event propagation or event delegation. To resolve this, make sure to prevent event propagation when clicking on the options within the dropdown by using event.stopPropagation() like so:


$('#ratingDropdownContainer').on('click', function() {
    if ($('.dropdown-list-container').css('display') == 'none') {
        $('.dropdown-list-container').show();
    }
})

$('.avg-rating-select').on('click', function(event) {
    event.stopPropogation(); // Corrected spelling here.
    var selectedRatingImg = $(this).find('img').prop('outerHTML');
    var selectedRatingText = $(this).find('p').prop('outerHTML');

    var newDiv = $("<div>" + selectedRatingImg + selectedRatingText + "</div>");
    newDiv.addClass("rating-selected-container");

    if ($('.rating-selected-container').length) {
        $('.rating-selected-container').replaceWith(newDiv);
    } else {
        $('.rating-dropdown-inner-text p').replaceWith(newDiv);
    }
    if ($('.dropdown-list-container').css('display') === 'block') {
        console.log("okokoko");
        $('.dropdown-list-container').hide();
    }
})

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

What would you name this particular element?

I want to create a unique slider design but I'm unsure where to begin or how to search for information because I don't know the correct terminology. Does this type of slider have a specific name? I heard about Marquee, but that seems like someth ...

Tips for creating collapsible panel groups that close automatically when another panel is opened?

Looking at the code snippet provided, it appears that both panel-groups can be simultaneously open. Is there a way to make one collapse when the other is clicked? <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1 ...

The DIV element fails to encompass all of its content

There seems to be an issue with the only div element on my page. It's covering the middle of the page, but I managed to make it extend all the way down using CSS tweaks. However, there is a problem - the video inside the div is overflowing: Below is ...

What is the best way to retrieve an attribute from a different table using a many-to-many relationship in Django?

As a newcomer to Django, I have a question that might seem basic. My goal is to retrieve the selling price and other relevant data from the product table using the order table. views.py def createOrder(request): form = OrderForm() if request.metho ...

Enhancing Security and Improving Performance with Subresource Integrity and Cache Busting Methods in

I am in the process of integrating Subresource Integrity and cache busting for my application's static assets like stylesheets and JavaScript files. Currently, I am using PHP with Twig templates. While I am aware of tools available for generating has ...

Clicking on an item will now automatically remove it from the selection, rather than requiring you to click on a specific

Is there a way to customize the design of select2 items in a multi-select box so that users can easily remove selected items by clicking anywhere on the button, rather than just the small "cross" icon on the left-hand side? Refer to the image; instead of n ...

Tips for optimizing text retrieval in headless mode with Selenium to avoid unnecessary duplicate runs

My current task involves scraping specific parts of the materials listed on the Zara website. The process I am following includes the following steps: step#1 - opening the website in headless mode step#2 - clicking the "see more" button to reveal the p ...

Combining Webpack 4 with Vue and jQuery

I am currently working on a jQuery project and I am looking to migrate it to Vue. Assembling a project with webpack 4, I am struggling to find a successful method for integrating jQuery into Vue using this version of webpack. If anyone out there can prov ...

Vercel enables faster PAAPI transactions through Edge Caching

When working on a Nextjs site hosted on Vercel and making a call to Amazon's paapi, it's important to keep in mind the limitations imposed by Amazon on the number of transactions allowed per second and per day. The approach I'm taking involv ...

I want to find out how to use Chrome Dev Tools to view and inspect all elements simultaneously in order to understand the page layout better. Can someone provide an example?

Can someone help me figure out how to view and inspect all the elements at once in Chrome Dev Tools to understand the page layout? (Example linked below) Thank you! 'View All' Chrome Dev Tools Additional Information: I captured this screenshot ...

Enhance React component props for a styled component element using TypeScript

Looking to enhance the properties of a React component in TypeScript to include standard HTML button attributes along with specific React features such as ref. My research suggests that React.HTMLProps is the ideal type for this purpose (since React.HTMLA ...

Is it possible for me to access both the previous and current values from the watcher within the mounted lifecycle?

I want to utilize this.prev and this.curr in the mounted cycle, incorporating the updated changes from the watcher. How do I access these current values in the mounted cycle? <template> <component :is="'nuxt-link'" : ...

What is the method for extracting CSS class names and storing them in an array using PHP?

Hey there, I have a bunch of CSS code and I'm looking for a way to extract only the names of the CSS classes without the unnecessary characters and values, and then store them in an array using PHP. For Example: .dungarees { content: "\ef ...

VueJS and Vite: Encountering an unexpected character '�' while attempting to import files that are not JavaScript. Keep in mind that plugins are required for importing such files

I'm puzzled by the error message I'm receiving: [commonjs--resolver] Unexpected character '�' (Note that you need plugins to import files that are not JavaScript) file: /..../..../WebProjects/..../ProjectName/node_modules/fsevents/fse ...

Smooth Div Scroll experiencing display issues

Trying to integrate the smooth div scroll, specifically the "Clickable Logo Parade" found at: Successfully implemented it on a blank page exactly as desired, but encountering issues when inserting it into the current layout. Could something be causing int ...

Modify button text with javascript based on the body's class selection

I successfully implemented a dark and light theme on my website following this helpful guide. The two color schemes are defined as classes in CSS and dynamically applied to the body element using JavaScript. The script automatically selects the theme based ...

add the AJAX response to the specified div element

I'm currently using an ajax call to retrieve movie data from the IMDb API for 'The Shawshank Redemption'. My goal is to display this data within the designated div element. <div id="movie-data"></div> Here's my current Jav ...

Issue encountered while attempting to install lxml on Mac (Mavericks) in order to utilize it with Django 1.5

cc -fno-strict-aliasing -fno-common -dynamic -arch x86_64 -arch i386 -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -fwrapv ...

After my jQuery functions are executed, my CSS rules are loaded

Struggling with the communication between CSS and jQuery, I find myself torn. In CSS, my rules are often very specific, like this: div#container > div#contentLeft { //Code here } However, when I add jQuery to spice up my site, the CSS rules seem to ...

simple query about AJAX using jQuery

Testing out ajax for the first time, please be patient. <html> <script type="text/javascript" src="jquery-1.4.2.min.js"></script> <script type="text/javascript"> $(document).ready(function() { function greet() ...