Reputation: 3
The following code does not work:
<input id="inp" type="text"
onfocus="(function(){document.getElementById('inp').style.background="yellow";})">
But this code works as I wish it to work:
<input id="inp" type="text"
onfocus="(function(e){document.getElementById('inp').style.background ='yellow';}(this)">
Why doesn't the first code work?
Upvotes: 0
Views: 797
Reputation: 724
Scott already answered your question very well. I'd just like to add to your second example:
<input id="inp" type="text"
onfocus="(function(e){document.getElementById('inp').style.background ='yellow';}(this)">
Should be:
<input id="inp" type="text" onfocus="(function(that) {that.style.background='yellow'})(this);">
There is no need to use the document.getElemetnsById method as you have already passed "this" element to the self invoking function.
But like Scott already mentioned you should use DOM Event Standard, handling evetns via HTLM attributes is old school.
Upvotes: 0
Reputation: 65808
The first doesn't work because it is wrapped in parenthesis and therefore it is a function "expression", rather than a function "declaration". Expressions are meant to be "evaluated", so when your element gets the focus, the expression is evaluated, but not invoked. Also, you have double-quotes nested within double-quotes, which would cause a syntax error ("yellow"
). Those would need to be changed to single quotes.
The second works because the "expression" is immediately invoked by the second set of parenthesis (this)
.
However, both syntaxes should be avoided. Don't use inline HTML event attributes to wire up event handling callback functions because they:
this
binding in the
functionInstead, write your event handlers in JavaScript:
// Get a reference to the DOM element
var input = document.getElementById("inp");
// Wire up an event handler
input.addEventListener("focus", function(e){
input.style.background ='yellow';
});
<input id="inp" type="text">
Upvotes: 1
Reputation: 242
First one have is not working because of:
IIFE syntax is like (function(){}())
and "
around yellow is pre closing the onfocus.
Corrected syntax is this.
<input id="inp" type="text"
onfocus="(function(){document.getElementById('inp').style.background='yellow';})()">
Upvotes: 1
Reputation: 32511
The issue is that you aren't invoking the first function. Essentially, you're declaring a function but never calling it.
Example:
(function() {
console.log('I would do something but no one calls me');
}); // <-- Notice the lack of ()
(function() {
console.log('I do something because I am called');
})(); // <-- Notice the () on the end
You also have trouble in the first example due to your use of double quotes ("
) in the function. Since the onfocus
attribute value must be wrapped in double quotes, you're prematurely closing that attribute.
<input onfocus="console.log("I won't work since I'm closing the quotes");" />
Upvotes: 0