If the width of the element is equal to .. pixels, then carry out the

Currently, I have a search box that can show or hide by changing its width. Now, my goal is to add a class to the search icon when its width exceeds zero.

$("#search input").animate({width: "0px"}, 0);
var searchWidth = $('#search input').width();

$('#search i').click( function() {
    //Change the width (show it)
    var toggleWidth = $("#search input").width() == 150 ? "0px" : "150px";
    $('#search input').animate({ width: toggleWidth });

    //Make the search icon red
    if ( searchWidth > 0 ) {
        $("#search i").addClass("active");
    } else {
        $("#search i").removeClass("active");
    }
});

Initially, I tried using toggleClass, but encountered issues when clicking too quickly during the animation. This led me to the approach above...

//Change the width (show it)
var toggleWidth = $("#search input").width() == 150 ? "0px" : "150px";
$('#search input').animate({ width: toggleWidth });
//Make the search icon red
$("#search i").toggleClass("active");

Answer №1

Below the click event, place the calculation logic for searchWidth as the width is being altered.

$("#search input").animate({width: "0px"}, 0);
//var searchWidth = $('#search input').width();

$('#search i').click( function() {
    //Change the width (show it)
    var toggleWidth = $("#search input").width() == 150 ? "0px" : "150px";
    $('#search input').animate({ width: toggleWidth });
var searchWidth = $('#search input').width();
    //Make the search icon red
    if ( searchWidth > 0 ) {
        $("#search i").addClass("active");
    } else {
        $("#search i").removeClass("active");
    }
});

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

Console shows successful jQuery ajax request, but the callback function is not being executed

I've been working on a jQuery POST request that's been giving me some trouble. Here is a snippet of the code I'm using: $.ajax("/myurl",{ data:{ ... }, mimeType:"application/json", dataType:"application/json", me ...

Use Bootstrap to effortlessly arrange columns horizontally in a row

I'm facing a scenario where I need to arrange the columns in a row horizontally. The challenge is to ensure that the row expands horizontally to fit the columns. I attempted to use white-space: nowrap on the row, remove floats on columns, and set the ...

Issue with PHP Ajax Image Upload

I am currently working on setting up an Ajax image upload feature. Unfortunately, I am encountering issues and unable to identify the root cause. <script> $(document).ready(function() { $("#uploadBTN").click(function(event) { ...

Adjust the content of an iframe based on the size of the screen

Hi there, I'm currently facing an issue with an ad that can't be resized. The support team suggested using two different ads - one for mobile and one for desktop. The dimensions of the ads are 720 x 90 and 300 x 100. I would like the ad to automa ...

creating styles for css elements using equations

I am curious about defining CSS element dimensions before they are rendered without using offset and jQuery. Is it possible to echo PHP into the width/height or position values? For example: <?php $width = 290px; $altwidth = 290; ?> <style> ...

Slice the towering text in half lengthwise

Ensure that the last line of visible text fits within a 20px padding, or else it should be completely cut off. The challenge lies in the varying text lengths of h3 each time. It's difficult to predict how much needs to be trimmed. Currently, the tex ...

Tips for crafting a perpetually looping animated shape using canvas

Lately, I've been experimenting with canvas and have encountered a challenge that I can't seem to solve. I've mastered creating shapes, animating them, and looping them across the canvas. However, I'm struggling to figure out how to spa ...

The scrollTop feature fails to function properly following an Axios response

I'm currently facing a challenge with creating a real-time chat feature using Laravel, Vue.js, Pusher, and Echo. The issue arises while implementing the following 3 methods: created() { this.fetchMessages(); this.group = $('#group') ...

Ways to display a jQuery datepicker when a button is clicked

I'm looking to display a datepicker only when a button is clicked <input type="button" id=day value="day" /> $("#day").datepicker(); The code above will populate the button text with the selected date I also attempted the following code, but ...

How can you make a form group expand within a container in Bootstrap 4?

After experimenting with the paddings, I still couldn't resolve the issue at hand. The goal is to extend these fields all the way to the right side. Check out the Fiddle for comparison between the current appearance and the desired look. The stylin ...

jQuery's text() function may return null when used in Google Chrome

Observing an unusual behavior in Google Chrome with the jQuery text function: $(document).ready(function () { $("#btnSubmit").click(function () { var t = $('#txtMessage').text(); alert(t); //this displays nothing in Google Chrom ...

Transferring JavaScript variables to PHP via AJAX and successfully utilizing them

A new WordPress plugin is currently in the works, involving AJAX to send a JavaScript variable as data. The goal is to retrieve and utilize this variable from the data in my PHP plugin template file. Here's a more detailed explanation: I have a file ...

What is the best way to clear out outdated items from the shopping cart when new items are added?

Looking to implement jQuery code that will display only one value at a time upon dragging it into the designated area. For example, if Bank is dragged, then only Bank should be displayed. Similarly, if Rent is dragged, only Rent should be shown. I have en ...

Angular is encountering a CORS issue with the "No Access-Control-Allow-Origin" error when trying to access a CSS file

Currently, in my Angular 5 application with a Web API back-end, my main goal is to reference a CSS file on a production server. I'm facing a cross-origin issue when trying to access the CSS file hosted on the IIS server website. Even though CORS is e ...

Extract value from child div using JQuery and update text in another section of the page

Here is a fiddle showcasing the concept I am working on: https://jsfiddle.net/wvz9p3e7/1/ The code is written in PHP and involves a loop for cycling through 7 or 8 different garments. My goal is to have the window on the right side of the fiddle display t ...

"Troubleshooting Problems with Scaling in the jQuery Mouse Wheel Plugin

I am currently utilizing this code in conjunction with the following plugin: mouse wheel $('#painter').on('mousewheel', function(e) { cp.scale(2, 2); var e0 = e.originalEvent, delta = e0.wheelDelta || -e0.de ...

Experiencing an issue where the canvas element fails to render on mobile Chrome browser,

I've encountered an issue with a script that draws a canvas based on the background color of an image. The image is loaded dynamically from a database using PHP. The responsive functionality works fine on mobile Safari, but not on Chrome. When the re ...

Finding the position of a specific element in an array by searching through multiple object keys

Assuming I have a single key (for example, if I have the object.name = 'Sam') and I want to find the index using: var index = array.map(function(el) {return el.name}).indexOf('Sam'); I can retrieve the index of the array element with ...

Which is more efficient for rendering performance: using images, CSS gradients, or box shadows with borders?

I'm curious about improving website scroll and animation performance. Which option would be better for your mobile webapp or website: Using a repeating thin image or CSS3 gradient? or Utilizing a repeating image instead of box shadow with a borde ...

Issue with Hover Effect for Input Type in Submit Form in HTML and CSS

In the following HTML code, a form is displayed inside a card HTML. The form appears after an onlick function which functions correctly. However, the submit button in the form below does not display a hover effect. <!-- Update details form here --> ...