Function for calling a CSS callback with jQuery

I am currently working on enhancing my search bar using jQuery, and I am also looking to hide the navigation links.

Here is a snippet of the jQuery code I have been using. The code functions properly when focused.

$(".searchBox input").focus(function(){
    $("#navlinks").css('display','none');
   $(this).css({'width':'200px','-moz-transition':'width 0.5s ease-out','-webkit-transition':'width 0.5s ease-out','transition':'width 0.5s ease-out'});
});

 $(".searchBox input").focus(function(){
       $(this).css({'width':'100px','-moz-transition':'width 0.5s ease-out','-webkit-transition':'width 0.5s ease-out','transition':'width 0.5s ease-out'});
$("#navlinks").css('display','block');
    });

The second function also works properly, except that it displays the content before the animation is complete.

Therefore, I am looking for a way to ensure that

$("#navlinks").css('display','block');
is only executed once the animation is complete.

If anyone knows how to achieve this, I would greatly appreciate the help.

Thank you

Answer №1

The .css() method does not include a callback function, but the .animate() method does. By setting the time to 0 and using animate, you can achieve the desired effect.

$(".searchBox input").on('focus',function(){
   $(this).animate({width:100,mozTransition:'width 500ms ease-out',webkitTransition:'width 500ms ease-out',transition:'width 500ms ease-out'},0,function(){
       $("#navlinks")
            .delay(500)
            .css({display:'block'});
   });
});

Edit: I have also included the necessary delay as suggested by eicto. (Thank you eicto)

Answer №2

Given that you are aware of the duration of your animations, why not consider using setTimeout() following a CSS modification? It seems that your animation lasts approximately 0.5 seconds. By specifying the same duration in milliseconds, you can smoothly execute your "callback" at the conclusion of the animation.

 $(".searchBox input").focus(function(){
       $(this).css({'width':'100px','-moz-transition':'width 0.5s ease-out','-webkit-transition':'width 0.5s ease-out','transition':'width 0.5s ease-out'});
       setTimeout( function() {
            $("#navlinks").css('display','block');
       }, 500);
  });

Answer №3

If you're looking for a smooth animation effect, I suggest using the .animate() function in jQuery like this:

$(".searchBox input").focus(function(){
    $(this).animate({
        'width': '100px'       
    }, 500, function() {
        $("#navlinks").css('display', 'block');
    });
});

This code snippet is compatible with all browsers and ensures that the #navlinks command will execute only after the animation is finished. Remember, the 500 value represents the duration of the animation in milliseconds, so feel free to adjust it to your liking.

For more information on the .animate() method, you can refer to the documentation here: http://api.jquery.com/animate/

Answer №4

I found a different approach when I encountered a similar situation:

$('.something').one("webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend",
    function(event) {
        // Executing actions after the transition ends

 });

This code snippet demonstrates how to perform tasks after a transition has completed.

More information can be found at:

Best regards,
Lars

Answer №5

Click here to learn about the concept of the transitionend event and how it can be implemented.

CSS:

#sample {
    width: 100px;
    border: 1px solid black;
    -webkit-transition: all 1s;
    -moz-transition all 1s;
    transition all 1s;
}
#sample.expanded {
    width: 200px;

}

JS:

var sample = $('#sample');
 sample.bind('transitionend webkitTransitionEnd oTransitionEnd', function () {
        $('body').append('<div>END!</div>');
    })
$('button').click(function () {
    sample.toggleClass('expanded');
});

Check out the DEMO

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

Explore within the <li> element using jQuery

Need assistance on how to search within the li element. The li list consists of employee names in the format [surname,firstname]: Venkata,Anusha Raju,Suma Here is the HTML CODE: <input type="text" id="comboBox" placeholder="Search.." /> < ...

Change the colors of a dynamic row in an HTML table using various options

I have successfully implemented a dynamic table using HTML and JavaScript. However, instead of applying alternate row colors, I want to assign a unique color to each row. How can I achieve this? <!DOCTYPE HTML> <html> <head> ...

The html carousel displays stacked images instead of scrolling

I have been staring at this code for what feels like an eternity, trying to figure out why it's only displaying stacked pictures instead of a functioning carousel. Perhaps I overlooked something crucial. Could someone please lend a hand? My code is pr ...

Tips for utilizing maps in a react component within a Next.js application

I received an array of data from the backend that I need to display on a React component. home.js import Head from "next/head"; import Header from "../src/components/Header"; import * as React from 'react'; import { styled } ...

Looking to encode/decode a JSON response in order to transfer it to a different webpage

Currently, I have a website application where I am required to pass a JSON response (in string format) across the site. To achieve this, I have been using a hidden type value and passing it upon the submission of a link/button which subsequently triggers a ...

Executing a controller method in Grails using JavaScript

When working in a Grails view, I find myself needing to execute a JavaScript method to retrieve certain information. To achieve this, I have set up a submit action as shown below: <input type="submit" name="submit" class="submit action-button" value="G ...

What is the best way to apply a class to the initial div using jquery?

I have the following HTML code: <div class="main"> <div class="sub"></div> <div class="sub"></div> <div class="sub"></div> </div> <div class="main"> <div class="sub"></div> <di ...

Display every div element if none of the links have been clicked

On my webpage at url.com/yourfirstpage/, all div elements are hidden by default with a display:none property. If we specifically target #sec1 by going to url.com/yourfirstpage/#sec1, only sec1 is displayed while the others remain hidden. But what if we acc ...

Utilizing jQuery for displaying or hiding list elements

To view all the code, click on this link: http://jsfiddle.net/yrgK8/ A section titled "news" is included in the code snippet below: <ul id="news"> <li><p>asfdsadfdsafdsafdsafdsafdsafdsafdsa</p></li> <li>&l ...

Activate the button solely when the text field has been populated without any spaces

Searching for a solution to my query, but all the suggestions I've encountered don't consider spaces as valid input. In the join function I have, the button should be disabled if the user enters only spaces. A requirement is for actual text inpu ...

Utilizing Ajax looping to generate dynamic HTML content with Bootstrap tabs

I am looking for a way to fetch multiple JSON files and display the data from each file in separate Bootstrap 3 Tabs. I understand that the getJSON function does not wait for completion before moving on, but I need help with using callbacks in situations ...

Steps to create spaces between the bootstrap cards

Just diving into Bootstrap and attempting to incorporate images as cards, I encountered a challenge where the cards were piling up one after another without any spaces between them. Below is the code snippet utilizing Bootstrap4: <body> <div class ...

Is it possible to deploy a build across various website subdomains without altering user data?

Currently, I am in the midst of developing a project for a client where I am responsible for both the front end and back end components. After much consideration, I have opted to use Remix due to my familiarity with React and proficiency in JavaScript/Type ...

In the Vercel production environment, when building Next.js getStaticPaths with URL parameters, the slashes are represented as %

I've encountered an issue while implementing a nextjs dynamic route for my static documentation page. Everything works perfectly in my local environment, and the code compiles successfully. However, when I try to access the production URL, it doesn&ap ...

The press of the Enter key does not trigger the button

I'm facing an issue with a form that has just one field for user input and a button that triggers some jQuery to hide the login form when clicked. However, pressing enter after entering text causes the page to refresh... I'm starting to think th ...

Tips to detect a specific animation completion on an element?

How can I ensure that a specific animation ends when multiple animations are triggered on an element? My scenario involves an overlay song list that appears when a list icon is clicked. The challenge lies in closing the menu smoothly. I have implemented a ...

Add middleware to one individual store

When working with Redux, it is possible to create middleware that can be easily applied to the entire store. For example, I have a middleware function called socketMiddleware that connects to a socket and dispatches an action when connected. function sock ...

Encountering a 404 error while trying to refresh the page in a React App hosted on Her

After deploying a React App on Heroku, I encountered a frustrating issue: every time a page is refreshed, a 404 error appears, such as: Cannot GET /create In my search for a solution, I came across a related issue: Question about 404 with React Router ...

Utilizing tables for inquiries in email communication

Currently tackling a basic mailer with html. It seems like tables are recommended and inline styling is the safer route. However, I'm encountering an issue where there's a mysterious space when setting up my td and I can't seem to pinpoint ...

Displaying Date in Angular 2 Application with Proper Formatting

I'm currently working on formatting the date pipe in my Angular application to display correctly when used within an input template. Originally, without the date formatting, my code looked like this: <input class="app-input" [readonly]="!hasAdminA ...