开发者

Javascript onFocus . then onClick inside function

I'm trying to make it so when an element gets focus it calls a function which then will take care of all other events - here is my code for now.

<span id="checkbox" class="checkbox" onFocus="cbHover(checkbox)"></span>

<script type="text/javascript">
    function cbHover(id) {
        if(document.getElementById(id).onClick) {
            document.getElementById(id).style.backgroundPositionY = '-63px';
        }
    }
</script>

Obviously this isn't working开发者_如何学编程 :( So is there a way to keep the function running to listen for other events?

Thanks!


When the object is clicked, it is already focused. You can either skip the onFocus and replace it with onClick, or the other way around and remove if(document.getElementById(id).onClick) from the code, because you don't need it.


You are able to use two events: onFocus and onLostFocus. In onFocus event handler you are able to add onClick event to element:

document.getElementById(id).addEventListener('click',function_name,true);

In onLostFocus event handler you are able to remove event

document.getElementById(id).removeEventListener('click',function_name,true)


this is a bad idea even if you did get it to work you run the risk of applying multiple clicks on the same element. your best bet it to just apply the click event on dom ready I typically use jQuery

so if I where doing this in jquery i would do it like this

$(document).ready(function(){
    $('.classname').click(function(){
       // what to do onclick
    });
});


The reason it isnt working is the parameter that is passed, should be enclosed in quotes.

It should be

onFocus="cbHover('checkbox')"

otherwise, javascript treats checkbox as a variable and tries to pass the value of the variable which is null.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜