Change div color on focus

That I am trying to change the color div

with the letters

<div class="search_container">
    <input type="text" class="search_field" placeholder="Search..." />
    <div id="magnify_glass">s</div>
</div>

      

What I have tried is this

<script>
    $('.search_field').focus(function() {
        $('#magnify_glass').css('color','#ff0000');
    });
</script>

      

+3


source to share


2 answers


Assuming your code is in a <head>

document, you only need a document handler. Try the following:

Update

To remove a color, you need to add a handler blur

.

<script>
    $(function() {
        $('.search_field').focus(function() {
            $('#magnify_glass').css('color','#ff0000');
        }).blur(function() {
            $('#magnify_glass').css('color','transparent'); // or whatever the default is.
        });
    });
</script>

      



Also, it is better to use class

to add style to an element as it is a better separation of concerns:

.focus { color: #F00; }

      

$('.search_field').focus(function() {
    $('#magnify_glass').addClass('focus');
}).blur(function() {
    $('#magnify_glass').removeClass('focus');
});

      

+5


source


You are working and working properly to make sure you have the document.ready code to ensure the element is accessible before the script is accessed and the jquery library is added.

Live Demo



$('.search_field').focus(function () {
    $('#magnify_glass').css('color', '#ff0000');
}).blur(function() {
    $('#magnify_glass').css('color', '#000000');
})

      

+2


source







All Articles