Add onClick attribute to any element with this JS snippet

Simple onClick replacement snippet. This method works by using the ID of the element (links, buttons, div’s, etc.).

First example below stops a video by removing the content of a div and then replaces it again.
Second example will hide or show a element. Both scripts can be modified to use ClassName.


script
var BTN_1 = document.getElementById('BTN_ID-1');
var BTN_2 = document.getElementById('BTN_ID-2');

//Do Something
function MyFunction_1() {
	document.getElementById('ELEMENT_ID').innerHTML=''; //Removes the div
	document.getElementById('ELEMENT_ID').innerHTML='{iframe code here}'; //Puts the content back
}

//Do Something
function MyFunction_2() {
	//document.getElementById('ELEMENT_ID').innerHTML=''; //Removes the div
	//document.getElementById('ELEMENT_ID').innerHTML='{iframe code here}'; //Puts the content back
}

BTN_1.onclick = MyFunction_1; //Start action on click
BTN_2.onclick = MyFunction_2; //Start action on click
/script


script
var BTN_1 = document.getElementById('BTN_ID-1');
var BTN_2 = document.getElementById('BTN_ID-2');

//Just hide element
function JustHide(){
	document.getElementById('ELEMENT_ID').style.display = "none"; 
	}

//Just show element
function JustShow(){ 
	document.getElementById('ELEMENT_ID').style.display = ""; 
	} 

BTN_1.onclick = JustHide; //Start action on click
BTN_2.onclick = JustShow; //Start action on click
/script

3 Likes