Javascript Function Pointer Used to set onclick Function - javascript

I have a string I am using to get a pointer to my function. Then I want to use this function to set an onclick while passing arguments to the function.
var functionPtr = window[stringFunction];
pTag.onclick = function () {
functionPtr(args);
};
When I do this, the onclick event tries to call "functionPtr(args)" instead of calling the function I'm pointing to. Using break points, I can see that functionPtr is definitely a reference to the function I want when I assign the onclick function. What steps am I missing here?
Thanks in advance!

I couldn't get my above attempt to work so I decided to set the onclick event using the setattribute() function instead.
var stringFunction = 'myFunction(args)';
pTag.setAttribute('onclick', stringFunction);
This seems to do the trick. Its important to note this doesn't work for earlier versions of IE, but I'm only required to work with IE 10 and up so this works for me.

Related

how to insert onclick attribute into a span? [duplicate]

This is my function and it should change the onClick attribute of the HTML input, but if I use
document.getElementById('buttonLED'+id).onclick = "writeLED(1,1)";
it does not work at all, but if I use
document.getElementById('buttonLED'+id).onclick = writeLED(1,1);
the function executes by itself!
Any ideas what code do I have to use to change the onCLick attribute WITHOUT executing the function, before the button is clicked?
Here is the full function, if it matters:
function showLED(id){
if(color == 0){
document.getElementById('buttonLED'+id).onclick = "writeLED(1,1)";
document.getElementById('buttonLED'+id).value="light is on";
//document.getElementById('buttonLED'+id).disabled = false;
}else{
document.getElementById('buttonLED'+id).onclick = "writeLED(1,0)";
document.getElementById('buttonLED'+id).value="light is off";
//document.getElementById('buttonLED'+id).disabled = false;
}
}
Well, just do this and your problem is solved :
document.getElementById('buttonLED'+id).setAttribute('onclick','writeLED(1,1)')
Have a nice day XD
You want to do this - set a function that will be executed to respond to the onclick event:
document.getElementById('buttonLED'+id).onclick = function(){ writeLED(1,1); } ;
The things you are doing don't work because:
The onclick event handler expects to have a function, here you are assigning a string
document.getElementById('buttonLED'+id).onclick = "writeLED(1,1)";
In this, you are assigning as the onclick event handler the result of executing the writeLED(1,1) function:
document.getElementById('buttonLED'+id).onclick = writeLED(1,1);
The line onclick = writeLED(1,1) means that you want to immediately execute the function writeLED(arg1, arg2) with arguments 1, 1 and assign the return value; you need to instead create a function that will execute with those arguments and assign that. The topmost answer gave one example - another is to use the bind() function like so:
var writeLEDWithSpecifiedArguments = writeLED.bind(this, 1,1);
document.getElementById('buttonLED'+id).onclick = writeLEDWithSpecifiedArguments;
Using Jquery instead of Javascript,
use 'attr' property instead of 'setAttribute'
like
$('buttonLED'+id).attr('onclick','writeLED(1,1)')
You are not actually changing the function.
onClick is assigned to a function (Which is a reference to something, a function pointer in this case). The values passed to it don't matter and cannot be utilised in any manner.
Another problem is your variable color seems out of nowhere.
Ideally, inside the function you should put this logic and let it figure out what to write. (on/off etc etc)
Another solution is to set the 'onclick' attribute to a function that returns your writeLED function.
document.getElementById('buttonLED'+id).onclick = function(){ return writeLED(1,1)};
This can also be useful for other cases when you create an element in JavaScript while it has not yet been drawn in the browser.
First we'll select the required button using query selector and for all the selected buttons we'll set the onclick attribute with a function that needs to be called by clicking on the buttons.
You can write the code for required work you want to do by clicking the button in the function defined.
Well "One of the" generalized solution to your to your problem can be achieved by the following code:
var a=document.querySelectorAll('button');
for(b=0;b<a.length;b++)
{
a[b].setAttribute("onclick","check("+b+")");
}
function check(e)
{
var sa=a[e].innerHTML;
console.log('working onclick',sa);
}

Immediately invoked arrow function expression

Here's a function where it suppose to work when I click a "button
but surprisingly it immediately invoked without calling!
const show_card = (shopping_card_checkout) => {
console.log("ali el-deeb");
};
document.querySelector('.fa-shopping-cart').addEventListener('click', show_card()) ;
If I tried to redo the code after the event listener it says reference error as I called the function before declaration.
Help a beginner.
Saw your post request in JS FB group and thought I'd answer here.
First you need to use document.ready or make sure that all js is loaded as last cause else the element might not yet exist. This is not th cause of your problem btw. The problem I explain as last but some advice. You use a class and querySelector, querySelector will fetch the first element in the document and if you want all elements returned you need querySelectorAll and this is not unique or would you like to bind the same action and functionality to many elements? So better would be to use the unique id of an element and use something like:
const myElement = document.getElementById("idName");
myElement.addEventListener("click", myFynction);
const myFunction = () => console.log("Clicked");
The real cause of your issue
You bind the function to the click event and bind it with () behind it and that triggers the execution cause now you don't bind the function but the result of the bound function, you can't pass parameters like that to a bound event. You will need to fetch them inside the function cause only event and a callback can be triggered.
So your working code is:
const show_card = (shopping_card_checkout) => console.log("ali el-deeb");
document.querySelector('.fa-shopping-cart').addEventListener('click', show_card);
And if only one return or one statement inside an arrow function there is no need for the curly brackets and no need to use return since it will automatically return the result of the oneliner.

Function parameter evaluates to undefined

When dynamically creating an element of type select, there are two problems when setting the onclick method:
It is impossible to simply set the onclick with element.onclick="updateInput(this.articleIndex)";
This results in a final HTML tag where no onclick is shown at all.
When set by e.setAttribute("onclick","updateInput(this.articleIndex)");, it does appear in the final HTML. And the updateInput method does get called.
However the functionality seems to be broken, as the argument always evaluates to undefined
Here a simple example of my problems:
var selectElem = document.createElement("select");
selElem.id="articleSelector_"+this.articleIndex;
console.log("the index of the article is " + this.articleIndex);
selElem.setAttribute("onclick","updateInput(this.articleIndex);");
//selElem.onclick="updateInput(this.articleIndex)"; //this does not work
The log shows the correct number. Inside the updateInput method, the argument is of value undefined instead of the number previously shown in the log.
Try attaching handlers with pure Javascript, and not with HTML, without onclick = "... (which is as bad as eval).
The this in your script refers to the calling context of the function - what is it?
You might want:
element.addEventListener('click', () => {
updateInput(this.articleIndex);
});
(arrow functions retain the this of their surrounding scope)
it is impossible to simply set the onclick with element.onclick="updateInput(this.articleIndex)";
What that code does is it assigns the string "updateInput(this.articleIndex)" to the onclick which makes no sense and certainly not what you want.
Even if you remove the quotes:
element.onclick = updateInput(this.articleIndex);
It is still incorrect because it assigns the result of the updateInput() function to the onclick which is again not what you want.
You need to assign a function name to the onclick like this:
element.onclick = updateInput;
However, this doesn't allow you to pass a parameter as you wish. To do so, you need to use an anonymous function:
element.onclick = function() {
updateInput(this.articleIndex)
};
When set by e.setAttribute("onclick","updateInput(this.articleIndex)");, it does appear in the final HTML. And the updateInput method does get called.
This works because it sets the attribute onclick and it is a string type, so everything is correct. It is equivalent to using the anonymous function above. The only difference is this, which in this case refers to the element itself, while in the above code it depends on the context that the code appears in. That's why in this case the argument always evaluates to undefined because the select element doesn't have an articleIndex property.
The problem is the value of the context this when that element is clicked, the context this is not available anymore at that moment.
You have two ways to solve this problem:
You can use the function addEventListener to bind the event click, and bind the function/handler with the desired context this:
The function bind binds a specific context to a function.
selElem.addEventListener('click', updateInput.bind(this));
function updateInput() {
console.log(this.articleIndex);
}
As you need a specific value, you can use data attributes. That way, you don't need to worry about the context this.
selElem.dataset.articleIndex = this.articleIndex;
selElem.addEventListener('click', function() {
updateInput(this.dataset.articleIndex); // Here you can get that value.
});

RemoveEventListener without running function

So I am trying to remove my addEventListener function using the removeEventListener function. I've read alot about it needing to include an handler function, which I have done.
One of the issues is that I am running into is that I would like to remove the eventlistener when I change an input using google's searchbox. Don't mind google but really all what is happening is it is identifying when the input value has changed and providing new results. So a bit of code
var input = document.getElementById('search-input');
var searchBox = new google.maps.places.SearchBox(input);
google.maps.event.addListener(searchBox, 'places_changed', locationChange);
function previousButtonFunction(){
//Does something here and does not return anything. Lets just say it places markers all over the map
}
function locationChange() {
var previousButton = document.getElementById('previous');
previousButton.removeEventListener('click', previousButtonFunction());
previousButton.addEventListener('click', function () { previousButtonFunction()})
};
So this code looks like it doesn't make any sense to you probably, but what I am trying to get is that on the first input it would run the add event listener, and not run the removeEventListener function. Once the value of input has changed, I would like to remove the current listener and re-identify the previousButton with a new addeventlistener.
At the first go, I realize that the function of previousButtonFunction() is run, which I thought that it would only run if there was an identified listener. So the first question is the removeEventListener function supposed to run if the eventlistener wasn't added? Second how can I remove the addEventListener without running the function? Would I need to pass in a tracking identifier such as true => run it/false => don't run?
Thanks any help is greatly appreciated
Don't use ()after the function name. You want to pass only a reference to the function. Putting() after the name calls the function and passed the return value. This is a very common mistake.
Change this:
previousButton.removeEventListener('click', previousButtonFunction());
to this:
previousButton.removeEventListener('click', previousButtonFunction);
The same goes for .addEventListener(). Don't put () after the function name unless the function returns another function that you want to be the listener.
FYI, it's a little unclear why you're attempting to remove and then add back the same exactly same listener function. Unless there are multiple listeners on that object and you're trying to change the order of listeners, this is essentially a noop.

appendChild of objects containing javascript attributes

i have this Javascript function
function webit(thumb){
webi = document.createElement("img");
webi.alt=thumb.id.replace("t", "");
webi.id = "w"+webi.alt;
webi.className = "web";
webi.src= thumb.src.replace("thm","web");
webi.height=233;
webi.onclick='alert()';
document.body.appendChild(webi);
}
which is supposed to embed a larger version of a thumbnail image the end of the document. It works fine except that any javascript function ( ie onXXX) stays resolutely null. This seems to be no matter which JS function i use and afaict any thing i try to set it to.
The above example uses
webi.onclick='alert()';
which fails leaving onclick null, though all the other statements succeed.
When in javascript the .onclick property expects a function not a string
webi.onclick=function(){ alert(); };
You could also use the addEventListener method to set an event handler
webi.addEventListener("click",function(){ alert(); });
There are two problems, you are giving quotes to alert & onclick requires a function that can be called after clicking on it, you should not call the assigned function.
webi.onclick=function(){alert()};
You might consider declaring webi as var. Without "var", you implicitly defined window.webi, and it will introduce memory leaks.
var webi = document.createElement("img");
In addition, jQuery is usually a better choice than raw js/browser API.

Categories