ユーザーが入力ボックス (フォーカス) 内をクリックしたときに "myfunction" と呼ばれる関数を実行するコードは何ですか。
jquery で例を見たことがありますが、ストレートな JavaScript でそれを行う方法がわかりません。
ユーザーが入力ボックス (フォーカス) 内をクリックしたときに "myfunction" と呼ばれる関数を実行するコードは何ですか。
jquery で例を見たことがありますが、ストレートな JavaScript でそれを行う方法がわかりません。
var addEvent = (function(){
/// addEventListener works for all modern browsers
if ( window.addEventListener ) {
/// I'm returning a closure after the choice on which method to use
/// has been made, so as not to waste time doing it for each event added.
return function(elm, eventName, listener, useCapture){
return elm.addEventListener(eventName,listener,useCapture||false);
};
}
/// attachEvent works for Internet Explorer
else if ( window.attachEvent ) {
return function(elm, eventName, listener){
/// IE expects the eventName to be onclick, onfocus, onkeydown (and so on)
/// rather than just click, focus, keydown as the other browsers do.
return elm.attachEvent('on'+eventName,listener);
};
}
})();
上記のクロスブラウザ機能を使用すると、次のことができます (dom が完全にロードされたら):
addEvent(document.getElementById('your_input'),'focus',function(e){
var input = e.target || e.srcElement;
alert('this input has gained focus!');
});
onfocus 属性を使用する
<input type="text" onfocus="someFunc()">
<script>
function someFunc(){
}
</script>
document.getElementById("elementId").addEventListener("focus",function(e){
//Do Something here
});