Code Cat
Code Cat

Reputation: 3

javascript events, onfocus

Now I'm changing default behavior of onfocus(onclick etc) events like this:

<div onfocus="my(this);"> </div>
function my(e){
    e.style.backgroundColor = "red";//here we do not use getElementById
}

This works good until I need to attach events from javascript. Of course we can use addEventListener("focus", my) but in this case we do not send this value and I need to find to by getElementById, but this is not good for me. How can I solve this problem? Thanks

Upvotes: 0

Views: 190

Answers (3)

Drifter
Drifter

Reputation: 281

Working example here

Add a class to each div you want to use for focus with a tabindex. Tabindexes can make divs focus

<div class="sofocus" tabindex="0">

And now you can just add the eventlistener

var focusDivs = document.querySelectorAll('.sofocus');
for(var i = 0; i < focusDivs.length; i++){
  var div = focusDivs[i];
}

Bind each div with the event

div.addEventListener("focus", styleItRed);

And also for not focussing anymore

div.addEventListener("blur", removeColor);

With that in mind you can create the functions

function styleItRed(){
    this.style.color = 'red';
}

function removeColor(){
    this.style.color = 'inherit';
}

Upvotes: 0

Mouser
Mouser

Reputation: 13304

    document.querySelector("div").addEventListener("click", my, false); //select the only div

    function my(e){
        e.target.style.backgroundColor = "red";//here we do not use getElementById
    }
<div> Test div </div>

Target is the keyword. I would still use addEventListener since it's a more standard approach than inline events. Also (you don't need it now) it natively send the this keyword and it allows other similar events to be attached without overriding them.

Upvotes: 0

winhowes
winhowes

Reputation: 8065

Try this. Change your html to this:

<div onclick="my(event);"> test</div>

And your JS to this:

function my(e){
    e.target.style.backgroundColor = "red";//here we do not use getElementById
}

e.targetis the element which received the event.

Upvotes: 1

Related Questions