I'm working on someone's existing code. In the code there are some inline onClick events attached to some input elements, like this one:
<input type="button" id="inputID" onClick="someFunction()"/>
Problem is that I cannot edit that input's HTML, but I can edit the javascript function declaration of that function.
function someFunction(){
//want to console log the ID of the triggering input element e.g. #inputID
}
Is there a way that I could find the ID of the triggering input within the function, without passing any parameters at the time of calling the function (as I cannot edit the HTML)
Don't use inline event handlers. Use event listeners:
function someFunction(event) {
// Use `this` or `event.currentTarget` to get the current target
console.log(this.id);
}
document.getElementById("inputID").addEventListener('click', someFunction);
<input type="button" id="inputID" value="Click me" />
Since you listed in the tags that you're using jQuery, just leave the body of someFunction empty and attach an event listener to your inputs that call that function.
$('[onclick="someFunction()"]').click(function() {
console.log(this.id);
});
https://jsfiddle.net/k8o1umo4/
You can, however it's not cross browser, in IE it's
window.event.srcElement.id
In FF and Chrome, you have to pass it to the inline function like
someFunction(event)
And then you can access it from target property
event.target.id
You could use the global event object to achieve this:
function someFunction() {
var el = window.event.target;
console.log(el.id);
}
Example fiddle
Be aware that this is may have issues in older browsers. An alternative would be to leave the someFunction() empty (as you say that you cannot remove it in the HTML) and instead assign the event handlers through unobtrusive Javascript, from which you can access the element which raised the event through the this reference.
function someFunction() {
console.log(this.id);
}
var el = document.getElementById("inputID")
//remove inline click event
el.removeAttribute("onclick");
//attach click event
el.addEventListener("click", someFunction);
Within the function that was called from addEventListener 'this' will now reference the element from which the event was fired.
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#The_value_of_this_within_the_handler
First Way: Send trigger element using this
<button id="btn01" onClick="myFun(this)">B1</button>
<button id="btn02" onClick="myFun(this)">B2</button>
<button id="btn03" onClick="myFun(this)">B3</button>
<script>
function myFun(trigger_element)
{
// Get your element:
var clicked_element = trigger_element
alert(clicked_element.id + "Was clicked!!!");
}
</script>
This way send an object of type: HTMLElement and you get the element itself. you don't need to care if the element has an id or any other property. And it works by itself just fine.
Second Way: Send trigger element id using this.id
<button id="btn01" onClick="myFun(this.id)">B1</button>
<button id="btn02" onClick="myFun(this.id)">B2</button>
<button id="btn03" onClick="myFun(this.id)">B3</button>
<script>
function myFun(clicked_id)
{
// Get your element:
var clicked_element = document.getElementById(clicked_id)
alert(clicked_id + "Was clicked!!!");
}
</script>
This way send an object of type: String and you DO NOT get the element itself. So before use, you need to make sure that your element already has an id.
You mustn't send the element id by yourself such as onClick="myFun(btn02)". it's not CLEAN CODE and it makes your code lose functionality.
in your case it would be:
<input type="button" id="inputID" onClick="someFunction(this.id)"/>
js:
function someFunction(clicked_id){
// Get your element:
var clicked_element = document.getElementById(clicked_id);
// log your element id
console.log(typeof tab);
}
Related
How do I replace the destination URL on a button when using onclick?
<div id="my_button" onclick="window.location.replace('/destination1')">Button<div>
So it would look like this
<div id="my_button" onclick="window.location.replace('/destination2')">Button<div>
The following Javascript code doesn't work though. Why?
<script>
document.getElementById("my_button").onclick="window.location.replace('/destination2')"
<script>
onclick that you have used in tag - is html event attribute, but onclick in tag, that you also tring to change - is div object property.
Both are like "onclick", but it's not the same.
So, if you want to make thing work, do this:
document.getElementById("my_button").onclick = () => window.location.replace('/destination2');
onclick div property need function(callback) not a string
A simple way to do it would be by adding a listener and preventing the default behavior of the event
document
.getElementById('my_button')
.addEventListener('click', function (event) {
event.preventDefault();
window.location.replace('/destination2');
});
working example
element.onclick requires a function to be assigned and differs from the attribute <node onclick=""> where the content will be wrapped up in a function automatically.
If you want to change the attribute, make use of element.setAttribute("onclick", "...");
element.setAttribute("onclick", "window.location.replace('/destination2');");
Behaves similar to:
element.onclick = function() { window.location.replace('/destination2'); };
Another solution would be using the data-attributes which can be accessed by element.dataset.name.
Example:
<div id="my_button" data-path="/destination2" onclick="window.location.replace(this.dataset.path);">Button</div>
And to change it:
my_button.dataset.path = "/otherPath";
<td><input name="SeeUsers" id="SeeUsers" class="SeeUsersButton" value="See Users" type="button" title="#qPages.id#" onclick="ListUsers();"></td>
<script type="text/javascript">
ListUsers=function(){
var userid = $(this).title;
$('.userslistdiv').text(userid);
$('.userslistdiv').show;
};
</script>
I've been trying to bind this input to a jquery click event but couldn't get it to fire. So, I dumped the jquery click function and just used onclick=. Neither one fires the event.
The problem may be that the main page has a cfdiv that dynamically loads content that has the input with the onclick=. But I do this on several pages using jquery datepicker without a problem.
In dev tools I can see the script and it is in the head.
Edited code:
ListUsers=function(el){
var userid = el.title;
$('.userslistdiv').text(userid);
$('.userslistdiv').show;
};
<input name="SeeUsers" id="SeeUsers" class="SeeUsersButton" value="See Users" type="button" title="#qPages.id#" onclick="ListUsers(this);"></td>
If you are trying to fire an event on a dynamically added element you have to first select an element that already existed that encloses the dynamically added element. This could be a div in which you have appended the new element or you can use the document object if you don't know ahead of time where the element will be added.
Javascript needed:(alert added to let you know the event works)
Code Pen example: http://codepen.io/larryjoelane/pen/zrEWvL
/* You can replace the document object in the parentheses
below with the id or class name of a div or container
that you have appended the td tag
*/
$(document).on("click","#SeeUsers",function(){//begin on click event
var userid = $(this).title;
$('.userslistdiv').text(userid);
$('.userslistdiv').show;
//test to see if event fired!
alert("it worked");
});//end on click event
this inside the ListUsers does not refer to the clicked element so you need to pass the clicked element reference as a param
<input name="SeeUsers" id="SeeUsers" class="SeeUsersButton" value="See Users" type="button" title="#qPages.id#" onclick="ListUsers(this);">
then
ListUsers = function(el) {
var userid = el.title;
$('.userslistdiv').text(userid);
$('.userslistdiv').show();
};
--
But since you have jQuery, use jQuery to handle events
jQuery(function ($) {
$('#SeeUsers').click(function () {
var userid = this.title;
$('.userslistdiv').text(userid);
$('.userslistdiv').show(); //it is a function
});
})
I've got a function bound to the onclick event in the html, like so:
<script>
function f1(){ alert('hello world'); };
</script>
<a onclick="f1()">test</a>
I'd like to do something with that function, like bind it to another event. I tried this in jQuery:
var defaultFunction = $('a').attr('onclick');
but defaultFunction is defined as a string rather than the function itself. I can evaluate it with eval(defaultFunction), but that makes me feel dirty. Is there a way I can access the function itself, rather than the string?
i.e. I'd like to be able to call defaultFunction() and do whatever the default onclick behavior bound to the a element is. (In this case, call f1()).
Here's a fiddle that tries to do that, but fails.
see this document.getElementById("id_of_your_element").onclick if that help you, it will return click handler, and you can call that, but its not right to raise events manually
Something like this:
Example
var defaultFunction = $('a').attr('onclick');
var defaultFunctionName = defaultFunction.substring(0, defaultFunction.indexOf('('));
$('div').on('click', function(){
if(typeof window[defaultFunctionName] ==="function")
{
window[defaultFunctionName]();
}
alert('Hello universe!');
});
It's just onclick attribute, no jQuery required:
<script>
function f1(){ alert('hello world'); };
</script>
<a onclick="f1()" id="aa">test</a>
<a id="bb">test2</a>
<script>
bb.onclick = aa.onclick;
// or
bb.onclick = function (){ alert('hello bb'); };
</script>
Use this:
function f1() {
alert('hello world');
};
$('a').on('click', f1);
Here is your fiddle with the fix: http://jsfiddle.net/o8b5j15k/2/
Instead of attempting to copy the function bound inline, you could trigger the click event programatically:
function defaultFunction() {
$("a[onclick]").click(); // change selector to match your actual element
}
http://jsfiddle.net/o8b5j15k/3/
Its best to use addEventListener() you can add all types of events. example: "click", "mousemove", "mouseover", "mouseout", "resize" and many more. the false at the end is to stop the event from traversing up the dom. If you want parent dom objects to also receive the event just change it to true. also this example requires no javascript libraries. This is just plain old javascript and will work in every browser with nothing extra needed.
Also addEventListener() is better than onClick() as you can add an unlimited number of event listeners to a dom element. If you have an onClick() on an element and then set another onClick() on the same element you have overwritten the first onClick(). Using addEventListener() if i want multiple click events to trigger when i click on an element i can do it with no problem.
If you want data about the element that is triggering the event you can pass the event to the function. You will see in my example function(e) e is the event and you can use e or this to target the element that is being triggered. Using e or this i can also get more data about the triggered event. for example if the event was a mousemove or mouseclick i can get the x and y position of the mouse at the time of the event.
<!DOCTYPE html>
<html>
<head>
<title>exampe</title>
</head>
<body>
<a id="test" href="">test</a>
<script>
document.getElementById("test").addEventListener("click",function(e){
alert('hello world');
alert('my element '+e);
alert('my element '+this);
},false);
</script>
</body>
</html>
if you want to have addEventListener call a function just change the 2nd value to the function name like this.
document.getElementById("test").addEventListener("click",f1,false);
this will execute the function
function f1(){ ... }
When you want to remove an event listener just call target.removeEventListener(type, listener[, useCapture]). Very simple and easy to manage.
I've implemented the Google FastButton script into a web page. Following:
Trying to implement Google's Fast Button
The code works great. My question is how do I implement this for multiple buttons. I have several buttons that are dynamically created. I don't want to define each button with its own function. Can I use this script with another function that passes some variable.
For example, <button id="quick" onclick="someFunction(24);">button</button>
Current implementation
new FastButton(document.getElementById('quick'), function() {
alert("hello");
});
<button onclick="onLayerClick(8)">8</button>
Here's one way to do it: According to the link you pasted, the FastButton prototype accepts a function as its second argument (this.FastButton = function(element, handler)) and passes the click event to that function. So if you do something like this:
HTML:
<button id="quick">24</button>
JS:
var myHandler = function(event) {
var el = event.target;
console.log(el.innerHTML);
}
new FastButton(document.getElementById('quick'), myHandler);
Then the myHandler() function will have access to the DOM element where the click event originated (event.target), which will be whatever button was clicked. So you'll have access to that button's innerHTML, or you could put a data-mynumber="24" attribute on the button and use el.getAttribute("data-mynumber") instead of el.innerHTML... However you want to identify the button is up to you.
How do you change the JavaScript that will execute when a form button is clicked?
I've tried changing its onClicked and its onclicked child attributes like so:
$('mybutton').onClick = 'doSomething';
and
$('mybutton').attributes["onclick"] = 'doSomething()';
Neither seem to work. My other options are:
To have two buttons and hide one and show the other.
To have it directed to a function that evals a string and change the string to the function I want to execute.
Neither seem very elegant.
I'm using Prototype as a js library so it that has any useful tools I can use them.
If the original onclick event was set through HTML attributes, you can use the following to overwrite it:
$("#myButtonId").setAttribute("onclick", "myFunction();");
For Prototype, I believe that it would be something like this:
$("mybutton").observe('click', function() {
// do something here
});
EDIT: Or, as it says in the documentation, you could simply specify the function you want to call on click:
$('mybutton').observe('click', respondToClick);
function respondToClick(event) {
// do something here
}
But this is all, again, Prototype-specific.
Using the Prototype framework you can do:
Event.observe("mybutton", "click", clickHandler);
or:
Event.observe("mybutton", "click", function() {
alert("Button clicked!");
});
or:
$("mybutton").observe("click", clickHandler);
or:
$("mybutton").observe("click", function() {
alert("Button clicked!");
});
See the Event class documentation
The general way to set an onclick handler in javascript is to set onclick to a function, by passing it the name of a function directly, not in a string. So if myButton is set to a DOM Element, you would write:
myButton.onclick = doSomething;
So when you click the 'mybutton' button, the doSomething function will be called as doSomething(). For anonymous functions, you can write:
myButton.onclick = function() {
alert("myButton was clicked!");
};
In JQuery it's
$("#myButtonId").click(myFunction);
function myFunction(){
alert("Clicked");
}
Or if you want to put the function inline:
$("#myButtonId").click(function(){
alert("Clicked");
});
If you are using JQuery firstly make sure you use the relevant selector prefix (IE: If your using the Id of the element put a # in front of it). Secondly it's the click method to assign a callback to the click event.
Last I used Prototype, it was something like this:
Event.observe('mybutton', 'click', doSomething);
By the way, your examples might've even worked if you didn't quote the function names.
EDIT: Yes, Element.observe(element, eventName, handler) and someElement.observe(eventName, handler) also work. And don't quote the handler name - you want to pass the function not a string!
I found a solution for your issue with prototype under firefox:
$("#myButtonId").writeAttribute('onclick', ''); // first remove the attribute
$("#myButtonId").observe('click', function () { ... }); // then add the event