Why doesn't 'this' keyword work in following html code? - javascript

I want an alert with "button text"
this doesn't work:
<button onclick="fun()">button text</button>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script>
function fun(){
alert($(this).html()); //I've also tried $(this).val() and $(this).text()
}
</script>
but following works fine:
<script>
function fun(){
alert("some plain text");
}
</script>

The this you're trying to log is the Window object, on which you can't use innerHTML. Instead, pass the context of the button element.
function fun(context) {
alert($(context).html());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="fun(this)">button text</button>

I realize you've already accepted an answer, but none of the answers you received addressed your question. Please consider the following:
The HTML attribute for the on- type handlers were designed from the beginning to take raw JavaScript code and wrap that code into a function. That function is provided with the event object and the context set to the keyword this as the element receiving the event. So the first button in my solution below is the proper way to accomplish what you were attempting to do.
Ref: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Event_handlers#Event_handler's_parameters_this_binding_and_the_return_value
The same can be accomplished by setting the DOM Element's on- event property to the function name. This is seen in the second button example. Note that when the DOM property is used, the event is passed and the context set the DOM element too.
Now, the reason something like onclick="fun(this)" and its variants work in these answers, is because that is being wrapped inside a function which is executed with the this keyword set the context of the DOM element (just as described above). So it is a function calling a function and passing the current context - and an anti-pattern.
That should really answer your question.
document.querySelector('#otherButton').onclick = fun;
function fun() {
alert($(this).html());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="alert($(this).html());">button text</button>
<button id="otherButton">other button</button>

The following works:
<button onclick="fun(this)">button text</button>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script>
function fun(myButton){
alert($(myButton).html()); //I've also tried $(this).val() and $(this).text()
}
</script>
Within fun, this will not be your button, because fun is not called on the button.
The following also works:
<button onclick="fun.apply(this)">button text</button>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script>
function fun(){
alert($(this).html()); //I've also tried $(this).val() and $(this).text()
}
</script>
This code causes this to be defined in the manner you tried to use it.

Because you call fun() as a free function but not as a method. Being called as a function the fun() receives this set to global namespace.
In order to call fun with this set to what you want you shall be specific, for example like this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="fun.call(this)">button text</button>
<script>
function fun(){
alert($(this).html()); //I've also tried $(this).val() and $(this).text()
}
</script>

Using a native js event handler does not give the this context for jquery. The dom element that you clicked on is available through
function fun (e) {
let el = e.target // currentTarget, etc.
}

Related

Pass event object to trigger function in firefox

This is the MCVE of the problem I'm having. Let say I have this very simple test page:
<html>
<header>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
function testMethod(e){
alert(e.target.id);
}
$(document).ready(function(){
$("#btn_test").on("click", testMethod, event);
});
</script>
</header>
<body>
<input type="button" id="btn_test" value="OK" />
</body>
</html>
You can find the jsfiddle here.
In Chrome or IE, when I push the button, the id will be displayed in a message box. But in Firefox since window.event is not defined, I cannot bind testMethod to the button's onclick event.
I know that if I'm writting it inline, I can pass the event like this:
onclick="testMethod(event)"
But how can I pass event to my function in Firefox without writing it inline?
Usually, when you subscribe to an event using on or addEventListener, the event object is passed as a parameter to a callback. You never have to pass it explicitly when you register your callback. So this will do:
$("#btn_test").on("click", testMethod);
The problem with your code on Firefox is that there is no global event property and you get an error:
ReferenceError: event is not defined
and your event subscription never gets registered.
remove the the 3rd parameter it works on firefox.
$("#btn_test").on("click", testMethod);
If you refer to the jQuery Reference here, you'll notice that the third parameter has to be the handler. So, simply remove the third parameter and pass the handler to achieve this.
Check out the demo fiddle here.
<body>
<input type="button" id="btn_test" value="OK" />
</body>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
function testMethod(e){
alert(e.target.id);
}
$(document).ready(function(){
$("#btn_test").on("click", testMethod);
});
</script>

How to write jQuery code or call jQuery function in onclick attribute

Why doesn't this simple code work?
<div onClick="myFunction()"></div>
$(document).ready(function(){
function myFunction(){
alert("sss");
}
})
The JS file is external and it's called in the head of my HTML page. The jQuery library is added before that.
It doesn't work as functions called from the on* event attributes need to be within scope of the window. Your code places the function within the jQuery document.ready handler instead. Try this:
function myFunction() {
alert("sss");
}
<div onClick="myFunction()">Click me</div>
You should note though, that using on* event attributes is considered outdated for this reason, amongst many. You should instead use unobtrusive JS code to attach your event handlers, either in native JS:
document.querySelector('div').addEventListener('click', function() {
alert("sss");
});
<div>Click me</div>
Or jQuery, as you seem to be using it already:
$(function() {
$('div').on('click', function() {
alert("sss");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Click me</div>
First Go and read tutorials of html and Jquery at some tutorial websites like This or thisone.
and answer to your code is
HTML
<button onclick="myFunction()">Click me</button>
Javascript
function myFunction() {
alert('Hello');
}
Assuming you included JQuery libraries.

Textarea keypress not working

My code won't work. It's supposed to alert whenever a user presses a key while focused inside of a textbox element!
$("#yourcode").keyup(function() {
alert("I found Hogwarts.");
});
You need to wait until the DOM is ready before adding the keyup handler. This can be achieved by calling .ready() after using $() to get a DOM reference to the document (i.e. $(document)). Also make sure you load jQuery before you load the script:
JS:
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script>
$(document).ready(function(){
$("#yourcode").keyup(function() {
alert("I found Hogwarts.");
});
});
</script>
HTML:
<textarea id="yourcode"></textarea>
Here is a working example (also available in this jsFiddle):
$(document).ready(function(){
$("#yourcode").keyup(function() {
alert("I found Hogwarts.");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="yourcode"></textarea>

Call JS function for specific id in HTML

I have below function in JS file name as hello.js inside js folder.
JS
function hello(){
alert('hello world !);
}
HTML
<!DOCTYPE HTML>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" src="js/hello.js"></script>
<script>
$(function() {
$("#hello").hello();
});
</script>
</head>
<body>
<button type="button" id="hello">Click Me!</button>
</body>
</html>
How do I attach the hello() function to the button with the id="hello"? I'm doing something wrong but I can't find what.
Edit : I recommend reading all answers for completeness.
Edit2: The purpose of this question was to clarify the general method of attaching functions to specific elements on html. The button and the click interaction was an example.
You are probably looking to bind click event on button with id hello using hello as handler
$("#hello").click(hello);
There are many ways to handle events with HTML or DOM.
Defining it in HTML
<button type="button" id="hello" onclick="hello();">Click Me!</button>
Using JQuery
$("#hello").click(hello);
Attaching a function to the event handler using Javascript:
var el = document.getElementById("hello");
if (el.addEventListener)
el.addEventListener("click", hello, false);
else if (el.attachEvent)
el.attachEvent('onclick', hello);
function hello(){
alert("inside hello function");
}
Useful links
MDN - onclick event
SO - Ans 1
SO - Ans 2
Use .on() to bind event handler.
$("#hello").on('click', hello);
Pure javascript:
var elm=document.getElementById("hello");
elm.onclick= function{ hello();};
Jquery:
$("#hello").click(hello() );

windows.onload function not working

i want to execute two function as soon as my page load , i have used onload in body tag and windows.onload in script but both are not working.
here is my code
<html>
<head>
<title>(Type a title for your page here)</title>
<script type="text/javascript">
function my_code(){
alert(" Alert inside my_code function");
var text_val = document.getElementById("t2");
text_val.select();
}
window.onload=my_code();
</script>
</head>
<body >
<form name=form1 method=post action=''>
<input type=text name=t1 value=plus2net id="t2">
</form>
</body>
</html>
Substitution or addition to code both are accepted , give some link where i get more information.
thanks in advance
Changing this :
window.onload=my_code();
To this should do it:
window.onload=my_code;
The reason why: my_code() causes the function to be executed. Without () you are passing the function as a reference to the onload event on the window. The onload event when fired will execute the function.
Even better is using the event setter addEventListener. When other code (like jQuery or other libraries) use the window.onload, using addEventListener wouldn't cause the onload event to be overwritten.
window.addEventListener("load", my_code, false); //you need to omit the "on" when assigning with this method.
This is the preferred way.

Categories