Execute addClass if element width equals .. pixels

So I have this search box which shows and hides by changing its width now I want to add a class to the search icon if its width is larger than 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");
    }
});

now It sorta worked with toggleClass but then if you'd click faster than the animation it got messed up, so that's why I tried the 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");

Upvotes: 0

Views: 262

Answers (1)

Ashish Balchandani
Ashish Balchandani

Reputation: 1266

Move searchWidth calculation logic below, as you are changing the width on click.

$("#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");
    }
});

Upvotes: 1

Related Questions