this is my code :
<body>
<button id="mybtn">Click Me!</button>
<script>
document.getElementById("mybtn").onclick = sum(2,5);
function sum(a,b) {
document.getElementById("x").innerHTML = a + b;
}
</script>
</body>
why document show 7 before click button?
what happened there you are executing the function instead of assigning it
here is a solution :
document.getElementById("mybtn").onclick = function(){ sum(2,5) };
In addition to #NetaMeta's answer you can use Function.prototype.bind() method to create new function from sum function and prepend parameters:
document.getElementById("mybtn").onclick = sum.bind(null, 2, 5);
Related
I'm trying to add listeners to a number of buttons using a for loop. The appropriate listener for each button is indicated by the ID attribute of the button. Button IDs follow the form "button-[listenerName]". I get the list of all my button elements using querySelectorAll(), and then I iterate through that list, slicing out the name of each listener from the name of each button element. Then, I use the name of the listener with addEventListener() in an attempt to associate that button with its listener.
<!DOCTYPE html>
<html>
<body>
<button id="button-listener1">Try 1</button>
<button id="button-listener2">Try 2</button>
<button id="button-listener3">Try 3</button>
<button id="button-listener4">Try 4</button>
<p id="demo"></p>
<script>
var selector = "[id^=button]";
var allButtons = document.querySelectorAll(selector);
for (var button of allButtons) {
var listenerName = button.id.slice(button.id.lastIndexOf("-")+1);
button.addEventListener("click", listenerName);
}
var listener1 = function() {
document.getElementById('demo').innerHtml = "1";
}
var listener2 = function() {
document.getElementById('demo').innerHtml = "2";
}
var listener3 = function() {
document.getElementById('demo').innerHtml = "3";
}
var listener4 = function() {
document.getElementById('demo').innerHtml = "4";
}
</script>
</body>
</html>
Unfortunately, it doesn't work. What's up with that? Thank you.
There are 3 issues with your code:
In your for loop, you are essentially attaching strings as eventlisteners. You need to access your event listeners from the string you have.
Since you eventlisteners are declared in the global scopre, you can use window to access them:
button.addEventListener("click", window[listenerName]);
You are attaching the event listeners before declaring them. You need to declare listener1 and so on before your for loop
innerHtml does not exist. The right syntax is innerHTML
Here is a working example:
<!DOCTYPE html>
<html>
<body>
<button id="button-listener1">Try 1</button>
<button id="button-listener2">Try 2</button>
<button id="button-listener3">Try 3</button>
<button id="button-listener4">Try 4</button>
<p id="demo"></p>
<script>
var listener1 = function() {
document.getElementById('demo').innerHTML = "1";
}
var listener2 = function() {
document.getElementById('demo').innerHTML = "2";
}
var listener3 = function() {
document.getElementById('demo').innerHTML = "3";
}
var listener4 = function() {
document.getElementById('demo').innerHTML = "4";
}
var selector = "[id^=button]";
var allButtons = document.querySelectorAll(selector);
for (var button of allButtons) {
var listenerName = button.id.slice(button.id.lastIndexOf("-")+1);
button.addEventListener("click", window[listenerName]);
}
</script>
</body>
</html>
your line button.addEventListener("click", listenerName); tried to add a function called listenerName to the click event, and since listenerName is a variable and not a function, it doesn't work.
You could use an array of function to make it work instead.
var array_of_functions = [
'listener1' : listener1,
'listener2' : listener2,
'listener3' : listener3,
'listener4' : listener4
]
and then in your loop you could create the listener by giving the right function:
button.addEventListener("click", array_of_functions[listenerName]);
Also, make sure you create the function and the array before running the loop or they won't exist yet when the code runs.
There's a slightly easier way to do this - just have one function that handles the event:
for (var button of allButtons) {
button.addEventListener("click", handleClick, false);
}
function handleClick() {
var id = this.id.match(/button-listener(\d)/)[1];
document.getElementById('demo').innerHTML = id;
}
DEMO
Or, you can change your loop like this and your code will work
allButtons.forEach(function (button, i) {
var listenerName = button.id.slice(button.id.lastIndexOf("-") + 1);
button.addEventListener("click", function () {
document.getElementById('demo').innerHTML = i + 1;
});
});
I want to generate functions for an event by using a loop. Surely in the example below, when pressing the button, it will gives the value 100 and not 1.
<body>
<button id="b1">klickMeNow</button>
<script>
var i=1;
document.getElementById("b1").addEventListener("click", function() { alert(i);}, false);
var i=100;
</script>
</body>
I came up with this solution using a generate function:
<button id="b1">klickMeNow</button>
<script>
var i=1;
document.getElementById("b1").addEventListener("click", generate(i), false);
var i=100;
function generate(i1) {
f = function () {alert(i1);};
return f;
}
</script>
Is there a more elegant solution without writing a generate function?
Are you looking to for a simple counting function?
var count = (function() {
var c = 0;
return function() {
return ++c;
}
}());
document.getElementById('b1').onclick = function() {
alert(count());
}
<button id="b1">Click Me</button>
Oh sorry for the confusion.
If you run the first snippet it gives 100 as a result, but I want that it prints 1, the actual value when I bind the function.
1)
document.getElementById("demo").addEventListener("click", function(){
document.getElementById("demo").innerHTML = "Hello Worl";);
2)
document.getElementById("demo").onclick = function()
{document.getElementById("demo").innerHTML = "HelloWorld!";}
Please help. I think both are different ways to do the same thing. But the second method is not working.
You could try to add the onclick in the Html:
<button value="Some Text" onclick="click()" id="demo"></button>
<script>
function click(){
document.getElementById("demo").innerHTML="Hello World";
}
</script>
Another Method:
onload = demo;
function demo() {
var demo = document.getElementById("demo");
demo.onclick = click;
}
function click(){
document.getElementById("demo").innerHTML="Some text";
}
I hope this was helpful. If not leave a comment.
You didn't add your closing bracket
document.getElementById("demo").addEventListener("click", function(){
document.getElementById("demo").innerHTML = "Hello Worl";
);
should be
document.getElementById("demo").addEventListener("click", function(){
document.getElementById("demo").innerHTML = "Hello Worl";
});
The second method should work fine, are you sure you have a proper element on the page with this id?
Here's a fiddle with this example
https://jsfiddle.net/wvty8rpc/1/
Can someone help me get started with a button timeout feature. All I want is a button (when clicked) it becomes inactive for 2 seconds. After which it is active again.
<input type="button" value="click" id="click" onclick="foo(this);"/>
function foo(obj) {
obj.disabled = true;
setTimeout(function() {
obj.disabled = false;
}, 2000);
}
LIVE DEMO
window.setTimeout on MDN:
Executes a code snippet or a function after specified delay.
Start of with:
<button>Click me!</button>
Add an event:
<button onClick="...">Click me!</button>
Now we need to put something in place of that ....
this can be used to mean "the button that was just clicked"
this.disabled can be set to true or false to disable (or re-enable) the button.
setTimeout(function() {...},2000); executes the anonymous function after two seconds have passed (or as near as the timer resolution allows).
Again, need to put something in the .... I've already told you how to re-enable the button.
Although, since this isn't terribly reliable inside anonymous functions, it's probably better to start with var t = this; and use t to mean the button.
With all that in place, you have:
<button onClick="var t = this; t.disabled = true; setTimeout(function() {t.disabled = false;},2000);">Click me!</button>
Done. I hope this explanation was helpful.
PS. To those who are against inline event handlers:
This is an example
The OP is a beginner
An inline event is good enough
The function setTimeout allows you to specify a function to be called after an amount of milliseconds has passed. In this case, I passed in an anonymous function, that is, a function that does not have a name that is used for the sole purpose of re-enabling my button after 2 seconds.
var mybutton = document.getElementById("mybutton");
mybutton.onclick = function() {
mybutton.disabled = true;
setTimeout(function() {
mybutton.disabled = false;
}, 2000);
};
Live example
You can use setTimeout() function in javascript. Something like
<html>
<head></head>
<body>
<input id="test" type="submit" value = "clickme" onclick="deactivatefunc()">
<script type="text/javascript">
function deactivatefunc()
{
var btn = document.getElementById("test");
btn.disabled = true;
var mytimer = setTimeout(activate,2000);
}
function activate () {
var btn = document.getElementById("test");
btn.disabled = false;
}
</script>
</body>
</html>
I am a beginner in javascript, can you tell me what's wrong with the below code?
I want this to invoke buttonPressed() when a button gets pressed. From buttonPressed() it should call changeColor1(), changeColor1() should change the text color of a paragraph, and start a timer to invoke changeColor2(). Similarly changeColor2() should also change the color and call changeColor1() once the timer expires.
<html>
<head>
<script type="text/javascript">
function changeColor2()
{
alert("2");
var v = document.getElementById("onet");
v.style.color = rgb(0,255,255); // this statement is not working
var t=setTimeout(changeColor1,3000);
}
function changeColor1()
{
alert("1");
var v = document.getElementById("onet");
v.style.color = rgb(255,255,0); // this statement is not working
var t=setTimeout(changeColor2,3000);
}
function buttonPressed()
{
alert("Hello");
changeColor1();
}
</script>
</head>
<body>
<p id="onet"> Hello how are you? </p>
<form>
<input type="button" value="Display alert box!" onClick="buttonPressed()" />
</form>
</body>
</html>
Do not invoke the function, pass the reference only:
var t=setTimeout(changeColor2,3000);
I think you want style.color not .color.
By the way... please tell us what the code is supposed to actually do and what is wrong initially.
You need to quote style property values-
v.style.color = 'rgb(255,255,0)';
1) I don't like the fact that you have two timeouts set. Just call one function and use a flag to toggle between the two options.
2) The parameter to setTimeout that you want to use is a function pointer (changeColor) not the result of a function call (changeColor())
var flag = false;
var t;
function changeColor()
{
var v = document.getElementById("onet");
if(flag){
v.color = rgb(255,255,0);
} else {
v.color = rgb(0,255,255);
}
flag = !flag;
}
function buttonPressed()
{
alert("Hello");
t=setInterval(changeColor,3000);
}
Not really knowing what it is you're trying to do, I can tell you that your button's onClick handler references a method name that isn't in your code. Judging by the names of your methods, I think you meant to put "buttonClicked" in there.
Nevermind, looks like you changed it while I was typing.
Instead of v.color = rgb(0,255,255); use v.style.color = "#0ff".