Reputation: 607
What am trying is to change the color of the div
with letter s
<div class="search_container">
<input type="text" class="search_field" placeholder="Search..." />
<div id="magnify_glass">s</div>
</div>
What I tried is this
<script>
$('.search_field').focus(function() {
$('#magnify_glass').css('color','#ff0000');
});
</script>
Upvotes: 3
Views: 4304
Reputation: 148180
You code is fine and working you need to ensure you have the code in document.ready to ensure the element availability before accessed by script and you have jquery library added.
$('.search_field').focus(function () {
$('#magnify_glass').css('color', '#ff0000');
}).blur(function() {
$('#magnify_glass').css('color', '#000000');
})
Upvotes: 2
Reputation: 337714
Assuming your code is in the <head>
of the document, you just need a document ready handler. Try this:
Update
To remove the colour you need to add a blur
handler too.
<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's better to use a class
to add styling to an element as it's a better separation of concerns:
.focus { color: #F00; }
$('.search_field').focus(function() {
$('#magnify_glass').addClass('focus');
}).blur(function() {
$('#magnify_glass').removeClass('focus');
});
Upvotes: 5