Jump to content

Javascript: object.focused = true?


tinfanide

Recommended Posts

if (object.focused = true) {// do something}

Is there a way to check if an element is focused in JavaScript?

Link to comment
Share on other sites

You do mean a form element? yes! focus is only meant to be used for form elements

<input type="text" id="someinput" name="someinput"><input type="text" id="someinput2" name="someinput2"><input type="text" id="someinput3" name="someinput3"><input type="text" id="someinput4" name="someinput4">

window.onload=function(){ var inputelement = document.getElementsByTagName("input");var default_borderColor = inputelement[0].style.borderColor;for(i=0;i<inputelement.length;i++)	{	inputelement[i].onfocus=function()		{		this.style.borderColor="red";		}	inputelement[i].onblur=function()		{		this.style.borderColor=default_borderColor;		}	} }

And yes people i do know that changing of border colour can be achieve with css :focus. Just change code for styling change to reference a function to apply whatever.

Edited by dsonesuk
Link to comment
Share on other sites

I dont get what you are trying to do. Why do you want to check, if an input have focus? When an input is clicked, it gets focus. You dont need to check, just do something, when it get focus. Eg:

<input onfocus='doSomething()'/>

Edited by eTianbun
Link to comment
Share on other sites

input can be keyboard tabbed to receive focus
Yes, i now about that, but why does he want to search for it via js? I think what he is trying to do, is see, if an input have focus. E.x
if(elementFocus==true){/*doSomething via js*/}

Link to comment
Share on other sites

Perhaps he knows how to apply inline as onfocus='doSomething()', but wishes to use the unobtrusive method, where you don't manually add it to each input, but search for inputs, or specific inputs and apply it dynamically. how i had shown.

Link to comment
Share on other sites

It seem you still dont get me! I think he wants a property of an input element, which i dont realy know of, that is set by the browser each time an input have focus, just like the event object.ex:

event.ctrlKey==1 /*A property, that is set each time a ctrl key is press*/

input.hasFocus==1 /*I think this is what he is refering to, a property, sets by the browser, that state if the input curently have focus, or not or am i wrong?*/

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...