I tried doing this but it didn't seem to work:
window.onload = initAll;
function initAll(){
document.getElementsByTagName('a').onclick = clickHandler;
}
function clickHandler(){
if(this.toString().indexOf("localhost") < 0) {
confirmation = confirm("You are now leaving http://soso.com. Please click 'ok' to continue to this site, or 'cancel' to stay in http://soso.com");
if (confirmation == false){
return false;
}
}
}
I know I can getElementById and that works, but it doesnt work this way. Any help would be appreciated.
Thanks!
To pass an event and parameter onClick in React:Pass an inline function to the onClick prop of the element. The function should take the event object and call handleClick . Pass the event and parameter to handleClick .
click() The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event.
To add the click event in React using plain JavaScript, you need to use addEventListener() to assign the click event to an element. Create one <button> element as ref props so that it can be accessed to trigger the click event.
You should use addEventListener() instead."
document.getElementsByTagName('a') returns a NodeList of DOM Elements. So for starters, you will have to iterate over them and attach a handler to each like this :
var links = document.getElementsByTagName('a');
for( var i=0,il = links.length; i< il; i ++ ){
links[i].onclick = clickHandler;
}
If there are many elements, I suggest you read about event delegation and assign just one handler for everything.
function initAll()
{
var elements = document.getElementsByTagName('a'); // returns an array
// add the handler to each element
var n;
for (n = 0; n < elements.length; ++n)
elements[n].onclick = clickHandler;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With