Animating the height with jQuery can result in the background color being overlooked

For those curious about the issue, check out the JSFiddle. There seems to be an anomaly where the background of the <ul> element disappears after the animation on the second click. Oddly enough, even though Firebug shows that the CSS style is being applied, the red background just won't stay visible. Any idea what could be causing this hiccup?

UPDATE: The red background vanishes upon clicking any <li>.

The key snippets of code are highlighted below:

HTML

<div style="position: relative;" class="selectCover">
    <button>Transfer</button>
    <ul style="position: absolute; left: -34.5px; top:-15px; display:none;" value="0040346781">
        <li class="selected">CANCEL</li>
        <li data-branch="SJ">SJ</li>
        <li data-branch="SYI">SYI</li>
        <li data-branch="SZ">SZ</li>
        <li data-branch="SY">SY</li>
        <li data-branch="SE">SE</li>
        <li data-branch="SG">SG</li>
        <li data-branch="SD">SD</li>
    </ul>
</div>

CSS

.selectCover ul{
   background: red;
}
li.selected{
    background: green;
}

jQuery

$('.selectCover').click(function(){
    $(this).find('ul').slideDown(100,function(){
        $(this).mouseleave(function(){
            $(this).slideUp(100);
            $(this).off('mouseleave');
        });
    });
});

$('.selectCover li').click(function(e){
    $.post('x').done(function(){
        console.log($(e.target).attr('data-branch'));
        $(e.target).parent().attr('currsel',$(e.target).attr('data-branch'))
    });
    $(e.target).parent().animate({height : 0});
});

Answer №1

Make sure your javascript is structured properly:

$('.selectCover').find('button').click(function(){
    $(this).parent().find('ul').slideDown(100,function(){
        $(this).mouseleave(function(){
            $(this).slideUp(100);
        });
    });
});

$('.selectCover li').click(function(e){
    $.post('x').done(function(){
        console.log($(e.target).attr('data-branch'));
        $(e.target).parent().attr('currsel',$(e.target).attr('data-branch'))
    });
    $(this).parent().slideUp(100);
});

Upon review, there are 2 issues with your code:

The click events were conflicting as both listeners were triggered when clicking an "li" element. This stemmed from having a click event on the entire container and individual "li" elements. Clicking on an "li" element would inadvertently trigger the container's click listener again.

The second issue was setting the height of the element to 0. The slideDown() method did not update the DOM height correctly, resulting in a background with 0 height being displayed.

I have adjusted the first click event to target the button specifically to prevent it from triggering when clicking an "li" element.

Check out your updated fiddle here:

http://jsfiddle.net/64zUr/

Answer №2

Make changes to the code below.

You attempted to use hide or slidup, but encountered issues. To solve this problem, you utilized

$(e.target).parent().animate({height : 0});
, which resulted in removing the background color.

When an item is selected from the list, the click event propagates to the selectCover div causing it to reappear when hiding or sliding up.

Please refer to the modified code below where both problems have been resolved, and visit jsfiddle for more details.

$('.selectCover li').click(function(e){
    e.stopPropagation(); // prevent propagation of the click event to the parent div
    $.post('x').done(function(){
        console.log($(e.target).attr('data-branch'));
        $(e.target).parent().attr('currsel', $(e.target).attr('data-branch'))
    });
    $(e.target).parent().slideUp(100); // removed animation to retain background color, using slideup only
});

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

The datepicker feature has been programmed to only allow past or present dates

I've integrated a date picker on a website like so: <input type="text" id="popupDatepicker" placeholder="Select Date" name="from_date" class="input" size="50" /> Here's the script being used: $(function() { $('#popupDatepicker&apos ...

Detecting changes in checkbox states

In my current scenario, I have a section of the screen that can be shown or hidden depending on whether a checkbox is checked. The user can change the state of the checkbox manually or programmatically. The challenge lies in detecting this change and upda ...

Using jQuery to dynamically populate input values within a table that contains multiple rows with text from their respective siblings

My table contains many columns (exact number varies). $('.action-checkbox').val( $(this).parent().parent().find(".col-record_id").first().text().trim() ) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery ...

The functionality of IE's .attr disabled feature appears to be ineffective

My function to check if a product is available overnight is not functioning properly in Internet Explorer, although it works fine in other browsers. function checkOvernight() { id = $_2("[name='product']").val(); if(id.length > 0) { ...

Prevent selection of any dates before the most recent 2 days on the jQuery datepicker

Is there a way to restrict the date-picker from displaying past dates, except for the last 2 dates? <link href="Content/jquery-ui-1.8.23.custom.css" rel="stylesheet" /> <script src="Scripts/jquery-1.8.1.min.js"></script> <script src=" ...

Setting the z-index to place an absolutely positioned element below a relatively positioned one

I am currently facing a challenge where I need to position an element under another one that has already been relatively positioned. The blue box must remain relatively positioned due to specific constraints within the website development process. For bet ...

How can I change an element using jQuery's getElementById method?

My current setup involves using a web page as a server and an Arduino as a client. Whenever a specific mode is active, the Arduino sends the following code: <LED>on</LED> The server then adjusts its status accordingly based on this input. I ...

Resolve the 'undefined offset error' in Drupal Views Nivo Slider

After updating to the latest version of Drupal, I encountered an error while trying to use the "Views Nivo Slider" module. I keep seeing this error message: Notice: Undefined offset: 0 in template_preprocess_views_nivo_slider_view_nivo_sliderfields() (lin ...

Unleashing the power of specific dates with the angularJS datepicker directive

I am looking to develop a custom Datepicker directive using Angular JS, with the requirement of allowing only specific dates for selection by the user. For instance, I have a predefined list of numbers such as 1,3,5,7, and my goal is to make these particu ...

Utilize Bootstrap-Vue to ensure that an element expands to occupy the available space

In my Bootstrap-Vue application, I have set up the following hierarchy: <b-navbar.../> <b-container > <b-row align-v="center" style="min-height:100vh"> <b-col style="align-items:center"> <h1>404 Error&l ...

Troubleshooting problems with Jquery qtip ajax

I am currently attempting to send the value of an input box (specifically an IMDb link) to my imdbgrabber.php page in order to retrieve information about that movie and display it in a qtip box. EDIT: You can view the issue here. Hover over the images to ...

Incorporating JavaScript Object-Oriented Programming in PHP

As someone new to JS programming, I am tasked with developing a php web application that relies on ajax calls for all actions without reloading the page. While I have completed the php and JS code, I am struggling to understand what JS OOP entails. My coun ...

A guide on wrapping text within a Material-UI MenuItem

I am struggling to display text in a popover in multiple lines for UI reasons. I have tried updating the code but so far, I have not been successful. Any suggestions? <Popover anchorEl={target} open={open} anchorOrigin={{ horizontal: 'middle& ...

Expansive Child Division with Ample Margins

I'm currently working with a nested set of divs and I need the inner div to occupy the full width without extending beyond the parent div's margins. Despite trying to use max-width:100%, it hasn't been successful so far. For this particular ...

What is the most effective method for displaying two external web pages next to each other?

Looking for a solution to display an English Wikipedia article on the left side of the page alongside its Spanish version on the right side. Wondering if it's possible using HTML, JavaScript, AJAX, etc. I am aware that I could use iframes, but I woul ...

"Exploring the relationship between Javascript objects and the '

function createNewRobot(robotIdentifier) { this.id = robotIdentifier; this.components = new Array(); this.gatherComponents = function() { $.getJSON('specific/url', function(data) { for(index in data.responses) { this.part ...

Vanishing Submit Button with CSS

In my input submit button, I have included the following code: <input class="buttons" type="button" onclick="javascript:jQuery(xxxx)" style="font-size: 12px;" value="Invite to Bid"> Additionally, there is a CSS function that adds an elegant "Go" im ...

trouble with phonegap javascript ajax integration

I'm new to app development and I've been trying to create a mobile app using PhoneGap. I have a remote shared server that contains a MySQL table. My goal is to sign up a user, then send the data via JavaScript and AJAX to a PHP server page that w ...

Using radio buttons to toggle the visibility of a div element within a WordPress website

I am currently working on creating a WordPress page using the custom page tool in the admin interface. My goal is to have 3 radio buttons, with 2 visible and 1 hidden. The hidden button should be automatically checked to display the correct div (although ...

Equal height tabbed content design allows for a visually appealing and organized

I'm looking to create a tabbed menu that displays content in blocks, but I want each block to be the same height. I tried using padding and flexbox, but couldn't get it to work properly. Any suggestions on how to achieve this? .tab-pane { fl ...