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>
Related
Attempting to remove and reapply function to the onmouseover event of an element. Not sure how to go about this, have attempted several ways without any luck.
<!DOCTYPE html>
<html>
<body>
<button id="my_button" onmouseover="myFunction(this)">Try it</button>
<script>
function myFunction(ele) {
alert("hi")
document.getElementById("my_button").onmouseover = "null";
document.getElementById("my_button").onmouseover = "myFunction(this)";
}
</script>
</body>
</html>
The issue is that you're setting the button onmouseover property to a string in myFunction instead of to a function object.
The HTML parser creates an anonynmous handler function from the onmousever attribute value for you, but setting the button property to a string in JavaScript won't create such a function. Try
<!DOCTYPE html>
<html>
<body>
<button id="my_button" onmouseover="myFunction.call(this, event)">Try it</button>
<script>
function myFunction(event) {
alert("hi, this.tagName = " + this.tagName)
document.getElementById("my_button").onmouseover = "null";
document.getElementById("my_button").onmouseover = myFunction; // a function object
}
</script>
</body>
</html>
Notice I've modified myFunction to see the button object as its this value, and its argument to be the mouse event raised for the click, and changed the call in the handler generated by the HTML to call myFunction as if it were the actual event handler. This was to keep the calls to myFunction seeing the button as its this value and event as its argument in both cases.
For more about the handler created by the HTML parser see a previous answer (disclaimer: of mine) to 'this inside event handler from HTML attribute' that goes into greater detail.
Note that for various reasons it is no longer recommended to create event handlers using oneventname attribute values in HTML when you can add them using element.addEventListener in JavaSript as part of initialization.
you can use :
<button id="my_button" onmouseover="alert('hi')">Try it</button>
try
<!DOCTYPE html>
<html>
<body>
<button id="my_button" class="mousemove" >try it</button>
<script>
document.getElementsByClassName("mousemove")[0].onmousemove = function(){
alert("hi")
document.getElementById("my_button").onmousemove = function(){ return null }
}
</script>
</body>
</html>
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.
}
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.
Hey guys am new to javascript web development.I have been through preventDefault() through my code.But when i used it it returns the error ..My code
<html>
<body>
function preventDef(event) {
event.preventDefault();
}
document.querySelector('a').addEventListener("click",
preventDef(event),false);
</script>
click here
</body>
</html>
When i use this code and clicked on the link it redirects me to google.com ..what i need is the event must be blocked my preventDefault() function..
Hope you guys can help me out ..Thanks
You are calling the preventDef function instead of passing it by reference.
document.querySelector('a').addEventListener("click", preventDef, false);
// ^^^ don't call the function
EDIT: Another issue is that you are running this before the DOM is ready. You need to move the <script> tag down to be after the <a>.
<html>
<body>
click here
<script>
// ^^ did you miss an opening script?
function preventDef(event) {
event.preventDefault();
}
document.querySelector('a').addEventListener("click", preventDef, false);
// ^^^ don't call the function
</script>
</body>
</html>
I have this code:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('a.one').click(function(event){
event.preventDefault();
});
});
function test(event){
event.preventDefault();
}
</script>
<style type="text/css">
a.test { font-weight: bold; }
body { font-family:sans-serif; background-color:#AAAAAA;}
</style>
</head>
<body>
<a class="one" href="http://jquery.com/">jQuery</a>
<br/>
<a class="two" href="http://stackoverflow.com/" onclick='test(event)'>stack overflow</a>
</body>
</html>
The test-function does not work as it stands now, since a regular javascript event doesn't support the jQuery event preventDefault-function. Is there some way to wrap a regular javascript event in a jQuery event so that I can use e.g. preventDefault?
Try this:
function test(e) {
$.Event(e).preventDefault();
}
Event object
I've found the best way to wrap a native event in a jQuery event is with fix:
event = $.event.fix(event);
Please note, this function is not part of the public API (although it really should be).
I think it may be the fact that you're passing event in with onclick='test(event)'. I think onclick='test' is enough. I could be wrong though.
Yes (see Darin's answer). You could also work around IE's lack of preventDefault instead (which is essentially what jQuery is doing):
if ('preventDefault' in event)
e.preventDefault();
else
e.returnValue= false;
When you just want to execute the javascript - and not redirect - when clicking the href use "return false" in your click function. For example:
$(function(){
$('a.one').click(function(event){
var condition = confirm('Do you want to redirect to ...?');
return condition == true;
});
});
If you never want the link to redirect use 'javascript:void(0);' as href attribute, all browsers will still render it as a link instead of an anchor (some IE version do this).