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

An effective method for parsing nested JSON objects in ajax with DataTables

Currently, I am in the process of transitioning to the DataTables Table plug-in for jQuery. I have been facing difficulties trying to make the below JSON Results compatible with DataTable's Object data source. Despite attempting various methods inclu ...

Modify an element upon clicking the mouse on an image

I am looking to dynamically change the paragraph element with className="details" to an editable input field when a user clicks on the image with className="edit-icon" within the same grid container. How can I achieve this functionality ...

Explore a different page containing interactive ajax components

I am in the process of setting up my website and I would like to create a link from page1 to page2: Page2 consists of a submenu that provides information in this format: $("#element").click(function(){ $("#another_element").load("page3.html"); ...

What is the best way to add border-radius to an image while incorporating padding?

I am facing an issue with images that have white padding at the top and bottom. Please refer to the attached image. Whenever I try to apply the border-radius property to these images, the edges appear distorted. Is there a way to resolve this problem wit ...

Utilize the fetch function to showcase information retrieved from a specific endpoint on a webpage using Javascript

Hey there, I have a Node server with an http://localhost:3000/community endpoint. When I make a GET request to this endpoint, it returns information about three different users in the form of JSON objects. [ { "avatar": "http://localhost:3000/avatars ...

What is the optimal approach: Extracting HTML from a jQuery response?

Just wondering how people handle this situation...if a user adds something to a list and, when it's done, triggers the following ajax code to update the .user-stream-list $.ajax({ url: "user-stream-list.php", success: function(data){ ...

showing the chosen item in a Bootstrap dropdown [limited to the first menu option and using the attr() method]

Is there a way to dynamically display the selected menu option using the bootstrap drop down? Initially, I was able to select the first menu option and apply it to the bootstrap drop-down button. However, I encountered an issue where I cannot change the ...

Utilizing jQuery to modify the text output from an input form

Check out the preview site at . It's a test version before launching on a separate domain. Hello, I need to customize the error response for a CRM contact form integrated into Wordpress with the help of StackOverflow. The form is connected via JavaSc ...

Understanding the relationship between CSS height and line-height can help developers create more

Is there a way to use CSS to set the height of a box based on its own line-height or its parent's line-height? This feature would make it much simpler to create text areas that are a specific multiple of lines, for example, displaying exactly three l ...

Accessing Angular templates scope after the document is ready using angular.element()

I am currently learning Angular and experimenting with the Symfony2 + AngularJS combination. I am facing a specific issue that I need help with: Within my index.html file, I have the following script: <script> global = {}; $(document).ready ...

What is the best way to incorporate the .top offset into a div's height calculation?

Looking to enhance the aesthetic of this blog by adjusting the height of the #content div to match that of the last article. This will allow the background image to repeat seamlessly along the vertical axis. I attempted the following code: $(document).re ...

Utilize the PHP variable HTTP_USER_AGENT to identify and analyze the user's browser

As I embark on creating a webpage, my goal is to have it display different content based on the user's browser. The SERVER [HTTP_USER_AGENT] variable initially seemed promising for this purpose, but upon inspecting the page in Chrome, I encountered: ...

After attempting to refresh the webpage with the F5 key, I noticed that the jQuery progress bar was not functioning properly. Additionally, the webpage failed to display any

Trying to implement a web loading bar using jQuery on my website was initially successful, but I encountered an issue when reloading the page with F5. The progress bar would not work and the webpage displayed only a white background. Below is the code snip ...

Validation in PHP and Javascript is only partially effective

I encountered an issue with my form validation setup that utilizes JavaScript, Ajax, and PHP. While the errors are correctly displayed when the form is filled incorrectly, I am unable to submit the form even if there are no errors. Clicking the submit butt ...

Struggling with implementing responsive mobile buttons that stack in a column? Here's the solution

My content is nearly responsive on all screen sizes, but I'm having trouble getting the buttons to stack neatly in a column. Can anyone provide suggestions on how to fix this issue? You can view the current progress below. Thank you in advance for any ...

Issue with the functionality of max-height in a CSS grid container

Update: After receiving clarification from @onkar-ruikar, I realized that my original problem was quite misunderstood. While I still haven't figured out how to properly handle the cyclic dependencies issue, I decided to address it separately. As a res ...

Calling jqXHR.abort() does not effectively cancel the request; instead, it can potentially render the browser unresponsive

I am encountering an issue with my jQuery dialog while making ajax calls. I need to be able to cancel the current request when the dialog is closed. To facilitate this, I have set up a global variable called currentRequest and assigned each ajax request to ...

The onblur event is triggering prior to the value being updated

There are two input fields within a <form> element. I am trying to retrieve the value of one input field (dpFin) once it has been changed. The issue is that when I attempt to get the new value inside the event using var endDt = document.getElementByI ...

JavaScript Calculator experiencing difficulty with adding two numbers together

I've been working on developing a calculator using HTML and JavaScript, but I'm facing an issue when trying to add two numbers together. Strangely enough, when attempting to calculate 1 + 0, I get the result of 512, and for 1 + 1, it returns 1024 ...

Issue with mobile.changePage() function not executing as expected

I created a basic code that generates a "Splash screen". For storing my data, I am utilizing localstorage. When I first load it, I retrieve data from a URL and I am able to navigate to different pages using $.mobile.changePage(). However, if the data is a ...