stack
stack

Reputation: 10228

How to define the css :focus state in a jQuery selector?

Here is a resizable textarea:

var KeyDown;
$(".TxtArea > div").mousedown(function(){
    $(this).parent().addClass("Resize");
    $("body").addClass("UnSelectable");
    KeyDown = 1;
    $("textarea").css("opacity","0.3");
		$("textarea").focus(function() { $(this).css("border-color","#ccc") });
});
$(document).mouseup(function(){
    $(".TxtArea").removeClass("Resize");
    $("body").removeClass("UnSelectable");
    KeyDown = 0;
    $("textarea").css("opacity","1");
    $("textarea").focus(function() { $(this).css("border-color","#07c") });
});
$(document).mousemove(function(Event){
    if (KeyDown == 1 && $(".TxtArea").hasClass("Resize")) {
        var Height = Event.pageY - $(".TxtArea").children("textarea").offset().top;
        $("textarea").height(Height);
    }
});
textarea {
  border: 1px solid #ccc;
  outline:none;
}

textarea:focus{
  border: 1px solid #07c;
}


.TxtArea {
    width: 300px;
}

.TxtArea > textarea {
    width: 100%;
    display: block;
    resize: none;
    box-sizing: border-box;
}

.TxtArea > div {
    height: 10px;
    background: #eee;
    border: 1px solid #ddd;
    box-sizing: border-box;
    text-align: center;
    line-height: 0px;
}
.TxtArea > div:hover {
    cursor: n-resize;
}

.UnSelectable {
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="TxtArea">
    <textarea></textarea>
    <div>.....</div>
</div>

Please follow these steps:

Why border doesn't change? and how can I return it to #07c after unclicking. How can I do that? (I want something exactly like SO)


Note: I want to set #07c just only focus state of that textarea after unclicking (Not a permanent border)

Upvotes: 0

Views: 124

Answers (1)

Robert Ingrum
Robert Ingrum

Reputation: 234

So I'm not sure exactly why your focus code wasn't working, but in general, this is just better practice. Typically you want the css to handle all of the styling and the javascript just toggles it. It just keeps things cleaner and more organized.

So you can do this: https://jsfiddle.net/psp12a0n/

The main thing that was changed was this part in the javascript:

$(".TxtArea > div").mousedown(function(){
    $(this).parent().addClass("Resize");
    $("body").addClass("UnSelectable");
    KeyDown = 1;
    $("textarea").addClass('inactive');
});
$(document).mouseup(function(){
    $(".TxtArea").removeClass("Resize");
    $("body").removeClass("UnSelectable");
    KeyDown = 0;
    $("textarea").removeClass('inactive');
});

And this in the css:

textarea:focus,
textarea:active {
    border: 1px solid #07c;
}

textarea.inactive {
    opacity: .3;
    border-color: #ccc;
}

Hope this works for you!

Upvotes: 1

Related Questions