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>
Related
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.
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();
http://ahmedstudio.za.pl/firefoxerror/
It works in chrome, opera but doesn't get along with Firefox.
The whole javascript thing is not applying.
This is directly in my javascript.js:
window.onload = function() {
todo("body", 50);
alert("alert!");
setTimeout(function () {
todo("body", 0);
}, 1000)
}
function todo(element, size) {
//blahblah
}
Even if it doesn't actually solve your problem I'd like to share my findings about replacing event handlers with invalid function calls. I've composed this little fiddle:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
jQuery(function(){
$("body").on("load", function(){
$(this).append("Should not run")
});
});
</script>
</head>
<body onload="doesNotExist()">
</body>
</html>
Firefox, Explorer and Edge actually replace the <body> event handler. However, Chrome ignores the onload="doesNotExist()" and execute previous handler.
In the land of tag soup it's hard to decide which workaround is the correct one but it's definitively a bug that could explain your symptoms.
function load() {
//do stuff
}
and the appropriate
<body onload="load()"> </body>
This runs fine in me. I even tried to create a dummy page with this snippet but could not replicate it.Here is snippet.Since the snippet you shared does not contain jquery , i opt to use same code .
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<script>
window.onload = function(){
_todo({
a:'body',
b:50,
alertFrom:'window.onload'
});
setTimeout(function(){
_todo({
a:'body',
b:0,
alertFrom:'setTimeOut'
});
},1000);
};
function _todo(options){
var a = options.a;
var b = options.b;
var c=options.alertFrom
alert(c +" "+a +" "+b);
};
</script>
</body>
</html>
Also note that there is a importance of semicolon after a function.
Here are couple of snapshots
Why does javascript work fine here: Fiddle
But not when I save it and wrap javascript in script html tags inside body tags, and then open in a browser. Checkboxes don't respond and all columns are shown in browser, whereas some columns should be hidden by default.
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>čezožinski odnosi</title>
<link rel="stylesheet" type="text/css" href="timeline.css">
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.js"></script>
<script>
$(document).ready(function() {
if($("#opt1").is(":checked")){
$("#col1").show();
$(".data1").show();
}else{
$("#col1").hide();
$(".data1").hide();
}
if($("#opt2").is(":checked")){
$("#col2").show();
$(".data2").show();
}else{
$("#col2").hide();
$(".data2").hide();
}
if($("#opt3").is(":checked")){
$("#col3").show();
$(".data3").show();
}else{
$("#col3").hide();
$(".data3").hide();
}
if($("#opt4").is(":checked")){
$("#col4").show();
$(".data4").show();
}else{
$("#col4").hide();
$(".data4").hide();
}
$("#opt1").live('click', function() {
if($("#opt1").is(":checked")){
$("#col1").show();
$(".data1").show();
}else{
$("#col1").hide();
$(".data1").hide();
}
});
$("#opt2").live('click', function() {
if($("#opt2").is(":checked")){
$("#col2").show();
$(".data2").show();
}else{
$("#col2").hide();
$(".data2").hide();
}
});
$("#opt3").live('click', function() {
if($("#opt3").is(":checked")){
$("#col3").show();
$(".data3").show();
}else{
$("#col3").hide();
$(".data3").hide();
}
});
$("#opt4").live('click', function() {
if($("#opt4").is(":checked")){
$("#col4").show();
$(".data4").show();
}else{
$("#col4").hide();
$(".data4").hide();
}
});
});
</script>
</head>
It seems that you have not included jquery.js file in to your example, in the reference JSFiddle example they have included jQuery 1.7.2,
<script>
$(document).ready(function() {
</script>
to run above code jquery file should be included into your document.
You are referring Jquery 1.11+, and using $("#opt4").live(..)
Live is depricated on Jquery 1.7+
use $("#opt4").on() instead. (use .on wherever you used .live)
see this is working.
I am having a problem with my code, which is a mix of jquery and plain javascript. I use jquery to show and hide some divs and the js to refresh a div by loading a page inside the div. The plain js code doesn't work as is, but if I delete the jquery code it works fine.
My code :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ton plans</title>
<link href="template/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#refresh').fadeOut().load('last_post.php').fadeIn();
}, 10000);
</script>
<script type="text/javascript" src="js/jquery-1.9.0.min.js"></script>
<script type="text/javascript">
//no conflict jquery
jQuery.noConflict();
//jquery stuff
(function($) {
$(document).ready(function()
{
$("#bott_div").click(function() {
$("#div_profile").show(['fast'])
})
$("#page").click(function() {
$("#div_profile").hide(['fast'])
})
})
})
(jQuery);
</script>
</head>
There is a conflict between the jQuery code and the plain javaScript that is preventing it from working properly. I would require help identifying the problem.
Change the order of the first two scripts -- like this
<script type="text/javascript" src="js/jquery-1.9.0.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#refresh').fadeOut().load('last_post.php').fadeIn();
}, 10000);
</script>
There is a "(" in front of your function in jQuery code. Encapsulate code in a
$(document).ready(function() {
$("sampleSelect").click(function() {
//code
}
});