Is it possible to animate the change in background color dynamically using jQuery?

I am struggling to implement a change/animate feature for the background color.

When I place the background script within the form submit event but outside the ajax call, I can briefly see the color change. However, once the remote content loads, the color disappears. It seems to be running too early. If I try placing it inside the ajax call, nothing happens at all.

$(function() {

    $(document).on("click", ".vote_button", function(event){

        var form = $(this).parent();
        var page = <?php echo json_encode($page) ?>;
        var target = $('.target');

        $(form).submit(function (event) {
            event.preventDefault();

            $(target).animate({
              backgroundColor: "#ccc"
            }, 'fast' );
            $(target).animate({
              backgroundColor: "#fff"
            }, 'slow' );

            $.ajax({
            type: "POST",
            url: "/forms/increase_rank.php",
            data: $(form).serialize(),
            success: function(response){

                $(function() {
                    getdata( page ); /* call the function onload */
                });

                function getdata(pageno){
                    var targetURL = 'search_results?page=' + pageno;   

                    $('#retrieved-data')
                    .html('<p id="ajax-load">testing</p>');        
                    $('#retrieved-data')
                    .load(targetURL)
                    .hide()
                    .fadeIn(1000);

                }

                $(form).html(response);

            }

            });
        });
    });
});

Answer №1

I have made modifications to enhance the overall usefulness and applicability of this answer.

It is important to note that the animate function requires the jQuery UI library to function properly.

<script src="//code.jquery.com/ui/1.11.0/jquery-ui.js"></script>

Below is a simple example using a static color:

HTML:

<div class="target">Change this background!</div>
<button>Change Background</button>

jQuery:

$(function() {
    $("button").on('click', function () {
        var $target = $('.target');

        $($target).animate({
            backgroundColor: "#4679BD"
        }, 'fast');
    });
});

Here is an example using dynamic colors (via color-picker):

JSFiddle

HTML:

<ul>
    <li class="black"></li>
    <li class="blue"></li>
    <li class="green"></li>
    <li class="purple"></li>
</ul>
<div class="target">This is some sample text.</div>

CSS:

ul {
    list-style: none;
    margin: 0;
    padding: 0;
}
li {
    width: 50px;
    height: 50px;
    margin-right: 10px;
    display: inline-block;
    cursor: pointer;
}
.black {
    background-color: black;
}
.blue {
    background-color: blue;
}
.green {
    background-color: green;
}
.purple {
    background-color: purple;
}
.target {
    margin-top: 50px;
    padding: 10px;
    background-color: #808080;
    color: #fff;
}

jQuery:

$(function () {
    $('li').on('click', function () {
        var $color = $(this).css('background-color');

        $('.target').animate({
            backgroundColor: $color
        }, 'slow');
    });
});

My Approach based on the Previous Question:

I had encountered several issues in my earlier attempts. In my code (on, click), I needed to ensure the form was submitted only after the AJAX call was completed. Rather than reloading the entire HTML, I opted to update only the content that had changed within the success callback.

$(function() {
    $( ".vote_button" ).on('click', function(event) {
        var form = $(this).parent();
        var target = $('.target');
        var voteCount = $(this).siblings('#vote_count');

        $(target).animate({
           backgroundColor: "#ccc"
        }, 'fast' );
        $(target).animate({
           backgroundColor: "#fff"
        }, 'slow' );

        $.ajax({
            url: "/forms/vote.php",
            type: 'POST',
            data: $(form).serialize(),
            success: function(data) {
                $(voteCount).html(data);
            }
            }).done(function() {
                $(form).submit(function(event) {
                });
            });
        return false;
    });
});

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 a <tr> tag to an HTML table using JQuery and AJAX in the context of Django framework step by step

I am currently navigating the world of Javascript, Jquery, and Ajax requests and I'm encountering a challenge with how my scripts are executing. My homepage contains a lengthy list of items (over 1200) that need to be displayed. Previously, I loaded ...

Ways to fix text overlap in a pill

Click here to view the code on jsBin I quickly copied HTML/CSS code to jsBin using a tool called SnappySnippet. I attempted various solutions, but none of them worked. The best option for me seems to be overflow: ellipses word-break: break-word; word-b ...

Leveraging jQuery to send data to MySQL with the click of a button

I am attempting to utilize jQuery in order to post a variable to a MySQL/PHP query. The button with the class="button" has the following code: $(".button").click(function(e){ e.preventDefault(); $.post("some.php", { var_today : <?php echo $new_var; ...

Regular Expression for jQuery to match both letters and numbers, including special characters

Is there a way to validate text input using a jquery regex that includes specific characters such as A-Z, a-z, 0-9, !, #, $, £ (preferably all currency characters), %, &, -, and _? If so, how can this be implemented? I have attempted to use the regex pa ...

How can we determine if the user is on a small device and utilizing flexbox with col-sm?

Is there a method to detect when the user is on a small device? I'm looking to adjust my navigation menu based on the size of the device, similar to the col-sm functionality. ...

Is there a way to lower just one border?

I need assistance with moving the .container div downward on my webpage. I attempted using (margin-top: 30px) and it worked, but unfortunately, it also shifted down the border of the (.container) along with the outline of .all. My goal is to have only the ...

Emphasize multiple anchor points

I am looking to highlight two sections of a page simultaneously. Here is what I currently have: <li class="langLI" style="list-style-type:none"><a href="/non-discrimination-and-language-assistance##French">| French Creole</a></li> ...

Setting up the Node.js file system for an Ionic project: A step-by-step guide

Seeking a solution to delete a Folder/File on the client side using javascript/jQuery/AngularJS1. After researching, I found that it can be done using Node.js as shown in this Sitepoint link. Now, I am unsure how to integrate Node.js fs(File System) with ...

The issue persists with the customized Bootstrap carousel featuring thumbnails

By combining http://codepen.io/srkimir/pen/mGbrf and http://codepen.io/transportedman/pen/NPWRGq , I successfully created a fading carousel with thumbnails similar to the one in http://codepen.io/kikibres/pen/gpZoXz . However, when trying to implement ...

Tips for implementing HTTP OPTIONS verb in an ASP.NET MVC/WebAPI application

After setting up an ASP.NET web application using an MVC 4/Web API template, everything appears to be working smoothly without any issues. Testing on Chrome and Firefox has been successful, and responses in Fiddler seem accurate. However, when attempting ...

Using Regular Expressions to eliminate any characters that are not directly adjacent to numbers (beside specific characters)

My function generates a result that looks like this: given output For comparison, consider the example string below: var string = '    111   1   1\n 1111111 1 \n   &nb ...

Using Jquery Ajax in Conjunction with Spring MVC

I recently encountered an issue while trying to make an ajax query from a Spring MVC JSP page. The request was successfully made and I could see the JSON response on the browser. $.get("${pageContext.request.contextPath}/xxx.htm", {x: y}, function(result) ...

Determine the complete number of rows associated with a Model in a JQuery Data Table

How can I retrieve the total number of rows in the result set while ensuring that the datatable search functionality also works? Currently, I am only able to display the first page of results after filtering using: OFFSET AND FETCH The code snippet below ...

I envision my home page being divided into two visually stunning full-screen sections, each taking up the entire height of the page

I am currently working with the code shown below. It successfully displays the first part in full height, regardless of resolution, but once I scroll to the second half, there is a large empty gap. How can I eliminate this gap and make the transition smoot ...

I aim to utilize vanilla JavaScript in order to remove the parent element of the button being clicked when the user interacts with it

My latest project involves a meme generator that allows users to input text and images, which are then combined to create a unique 'meme'. Each meme is assigned a unique ID and features buttons for deleting the meme upon hovering. To achieve this ...

Identifying Canvas Scrolling in iOS Safari using the Touchmove Event

I have encountered an issue while trying to detect scroll canvas from a touchmove event. It works perfectly on all browsers except for Safari. In Safari, the pageY and screenY coordinates of the touchmove event are not consistent. When I touch and move d ...

Verify if the username is already in use

Is it possible to validate the existence of a username while the user is entering it in a textbox or immediately after they finish typing? Should I use Jquery or Ajax for this task? Does anyone have any examples demonstrating how this can be done? ...

Establishing a minimum date based on the date selected in the earlier datepicker

My webpage features two date pickers, one for startdate and the other for enddate. The current setup requires that the second datepicker remains inactive until a change is made to the first one. The datepicker for enddate is initially set with the startin ...

What is the best way to make the div inside the table cells expand to fill the available space?

I'm having trouble making the inner divs within table cell divs expand and fit their parent div without overlapping the next cell below it. Check out the sandbox for reference I've outlined the areas in grey where I want the cells to be filled. ...

Display and conceal div with Jquery as you scroll to specific points on a mobile device

I'm looking to create a dynamic div that appears and disappears based on the user's scroll position. Here is what I have so far: $(document).scroll(function() { var y = $(this).scrollTop(); if (y > 200) { $('.float-contai ...