I want to create a function and then use with onclick method, for example:
one = document.getElementById("oneID");
then instead of writing function for each onclick():
one.onclick = function(x) {
tempStack.push(parseFloat(one.value));
viewTemp.value += one.value;
}
I want to use a single function:
one.click = input(one);
but I'm not sure how to do it in the correct way for example the below I tried, doesn't work:
var input = function(x) {
tempStack.push(parseFloat(x.value));
viewTemp.value += x.value;
}
Lastly, no external JavaScript libraries to aid this question, vanilla JavaScript.
You'll need to pass a function as a reference, not call it:
one.onclick = input;
In this case you won't be able to pass an argument, but you can use this as a reference for the DOM element on which event is fired:
function input() {
tempStack.push(parseFloat(this.value));
viewTemp.value += this.value;
}
Here's a method with using JavaScript's .addEventListener(), as a previous answer mentioned, using this to pass through the DOM Node Element to use within the inputFunction.
<input type="text" value="64.23" id="bt" />
<script>
function inputFunction( x ) {
console.log( x.value ); //Console Logs 64.23
}
var bt = document.getElementById("bt");
bt.addEventListener( 'click', function(){ inputFunction( this )}, false );
</script>
Fiddle: http://jsfiddle.net/Lhq6t/
Think about functions as a normal objects, so the way is:
function input (event) {
// Process the event...
// event is my event object
// this is the object which trigger the event
// event.target is my button
}
on.onclick = input;
You must assign the input function as a normal variable.
The function input will receive an event object as parameter. Also you can refer to the button clicked with this.
Maybe the mozilla developer network or the real w3c site would explain it better.
Your requirement can be achieved by following:
Add this method in your script tag:
function input(x) {
/*tempStack.push(parseFloat(x.value));
viewTemp.value += x.value;*/
alert(x.id);
}
And then call this method onClick event of your buttons / anchors like:
<input type="button" id="oneID" value="oneID" onClick="input(this);"/>
<input type="button" id="twoID" value="twoID" onClick="input(this);"/>
threeID
See working example: http://jsfiddle.net/Avd5U/1/
ok, so just create a function with a parameter in it like:
function setValue(input){
tempStack.push(parseFloat(input.value));
viewTemp.value += input.value;
}
and then call the function on the click of that element like:
var one = document.getElementById("oneID");
one.click = setValue(one);
Good luck!
Related
I want to add on-click function to my dynamic div tag in JavaScript.
divElement = document.createElement('div');
divElement.onclick = moveImages(j, k);
I want to pass two parameter to the moveImages() function.
In pure Javascript you need to define the onclick as a function, just like this:
divElement.onclick = function(e) {
moveImages(j,k);
};
Without it, Javascript will simply call the function and assign the return value to the "property" onclick.
That (e) parameter is just in case you need to know where the click was and things like that.
You can achieve that by doing the following:
var divElement = document.createElement("div");
function moveImages(j, k){
/* ... */
}
divElement.addEventListener("click", function() {
moveImages(j, k);
}, false);```
My goal is to include Element.ID within function and then, fetch their value or text. It is important to reduce code lines as well because there are many others buttons with the same rule.
So, I tried the below code and many others to get the appropriate results.
How do I fix it?
var el = document.getElementById("p1");
var id = document.getElementById("p1").id;
el.addEventListener("click", modifyText(id), false);
function modifyText(e) {
var x = e.value;
if (x < 40) {
e.value = 1;
}
};
<input id="p1" type="button" class="button" value=0>
<input id="pn" type="button" class="button" value=0>
Well, the second argument to .addEventListener() has to be a function reference, not "loose" code to execute. So, if you want to call another function and pass it an argument, the line should be:
el.addEventListener("click", function(){modifyText(id)}, false);
Now, you are making quite a bit out of the element's id, but you really only need the id to get your initial reference to the element. Once you've got that, you can just work with it.
You've got a lot of unnecessary code here. Also, I'm assuming (perhaps incorrectly) that you want both buttons to have the same click behavior, so that's what I'm proceeding with.
// You only need to get a reference to the element in question
var el1 = document.getElementById("p1");
var el2 = document.getElementById("pn");
// Set up each button to use the same click callback function
// The second argument needs to be a function reference
el1.addEventListener("click", modifyText);
el2.addEventListener("click", modifyText);
function modifyText(){
// When inside of an event handler, "this" refers to the element
// that triggered the event.
if (this.value < 40 ) {
this.value = 1;
}
}
<input id = "p1" type="button" class="button" value=0>
<input id = "pn" type="button" class="button" value=0>
Event listener callbacks tend to be executed with the execution context of the element (unless otherwise modified, or using Arrow functions). This means you can just use this keyword to refer to the element. So inside the callback you could use this.value / this.innerText (depending on type of element)
function modifyText() {
var x = this.value;
if ( x < 40 ) {
this.value = 1;
}
}
Also the way you called addEventListener was wrong.
.addEventListener("click", modifyText(id), false);
This will execute modifyText immediately and use the return value of the function as the callback. And since your function doesnt return anything nothing is set as the callback.
If you wanted to pass a variable to an event callback you would do it like the following
el.addEventListener("click", modifyText.bind(el,yourValue),false);
You would then need to modify the function definition
function modifyText(passedValue,event) {
}
I'm trying to figur out how I can set the var number and then use it in my other function Custom.init(number); and make it stay on the page.
//Set number onclick
function setVar() {
var number = document.getElementById("textbox").value;
//Pass in number
jQuery(document).ready(function() {
Custom.init(number);
});
};
If you're using jQuery, the ready function should wrap all other functions as it will be invoked first and foremost.
$(document).ready(function(){
var number = document.getElementById("textbox").value;
//Then do your validation here
var setVar = function(){
Custom.init(number);
//whatever else is involved with this
}
})
If that doesn't work I'd check the console for a specific error and ensure your Custom.init function is working as expected.
It doesn't make sense to hide the ready handler inside a function. The comments in your code do also suggest that you wish to call Custom.init in response to a mouse click on some element. You would register an event handler to this end.
A suggested streamlining:
//Set number onclick
$(document).ready(function() {
$(<selector for clickable elements>).on (
"click"
, function (eve) {
Custom.init(parseInt($("#textbox").val()));
1;
}
);
});
I'd like to dynamically create event listeners for multiple buttons, and subsequently, show a particular frame label depending on the button clicked, but I'm unsure what to pass through (FYI, this is will be used for HTML5 canvas in Flash CC, but principally the same should apply to a web page for showing divs etc). I currently have this:
var butTotal = 4;
var selfHome = this;
function createListeners () {
for (var i=0; i<butTotal; i++) {
selfHome["btn" + i].addEventListener('click', openPop);
}
}
function openPop () {
alert("test");
selfHome.gotoAndPlay("pop"+event.currentTarget.name.substr(3));
}
createListeners();
It creates the listeners fine, but I don't really know where to start with passing through the current button instance name to tell it which frame label to gotoAndPlay.
Based on the code that you have, I'd simply change the .addEventListener() to call a generic function (rather than openPop, directly), and pass it the reference to the button. So, this:
selfHome["btn" + i].addEventListener('click', openPop);
. . . would become this:
selfHome["btn" + i].addEventListener('click', function() {
openPop(this);
});
At that point, you would then have to update openPop to accept a parameter for the reference to the element that triggered it . . . something like:
function openPop (currentButton) {
At that point, you could reference the clicked button, by using currentButton in the openPop logic.
I'm not sure I totally understand your question. However if you just need to pass the button instance (in you case "selfHome["btn" + i]") you could call an anonymous function in your event handler which calls openPop() with the button instance as an arugment. Would this work for you?
var butTotal = 4;
var selfHome = this;
function createListeners () {
for (var i=0; i<butTotal; i++) {
var currentBtn = selfHome["btn" + i];
currentBtn.addEventListener('click', function(){openPop(currentBtn);} );
}
}
function openPop (btn) {
alert("test");
selfHome.gotoAndPlay(/*use button instance 'btn' to find frame*/);
}
createListeners();
When the event is triggered the this keyword inside the handler function is set to the element is firing the event EventTarget.addEventListener on MDN. If the button have the data needed to be retrieved just get it from the this keyword:
function openPop (btn) {
alert(this.name);
/* ... */
}
It looks like you expect it to contain the function gotoAndPlay() as well as the btn elements (which contain both an ID (of btn[number]) and a name with something special at substr(3) (I assume the same as the id). If those things were all true, it should work in chrome... in other browsers you'll need to add event to the openPop() method signature.
function openPop (event) {
alert("test");
selfHome.gotoAndPlay("pop"+event.currentTarget.name.substr(3));
}
I believe this is what you are looking for and adding that one word should fix your problem (assuming some things about your dom and what selfHome contains):
JSFiddle
You could also leave out the event from openPop() and replace event.currentTarget with this:
function openPop () {
alert("test");
selfHome.gotoAndPlay("pop"+this.name.substr(3));
}
JSFiddle
I am trying to iterate over the following Code and for some reason each time i iterate over it, it fires off the event handler, does any one know why it would be automatically firing off the handler?
nmbr = 1;
x1 = document.getElementsByClassName('fp')[0] ;
slowSkrol = document.createElement('button');
slowSkrol.className = 'mods';
slowSkrol.value= nmbr;
x1.appendChild(slowSkrol);
slowSkrol.addEventListener('click', whenclicked(nmbr),false);
function whenclicked(vv){
alert(vv);
}
You are calling the function, and binding it's return value to the event, rather than binding the function itself to the event. Replace whenclicked(nmbr) with:
function(){ whenclicked(nmbr); }
In modern browsers you could also use bind:
whenclicked.bind(null, nmbr);
change:
slowSkrol.addEventListener('click', whenclicked(nmbr),false);
to
slowSkrol.addEventListener('click', function() {
whenclicked(nmbr);
},false);
I shouldn't be adding another answer really. but the correct way to do this so that you get all arguments and the this would be like so.
slowSkrol.addEventListener('click', function( event ) {
whenclicked.apply(this, [event, nmbr]);
}, false);
Then you can use it like so.
function whenclicked( event, nmbr ){
alert(this, event, nmbr);
// this = slowSkrol
}