mdcrtv mdcrtv - 3 months ago 8
CSS Question

jQuery addClass function appears to run, but doesn't actually populate the class name

I'm experiencing a strange issue here.

I've developed a search box with several actions. The important bit is that it will (or it should...) open up when a user clicks the button.

HTML:

<form method="get" id="searchform" action="">
<input type="search" placeholder="Search" size="18" value="" name="s" id="s" />
<input type="submit" value=""></input>
</form>


CSS:

#searchform {
position: relative;
min-width: 40px;
height: 80px;
float: right;
}
#searchform input[type="search"] {
margin-right: 40px;
height:80px;
width:2px;
background:rgba(245, 245, 240, 1);
padding: 0;

-webkit-transition:all .2s ease-in-out;
-moz-transition:all .2s ease-in-out;
-o-transition:all .2s ease-in-out;
transition:all .2s ease-in-out;
}
#searchform input[type="submit"] {
background: rgba(255, 255, 255, 1);
position: absolute;
right: 0;
top: 0;
width: 40px;
height: 80px;
}
#searchform.open input[type="search"] {
width: 180px;
padding: 0 0 0 20px;
}
#searchform.open input[type="submit"] {
background:rgba(200, 160, 0, 1);
}


JS:

$('#searchform input[type="submit"]').click(function () {
$("#searchform").toggleClass('open');
});

$('#searchform input[type="submit"]').click(function () {
if ($('#searchform').hasClass('open') && $.trim($('#searchform input[type="search"]').val()).length === 0) {
event.preventDefault();
$('#searchform').removeClass('open');
}
});

$(document).bind('click', function () {
$('#searchform').removeClass('open');
});

$('#searchform').bind('click', function (event) {
event.stopPropagation();
});


And here's a fiddle: http://jsfiddle.net/5zB8f/1/




The open action is pretty simple. A jQuery script adds
class="open"
to
#searchform
, but it's only adding class ... The code seems valid, so I'm at a loss as to why it would behave like this.

If you manually add that class to the html and run it, you'll see what it's supposed to transition to.

Any help is appreciated. Bonus points if someone can tell me how to optimize that jQuery script... I'm sure I've written more than necessary for this to work...




Edit: I've got
toggleClass
on there now, but it behaves the same with
addClass
...

Answer

Is this what you need?

http://jsfiddle.net/5zB8f/3/

$('#searchform input[type="submit"]').click(function () {
    $("#searchform").toggleClass('open');
    if ($('#searchform').hasClass('open') && $.trim($('#searchform input[type="search"]').val()).length === 0) {
        event.preventDefault();
    }
    if ($("#searchform").hasClass("open")) return false;
});


$(document).bind('click', function () {
    $('#searchform').removeClass('open');
});

$('#searchform').bind('click', function (event) {
    event.stopPropagation();
});