Skip to main content
chespio
Inspiring
March 11, 2020
Question

solved: How to define actions for multiples buttons

  • March 11, 2020
  • 1 reply
  • 579 views

Hi, I'm totally nub in programming 

 

I know there must be a better way to set actions to my buttons but I do not figure it out yet.

 

 

 

image.clk1.addEventListener("click", clkAd1);

function clkAd1() {
    window.open(ad1[1], "_blank");
}


image.clk2.addEventListener("click", clkAd2);

function clkAd2() {
    window.open(ad2[1], "_blank");
}


image.clk3.addEventListener("click", clkAd3);

function clkAd3() {
    window.open(ad3[1], "_blank");
}

 

 

Please can enyone point me a better way to do this?

Thanks

This topic has been closed for replies.

1 reply

Vladin M. Mitov
Inspiring
March 12, 2020

Hi,

I would assume that the question refers to cases, when we need to create a bunch of identical buttons (for example - a "masonry" of image cards), with similar actions.
In such cases, I would create all buttons automatically, setting one function to listen to their click events, relying on something unique for each button.

For example (just idea, not tested):

 

 

for( var i = 0; i <= myImages.length; i++ ){
	myImages[i].addEventListener( "click", mainClickHandlerFunction );
}


function mainClickHandlerFunction( evtTarget ){
	switch( evtTarget.uniqueID ) {
	  case 1:
		window.open( "https://mywebsite.com", "_blank" );
		break;
	  case 2:
		window.open( "https://yourwebsite.com", "_blank" );
		break;
	  default:
		// code block
	}
}

 

 

- Vlad: UX and graphic design, Flash user since 1998Member of Flanimate Power Tools team - extensions for character animation
chespio
chespioAuthor
Inspiring
April 1, 2020

Thanks Vlad! 
I do not understand the switch(), but using an Array was really helpful, I've been got stucked focusing on one solution, not seeing alternatives ways to solve my problem.

 

This is my code:

var tl = this;
var ad = new Array;

ad[1] = "https://www.google.com/search?q=number+1"; 
ad[2] = ""; 
ad[3] = "https://www.google.com/search?q=number+3"; 
ad[4] = "https://www.google.com/search?q=number+4"; 
ad[5] = "https://www.google.com/search?q=number+5"; 
ad[6] = "https://www.google.com/search?q=number+6"; 
ad[7] = ""; 
ad[8] = "https://www.google.com/search?q=number+8"; 
ad[9] = ""; 
ad[10] = "https://www.google.com/search?q=number+10"; 
ad[11] = ""; 
ad[12] = "https://www.google.com/search?q=number+12"; 
ad[13] = ""; 
ad[14] = ""; 
ad[15] = "https://www.google.com/search?q=number+15"; 
ad[16] = ""; 


for(var i = 1; i < ad.length; i++){ 
	U = ad[i];
	B = tl["c" + i];
	B.url = U;
	if(U != "") {
		B.addEventListener("click", clkAct.bind(this));
		
	} else {
		B.visible = false;
	}	
}

function clkAct(evt) {
    window.open(evt.target.parent.url, "_blank");
}