I wanted to create a Button via JavaScript through a constructor. Everything works fine, but the onclick event starts immediately after loading the page and not after clicking the button.
function Button(text) {
this.button = document.createElement('button');
this.button.id = text;
this.button.innerHTML = text;
this.button.style.width = 100;
this.button.style.height = 30;
document.body.appendChild(this.button);
};
b1 = new Button('button1');
b1.onclick = alert('hello');
It will start on load, because you call it explicitly with alert('hello').
Better "wrap" it:
b1.onclick = function() {
alert('hello')
}
This way you assign a function to b1.onclick event, and this function will be invoked on button click.
When you say b1.onclick = alert("hello");, it thinks that you want whatever the alert() function returns to go into b1.onclick, so it will run the function and find out. What you want is this:
b1.onclick = function(){
alert("hello");
};
This is an actual function object that will be called when b1 is clicked.
In your code you were calling alert, and asigning it's return value to b1.onclick.
function Button(text) {
this.button = document.createElement('button');
this.button.id = text;
this.button.innerHTML = text;
this.button.style.width = 100;
this.button.style.height = 30;
document.body.appendChild(this.button);
};
b1 = new Button('button1');
b1.onclick = function() {
//Handle click here
alert("hello");
};
b1.onclick should be a function.
Related
Im using jQuery too. Im trying to call one method keyPressEvent on pressing enter button. Whats wrong in the code
var AplOperations = function() {
// this function i want to call when an enter button is pressed
this.keyPressEvent = function() {
// my code goes here
}
}
var myOpr = new AplOperations();
document.onkeyup = myOpr.keyPressEvent();
You don't need the () after myOpr.keyPressEvent, other wise the function will be executed intermediately.
Working example: (click first on the panel for the focus)
var AplOperations = function() {
// this function i want to call when an enter button is pressed
this.keyPressEvent = function() {
// my code goes here
var elem = document.getElementById("test");
elem.innerHTML += "key pressed<br>"
}
}
var myOpr = new AplOperations();
document.onkeyup = myOpr.keyPressEvent;
<div id="test"></div>
You have to wait for the keyup and execute your things in callback. Right now it executes when the script gets execute.
document.onkeyup = function () {
myOpr.keyPressEvent();
}
Updated Demo
This line is wrong:
document.onkeyup = myOpr.keyPressEvent();
Using brackets immediately calls the function and the result is assigned to the onkeyup handler. If you remove the brackets your function will be assigned as a handler
Well, I'm using object orientation in JavaScript, but instead of using new, I just call the method from the namespace. In the moment, I have the following code:
var Component = {
Button: function(_text, use_image) {
button = $.createElement('button')
if (use_image != false)
{
button.innerHTML = _text;
}
else
{
button.innerHTML = _text
}
var text = _text
return button
}
}
When I want to return a button, I do:
x = Component.Button("Click me")
And after I can use x. But if I want to change the text of x, I must use x.textContent. I'd like to instantiate this and use a setter to apply its text, this way:
x = new Component.Button("Click me")
x.text = "Don't click me"
document.getElementsByTagName("body")[0].appendChild(x)
And if I try to apply the setter text, it becomes global, I want to have a unique for each button. Mix namespaces with get/set.
Thank you in advance
One way can be like, I am not sure if this is the best approach. Looking for more answers
var Component = {
Button: function(_text, use_image) {
var button = {
node : document.createElement('button'),
setText : function(txt){this.node.innerHTML = txt;}
};
if(_text){button.setText(_text);}
return button;
}
};
x = Component.Button("Click me");
x.setText("Don't click me");
document.getElementsByTagName("body")[0].appendChild(x.node);
y = Component.Button("Click me2");
y.setText("Don't click me2");
document.getElementsByTagName("body")[0].appendChild(y.node);
http://jsfiddle.net/2LCyn/
How about something like this:
var Component = (function($){
var buttonCount = 0;
function Button(text, use_image){
this.id = ++buttonCount;
this.text = text;
this.use_image = use_image;
this.$element = $('<button/>').text(text);
this.bindEvents();
}
Button.prototype.bindEvents = function(){
var that = this;
this.$element.on('click', function(){
console.log('hello, I\'m button ' + that.id);
});
};
Button.prototype.setText = function(text){
this.text = text;
this.$element.text(text);
};
return {
Button: Button
}
})(jQuery);
var button1 = new Component.Button('hello', false);
button1.setText('helloooo');
$('body').append(button1.$element);
var button2 = new Component.Button('world', true);
$('body').append(button2.$element);
http://jsfiddle.net/ATmAx/1/
How can I add an eventlistener to my button? When the button is clicked the function speler1gooien has to run. When I run my example code below the function speler1gooien is fired on page load. What is the correct way to run my function only when clicked?
window.onload = function () {
buttonSpeler1 = document.getElementById("buttonspeler1");
buttonSpeler2 = document.getElementById("buttonspeler2");
tafelp2.src = "images/rechts_" + aantalBekersP2 + ".png";
resultaat = document.getElementById("resultaat");
buttonSpeler1.addEventListener("click", speler1gooien());
};
var speler1gooien = function() {
// some code
}
Remove the parenthesis in the call speler1gooien() because it's causing your function to be executed immediately, and the return value is being passed as the click event handler.
buttonSpeler1.addEventListener("click", speler1gooien);
// ^ removed ()
By removing the parenthesis, you are passing the function object, instead of executing it.
You are trying to attach function speler1gooien as onclick handler, but your code attaches as handler the result of spele1gooien function. Just remove () following name of that function
window.onload = function () {
buttonSpeler1 = document.getElementById("buttonspeler1");
buttonSpeler2 = document.getElementById("buttonspeler2");
tafelp2.src = "images/rechts_" + aantalBekersP2 + ".png";
resultaat = document.getElementById("resultaat");
buttonSpeler1.addEventListener("click", speler1gooien);
};
var speler1gooien = function() {
// some code
}
I am trying to have the setTimeout() function start only after I click a button as opposed to when the page loads. Here is my code:
function convert() {
'use strict';
var utcDate = new Date();
var message;
var output = document.getElementById('output2');
message = 'today is ' + utcDate.toUTCString();
if (output.textContent !== undefined) {
output.textContent = message;
} else {
output.innerText = message;
}
document.getElementById('output2').value = message;
}
button.onclick = setTimeout(convert, 5000);
If you want to start on click of the button. Than you this should be the way:
button.onclick = function() { setTimeout(convert, 5000); }
change
button.onclick = setTimeout(convert, 5000);
to
button.onclick = function () { setTimeout(convert, 5000);}
or you could use jQuery if you are already loading the library for something else
$('#idOfButton').click(function () { setTimeout(convert, 5000);}); //more efficient than $.on()
or another way using jQuery
$('#idOfButton').on('click', function () { setTimeout(convert, 5000); });
As with many tasks in programming, there are many ways to accomplish your task
button.onclick = function(){setTimeout(convert, 5000);}
You need to put the setTimeout part in a function. So that last line would look like
button.onclick = function(){setTimeout(convert,5000)}
I've this piece of code:
function ActivityDialog(_divId, _title) {
function addButton() {
var buttonElement = document.createElement('input');
buttonElement.setAttribute('type','button');
buttonElement.setAttribute('class','button');
buttonElement.setAttribute('id','updateButton-' + id););
buttonElement.onclick = this.updateAction;
};
function updateAction() {
var buttonId = this.id; // correct: this is the Button
this.sendUpdateRequest(stringUrl); // not defined: Need to reference the current ActivityDialog!!!
};
function sendUpdateRequest(url) {
// something...
};
}
As you can see the problem is when I call function sendUpdateRequest; how can I, at the same time, retrieve button infos and call a function?
You might try this...
function ActivityDialog(_divId, _title) {
// Store the ActivityDialog context
var self = this;
function addButton() {
var buttonElement = document.createElement('input');
buttonElement.setAttribute('type','button');
buttonElement.setAttribute('class','button');
buttonElement.setAttribute('id','updateButton-' + id););
buttonElement.onclick = this.updateAction;
};
function updateAction() {
var buttonId = this.id;
self.sendUpdateRequest(stringUrl); // <---------------------
};
function sendUpdateRequest(url) {
// something...
};
}
Because your using updateAction as a event handler, you correctly see that this will be the button that generates the event. Storing the initial context of the ActivityDialog will allow you to maintain access to it even within event handlers.