Reputation: 4342
I am trying to use a function with click()
. I get no errors in the console how can I make it so that when the click happens it will perform the action in the function? Here is the code I am working with.
inputIds = [].filter.call(document.getElementsByTagName('input'), function(el) {
return el.id.indexOf('ansx') === 0;
}).map(function(el) {
return el.id;
});
// random number between low and high range
inputId = inputIds[Math.floor(Math.random() * inputIds.length)];
document.getElementById(inputId).click(function() {
chrome.extension.sendMessage({ message: "text here" }, function(response) {
return response;
});
});
Upvotes: 0
Views: 63
Reputation: 266
This is a generic implementation of addEvent that works across browsers.
function addEvent(el, type, eventHandle){
if ( el.addEventListener ) {
el.addEventListener( type, eventHandle, false );
} else if ( el.attachEvent ) {
el.attachEvent( "on" + type, eventHandle );
} else {
el[type] = eventHandle;
}
}
Your code would look like
addEvent(document.getElementById(inputId), "click", function() {
chrome.extension.sendMessage({ message: "text here" }, function(response) {
return response;
});
});
I would recommend anyone to use a base framework like jQuery as it would mask a lot of such quirks.
Upvotes: 1
Reputation: 22257
If you're not using any JavaScript framework you should use addEventListener
instead of click
function.
document.getElementById(inputId).addEventListener("click", function() {
chrome.extension.sendMessage({ message: "text here" }, function(response) {
return response;
});
});
Upvotes: 1
Reputation: 190907
click
isn't an event-binding function against a DOMElement
which getElementById
returns. As commenters have noted, click
invokes the event. You need to use jquery or use plain old event handlers.
Upvotes: 3