This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 1 year ago.
I am new to JS and especially class in JS.
I don't fully understand how classes work. Please help me in the following question.
This is a simple page with a button. I want it to run a function (doThis()) after clicking the button. But it gives an error saying the function is not defined.
class Test {
constructor() {
this.button = document.getElementById("but1");
this.button.addEventListener("click", this.butClick);
}
butClick() {
console.log("clicked");
this.doThis();
}
doThis(){
console.log("Inside doThis")
}
}
t1 = new Test();
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<button id="but1">Click me</button>
<script src="test.js"></script>
</body>
</html>
this.button.addEventListener("click", this.butClick); should be this.button.addEventListener("click", this.butClick.bind(this));.
Without bind(this), the this inside butClick is just the button element, not the class Test.
class Test {
constructor() {
}
butClick() {
console.log("clicked");
this.doThis();
}
doThis(){
console.log("Inside doThis")
}
}
t1 = new Test();
const button = document.getElementById("but1")
button.addEventListener('click', event => {
event.preventDefault()
// Call doThis method on t1, the instance...
t1.doThis()
})
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<button id="but1">Click me</button>
<script src="test.js"></script>
</body>
</html>
I have done some short and helpful article on using classes in JS, should help, go to the article here.
Related
This question already has answers here:
Javascript - arrow functions this in event handler?
(4 answers)
Closed 5 years ago.
Background
I'm just giving jQuery a go and for an hour, I could not hide an element using $([selector]).hide([milliseconds]), which in my sample code, is called when I click the element, in this case the anchor tag <a>. But I got it working in the end, but I don't understand why so. The only change I needed to make using the function keyword, instead, so this:
Note: Examples used this not "a", see edits
event => {
$(this).hide(2000);
}
into this
function(event){
$(this).hide(2000);
}
Question
Why does using function work and using an 'arrow' function doesn't? Is there a difference between the two?
My source code, for testing:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
<style>
a.test{
font-weight: bold;
}
</style>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<!--<script src="https://code.jquery.com/jquery-1.10.2.js"></script>-->
</head>
<body>
jQuery
<script>
// $(document).ready(function () {
// // $("a").click(event => {
// // alert("Thanks for visiting!");
// // //prevents the opening of the link (what are the default events of other events types?)
// // event.preventDefault();
// // //Special Effects - http://api.jquery.com/category/effects/
// // });
// });
$("a").click(function(event){
event.preventDefault();
$( this ).hide(2000);
});
$("a").addClass("test");
</script>
</body>
</html>
Arrow function does not create a new scope tethered to this. So, to get around this, just use a normal function (like bellow). Alternatively, you could do $(event.currentTarget).hide(2000); inside your arrow function.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
<style>
a.test{
font-weight: bold;
}
</style>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<!--<script src="https://code.jquery.com/jquery-1.10.2.js"></script>-->
</head>
<body>
jQuery
<script>
$("a").click(function(event) {$(this).hide(2000)});
$("a").addClass("test");
</script>
</body>
</html>
Hey guys just having an issue with my HTML button not actually running my javascript function when clicked on.
The HTML:
<html>
<head>
<meta charset="utf-8">
<title>PROJECT</title>
<script language="javascript" src="Hangman.js"></script>
</head>
<body>
<input id = "Begin" type = "button" value = "Play">
</body>
</html>
And here's the JS:
function start ()
{
document.getElementById("Begin").addEventListener("click",logic,false);
}
function logic ()
{
document.writeln("yo");
}
window.addEventListener("load", start, false);
Sorry if this is an amateur question, it just so happens I'm an amateur. Thanks you guys in advance!
check this jsfiddle
it is fixed
function start ()
{
document.getElementById("Begin").addEventListener("click",logic,false);
}
function logic ()
{
alert();
}
window.onLoad=start();
I tried to make it so that a string gets logged in the console every time I click on a button. However, nothing is logged. Why so?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function log_a_string_plz() {
console.log("some string i want logged");
}
document.onload = function() {
document.getElementById("my_wonderful_button").onclick = log_a_string_plz;
}
</script>
<title>logging a string test</title>
</head>
<body>
<button id="my_wonderful_button">log a string!</button>
</body>
</html>
I've tried changing event handlers to no avail.
Try:
window.onload = function () {
document.getElementById("my_wonderful_button").onclick = log_a_string_plz;
}
jsFiddle example
When I click on the button nothing happens unless I call the function in the html. I am trying to remove all inline javascript. I have included the commented-out section of html that works. Thanks in advance for the help!
JavaScript:
var welcomeString;
const TEST = 1;
function setWelcomeString() {
"use strict";
welcomeString = prompt("Please enter your name: ", "nobody");
}
function writeOutput() {
"use strict";
document.getElementById("demo").innerHTML = "Hello, " + welcomeString;
}
function main() {
"use strict";
setWelcomeString();
document.getElementById("sayHi").onclick = writeOutput();
}
main();
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>**SET TITLE**</title>
<link href="css/style.css" rel="stylesheet">
<script src="firstScript.js"></script>
</head>
<body>
<h1 id="wiggles">TEMPLATE</h1>
<!--<button id="sayHi" onclick="writeOutput()">Say Hi</button>-->
<button id="sayHi">Say Hi</button>
<p id="demo"></p>
</body>
</html>
When you assign a function as a handler for an event, you need to assign the function itself, not execute the function and assign it's return value as you are doing. Change this:
document.getElementById("sayHi").onclick = writeOutput(); // parens
To this:
document.getElementById("sayHi").onclick = writeOutput; // no parens
Here is a jsfiddle link with a working example.
You have to add your whole code inside load, like this
window.load = function(){
// your javascript here
};
Also, as jbabey mentioned, use either
document.getElementById("sayHi").onclick = function(){ writeOutput();};
Or
document.getElementById("sayHi").onclick = writeOutput;
You have two issues.
The first being covered by jbabey.
The second is that firstScript.js appears before your button. This is problematic as when you are assigning the onClick handler to it. It doesn't exist in the dom.
Try putting the entire main script inside window.onload = function () { ... } or moving it to the bottom of the markup.
I've been working with javascript for a while but never made any classes and my work has been getting messy with tons of unorganized functions. So now I am learning how to use classes, and I have question.
How can I execute functions within a class, example:
<html>
<head>
<script type="text/javascript">
window.onload = function (){
var object = new testClass("test123");
alert(object.content);
}
function testClass (id){
this.object = document.getElementById(id);
this.content = this.getContent(); //<- this is what I want to do
this.getContent = function (){
return this.object.innerHTML;
}
}
</script>
</head>
<body>
<div id="test123">Hello World</div>
</body>
</html>
Basically how can i call upon function inside of the class inside of the class? In the example how can I get this.getContent to return "Hello World".
I know I can do it like :
<html>
<head>
<script type="text/javascript">
window.onload = function (){
var object = new testClass("test123");
alert(object.getContent());
}
function testClass (id){
this.object = document.getElementById(id);
this.getContent = function (){
return this.object.innerHTML;
}
}
</script>
</head>
<body>
<div id="test123">Hello World</div>
</body>
</html>
I am using chrome to test. I am doing this wrong, can it be done? Thanks in advance.
You're calling getContent before creating it.
Move the function call below the assignment.