Javascript Execute onclick event stored in variable - javascript

I've created the function below to identify an onclick event which is dynamically generated with each page load. I'm able to get the onclick event into a variable (developer console output shown below). I want to execute that onclick event but can't find a good way of doing that. Any assistance is appreciated.
"ƒ onclick(event) {
mstrmojo.dom.captureDomEvent('*lK1129*kWA92AF1C396244F28902B3171F9642E57*x1*t1530820506700','click', self, event)
}"
function applyAll() {
//Get the self Link to click it
var linkBys = document.getElementsByClassName("mstrmojo-DocTextfield-valueNode");
// loop through each result
for(y = 0;y < linkBys.length;y++){
// retrieve the current result from the variable
var linkBy = linkBys[y];
// check the condition that tells me this is the one I'm looking for
if(linkBy.innerText.indexOf("link") !== -1){
// Find the right class
var idy = document.getElementsByClassName("mstrmojo-DocTextfield-valueNode")[y].onclick;
console.log(idy);
}
}
}

If the property 'onclick' is defined as a function, you can just run it as a function.
var idy = document.getElementsByClassName("")[y].onclick();
You could also handle it another way:
var idy = document.getElementsByClassName("")[y].onclick;
idy();

onclick is not an event, it's a function which gets executed when element is clicked. If you want to simulate click you can do element.click()

If you used:
element.addEventListener('click',()=>...);
instead of:
element.onclick=()=>...
then all you have to do is:
document.getElementsByClassName("mstrmojo-DocTextfield-valueNode")[y].dispatchEvent(new Event('click'));

You can call the function returned , adding parens:
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function foo() {
var idy = document.getElementsByClassName("mstrmojo-DocTextfield-valueNode")[0].onclick;
console.log(idy);
idy();//like so
}
function alertMe() {
alert('Hello');
}
</script>
</head>
<body>
<button id="btn" class="mstrmojo-DocTextfield-valueNode" onclick="alertMe();">No click</button>
<button id="btn2" onclick="foo()">Click me</button>
</body>
</html>

Related

How to change onclick of element onclick without immediately running?

When I click a button I want to change the onclick of the html tag.
Here's my code:
JavaScript:
function reset() {
//some code 1
}
function hit() {
//some code 2
document.getElementById("htmlId").onclick = reset;
}
HTML:
<!DOCTYPE html>
<html id = "htmlId">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width height=device-height">
</head>
<body>
<button id = "btn1" onclick = "hit();" class = "btn">Hit</button>
<script src="script.js">
</script>
</body>
</html>
When I click the button I expect for some code 2 to execute and on my next click for some code 1 to execute. But when I click both some code 1 and some code 2 execute immediately.
If you add an empty onclick before it, reset(); still runs.
JavaScript:
function empty() {
}
function hit() {
//some code 2
document.getElementById("htmlId").onclick = empty;
document.getElementById("htmlId").onclick = reset;
}
How can I fix this?
There are a few things going on here that are interesting to address:
You have JavaScript in HTML attributes which is no longer considered good practice.
Dealing with the whole HTML element and a button inside of that element that you want to manage will lead to bubble and capture issues
You want to change the listeners on elements but you are using the onclick property while modern practice is to use addEventListener and removeEventListener.
Here are my suggestions:
Put all of the JavaScript listeners in the JS file; your HTML should be free of JavaScript.
Use addEventListener instead of assigning to onclick.
Because event listener adding and removing can be tricky, consider using a variable that records whether the button has been pressed. Then your html click listener does a reset only if in that state.
So something like (code is not tested, but should get you started):
let shouldReset = false;
document.getElementById("btnId").addEventListener('click', (e) => {
shouldReset = true;
e.stopPropagation(); // so the big HTML element doesn't get it
}
document.getElementById("htmlId").addEventListener('click', () => {
if (shouldReset) {
reset();
}
}
So clicks on the html element do nothing unless the button has been first clicked. Hope that helps.
Simply create another function, and attach that once the first function has executed:
function hit() {
// you initial hit() function's code here
document.getElementById("btn1").onclick = '';
setTimeout(function(){
document.getElementById("btn1").addEventListener('click', function() {
/* define the next function */
})
}), 1);
};
or to better apply to your case :
function reset() { ... }
function hit() {
// you initial hit() function's code here
document.getElementById("btn1").onclick = '';
setTimeout(function(){
document.getElementById("btn1").addEventListener('click', reset)
}, 1);
};
This can be improved in many ways, but for the scope of your question it should do just fine.

Javascript functions still remain after loading another partial

let's suppose the browser rendered following page
<html>
...
<body>
<div id="partialContainer">
<script>
function saveItems(){
/* do somthing*/
}
</script>
<input type="button" id="btnTest" name="btnTest" value="Test" onclick="saveItems()"/>
</div>
</body>
</html>
after an AJAX call and change the "partialContainer" content using
$("#partialContainer").html(returnedMarkup)
saveItems function still remains in page and can get executed
how can remove this function when markup get replaced to avoid name colissioning
var saveItems = function () {}
After your Ajax, assign some other value to it, preferably the one above.
Try setting saveItems to undefined
$("#partialContainer").html(returnedMarkup);
if (!!saveItems && $.isFunction(saveItems)) saveItems = void 0;
You could put your function in an object literal:
var obj = { saveItems: function() { } }
and delete it after the ajax
delete obj.saveItems
On your ajax success callback function, just do:
$("#btnTest").prop( "onclick", null );
Be aware that $.removeAttr('onclick') will fail in ie 6-8, so .prop() is better.

Javascript - Function to use onclick?

I want to create a function and then use with onclick method, for example:
one = document.getElementById("oneID");
then instead of writing function for each onclick():
one.onclick = function(x) {
tempStack.push(parseFloat(one.value));
viewTemp.value += one.value;
}
I want to use a single function:
one.click = input(one);
but I'm not sure how to do it in the correct way for example the below I tried, doesn't work:
var input = function(x) {
tempStack.push(parseFloat(x.value));
viewTemp.value += x.value;
}
Lastly, no external JavaScript libraries to aid this question, vanilla JavaScript.
You'll need to pass a function as a reference, not call it:
one.onclick = input;
In this case you won't be able to pass an argument, but you can use this as a reference for the DOM element on which event is fired:
function input() {
tempStack.push(parseFloat(this.value));
viewTemp.value += this.value;
}
Here's a method with using JavaScript's .addEventListener(), as a previous answer mentioned, using this to pass through the DOM Node Element to use within the inputFunction.
<input type="text" value="64.23" id="bt" />
<script>
function inputFunction( x ) {
console.log( x.value ); //Console Logs 64.23
}
var bt = document.getElementById("bt");
bt.addEventListener( 'click', function(){ inputFunction( this )}, false );
</script>
Fiddle: http://jsfiddle.net/Lhq6t/
Think about functions as a normal objects, so the way is:
function input (event) {
// Process the event...
// event is my event object
// this is the object which trigger the event
// event.target is my button
}
on.onclick = input;
You must assign the input function as a normal variable.
The function input will receive an event object as parameter. Also you can refer to the button clicked with this.
Maybe the mozilla developer network or the real w3c site would explain it better.
Your requirement can be achieved by following:
Add this method in your script tag:
function input(x) {
/*tempStack.push(parseFloat(x.value));
viewTemp.value += x.value;*/
alert(x.id);
}
And then call this method onClick event of your buttons / anchors like:
<input type="button" id="oneID" value="oneID" onClick="input(this);"/>
<input type="button" id="twoID" value="twoID" onClick="input(this);"/>
threeID
See working example: http://jsfiddle.net/Avd5U/1/
ok, so just create a function with a parameter in it like:
function setValue(input){
tempStack.push(parseFloat(input.value));
viewTemp.value += input.value;
}
and then call the function on the click of that element like:
var one = document.getElementById("oneID");
one.click = setValue(one);
Good luck!

Onclick button doesn't function

i try to create a button when the page is load.
<!DOCTYPE html>
<html>
<head>
<script>
function createButton(){
var newButton = document.createElement("button");
newButton.onclick="document.write('Tasto premuto')";
var textButton = document.createTextNode("Premi qui");
newButton.appendChild(textButton);
document.body.appendChild(newButton);
}
</script>
</head>
<body onload="createButton()">
</body>
</html>
the button is created succesfully, but the function that I have associated with onClick event doesn't work. any ideas?
onclick expects a function, not a string:
newButton.onclick = function() { document.write('Tasto premuto') };
Please see this jsFiddle
Of course, you should be aware that document.write() completely clears the DOM of all current content, rather than simply appending the string to the existing content.
You're assigning a string to function pointer:
Change:
newButton.onclick="document.write('Tasto premuto')";
To:
newButton.onclick= function(){ document.write('Tasto premuto') };

Javascript Dynamic Event Handling, Not Jquery

here is my code
<html>
<head>
<script type="text/javascript">
window.onload = function(){
sel = document.getElementsByTagName('select');
for(i=0;i<sel.length;i++)sel[i].onclick = function(){alert('');}
}
</script>
</head>
<body>
<div id="ss"></div>
<select></select>
<input type="button" onclick="document.getElementById('ss').appendChild(document.createElement('select'))"/>
</body>
</html>
"onclick" event working for static tag "Select" but not working for Dynamically created "Select". In other word i want to know what is alternate to .live of JQuery in Javascript.
Bind the event to a parent element, that already exists in the DOM:
document.body.addEventListener('click', function (e) {
if (e.target.tagName.toLowerCase() == 'select') {
alert('You clicked a select!');
}
});
JS Fiddle demo.
It would be slightly more sensible to bind the click to an element 'closer' to the form, and if you use getElementById() rather than getElementByTagName() it's more simple, since you don't have to worry about the index of the number you're binding to.
jQuery's live function works by using "Event Delegation". The basic idea is that you bind a listener on a parent element, which is guaranteed to exist when the page loads. Any element below that (with the exception of some) will fire off an event which can be caught by the parent listener. From there you would need to retrieve the target/sourceElement of the event and determine whether or not it's one you care about.
Something like this will work for listening to clicks. Just make sure that any new elements you are adding are located within the proper parent container and have an attribute which distinguishes them from the rest of the clickable elements.
<html>
<head>
<script type="text/javascript">
window.onload = function(){
// get the relevant container
var eventContainer = document.getElementById("EventContainer");
// bind a click listener to that container
eventContainer.onclick = function(e){
// get the event
e = e || window.event;
// get the target
var target = e.target || e.srcElement;
// should we listen to the click on this element?
if(target.getAttribute("rel") == 'click-listen')
{
alert("You clicked something you are listening to!");
}// if
};
};
</script>
</head>
<body>
<div id="EventContainer">
<input type="button" rel="click-listen" name="myButton" value="Listening to this button." />
<input type="button" name="anotherButton" value="Not listening." />
<p>I'm also listening to this a element: listening to this</p>
</div>
</body>
</html>
there's no need to bind the onclick handler to every select every time you add one.
I am not going to retype your whole page, but you'll see what's going on by reading following snippets:
function handler() {
alert('You clicked a select!');
}
window.onload = function(){
sel = document.getElementsByTagName('select');
for(int i= 0; i < sel.length; i++) {
sel[i].onclick = handler;
}
}
function addSelect() {
var slt = document.createElement("select");
document.getElementById('ss').appendChild(slt);
slt.onclick = handler;
}
<input type="button" onclick="addSelect();"/>
You're only setting the onclick when the window loads. All you need to do is put the code currently in the window.onload into a named function, then call it every time you add a new select.
here's the dumb way to do it:
<html>
<head>
<script type="text/javascript">
function update () {
sel = document.getElementsByTagName('select');
for(i=0;i<sel.length;i++)sel[i].onclick = function(){alert('');}
}
window.onload = update;
</script>
</head>
<body>
<div id="ss"></div>
<select></select>
<input type="button" onclick="document.getElementById('ss').appendChild(document.createElement('select'));update();"/>
</body>
</html>
You can use a cross-browser solution as shown below to add event handler dynamically
sel = document.getElementsByTagName('select');
for( i=0; i<sel.length; i++){
if (sel[i].addEventListener){
sel[i].addEventListener("click", clickHandler, false);
} else if (sel[i].attachEvent){
sel[i].attachEvent("onclick", clickHandler);
}else{
sel[i].onclick = clickHandler;
}
}
function clickHandler(event){
}

Categories