开发者

Javascript onfocus / onblur issues

So I am making a little searchbar that shows results underneath of it like such:

<div id='searchWrapper'>
  <div id='Search'>
    <input id="inputSpn" type="input" value="" />
    <input id="searchBtn" type="image" src="/search.png" />
    <br clear='all'/>
  </div>
  <div id='Results'>
  </div>
</div>

I am basically doing a livesearch with through AJAX. The <div id='Results'> is initially hidden until you type and it populates some results. My issue however is getting it to hide when the user clicks away. having it disappear through onblur does not work either as I need to be able to click on the results and not have them disappear on me. Unfortunately I 开发者_StackOverflow社区have not been able to find a good non jQuery method on the internet yet. Simplest way to put it is: I want the results to disappear if anything but the <div id='searchWrapper'> is clicked. Thanks!


Here is a non-optimised but working non-jQuery solution

<script>
document.onclick=function(e) {
  var elem = e?e.target:event.srcElement;
  var id = elem.id;
  document.getElementById("inputSpn").value=id+" clicked"; // debug - remove when happy
  // the following could be done by looping over the searchWrapper and its children
  if (id !="searchWrapper" && id!="Search" && id != "inputSpn" && id != "searchBtn" && id != "Results") {
    document.getElementById("Results").style.display="none"
  }
}
</script>
<div id='searchWrapper'>
  <div id='Search'>
    <input id="inputSpn" type="input" value="" />
    <input id="searchBtn" type="image" src="TekTP/icons/search.png" />
    <br clear='all'/>
  </div>
  <div id='Results'>hello
  </div>
</div>

UPDATE:

Toggle if clicked on the wrapper div

 var hide= (id !="searchWrapper" && id!="Search" && id != "inputSpn" && id != "searchBtn" && id != "Results");
document.getElementById("Results").style.display=(hide)?"none":"block";


Add a listener to the document (using addEventListener) - JSFiddle Example

<style>
#Results {
     display: none;   
}
</style>

<script type="text/javascript">
window.onload = function(){
    document.addEventListener('click', function(event){
        if(document.getElementById('searchBtn') != (event.target) ? event.target : event.srcElement) {
            document.getElementById('Results').style.display = 'none';
        } else {
            document.getElementById('Results').style.display = 'block';
        }
    });
};
</script>

<div id='searchWrapper'>
    <div id='Search'>
        <input id="inputSpn" type="input" value="" />
        <input id="searchBtn" type="button" value="Search"/>
        <br clear='all'/>
    </div>
    <div id='Results'></div>
</div>

But if you are going to be using a significant amount of Javascript in your site, you might consider using jQuery - it will make your life much easier.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜