I wanted to add inner shadow to a search box when the user clicks on it so I used this simple code :
function shadow()
{
document.getElementById("search2").style.boxShadow="inset 0px 0px 12px 0px rgba(0,0,0,0.75)";
}
And the markup :
<input type="search" onClick="shadow()">
So that when you click on the search box, the "search2" div gets an inner shadow and it works. But I want to know how to reverse this (remove the inner shadow) when the user unclick the search box and click elsewhere.
Thanks
I wanted to add inner shadow to a search box when the user clicks on it so I used this simple code :
function shadow()
{
document.getElementById("search2").style.boxShadow="inset 0px 0px 12px 0px rgba(0,0,0,0.75)";
}
And the markup :
<input type="search" onClick="shadow()">
So that when you click on the search box, the "search2" div gets an inner shadow and it works. But I want to know how to reverse this (remove the inner shadow) when the user unclick the search box and click elsewhere.
Thanks
Share Improve this question asked Apr 16, 2014 at 18:12 Marwan OssamaMarwan Ossama 3451 gold badge6 silver badges12 bronze badges 2-
Don't do what you're doing. Your click handler should simply add/remove a class which contains the styles. Or rather,
focus
andblur
should add/remove respectively. – Evan Davis Commented Apr 16, 2014 at 18:14 - Unclick? Do you mean releasing the mouse button, often called mouseUp? Or do you mean clicking the mouse on anything other than the search box? – Surreal Dreams Commented Apr 16, 2014 at 18:14
3 Answers
Reset to default 4You should be using the onfocus
and onblur
events.
onfocus
- fires when the user is in the textboxonblur
- fires when the user leaves the textbox
In the onblur
event you add
document.getElementById("search2").style.boxShadow = "";
The click event only fires when the user clicks the element.
You can do this without using any JavaScript at all, using the CSS focus: pseudoselector. In your CSS styles, use this:
#search2:focus {
box-shadow: inset 0px 0px 12px 0px rgba(0,0,0,0.75);
}
The advantage here is that it's less code and it will still work even in browsers without JavaScript enabled. Here's a jsFiddle: http://jsfiddle/5g9an/
It couldn't be simpler. Well, I can't think of a simpler method, anyhow.
Use blur
event:
<input type="search" onClick="shadow()" onBlur="removeShadow()">
function removeShadow(){
document.getElementById("search2").style.boxShadow="none";
}