HighTechProgramming15
HighTechProgramming15

Reputation: 343

JS: Change OnClick Event from variable

I am trying to changing the onclick event of an button. Here is my code:

var onclickEvent = 'window.open("https://www.google.com", "", "widht:20px height:30px")'
btn.onclick = function() {onclickEvent}

Upvotes: 0

Views: 153

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

You need to assign like that:

var onclickEvent = function() {
    window.open("https://www.google.com", "", "widht:20px height:30px");
};
btn.onclick = onclickEvent;

With the string you have, your only option is to eval which is considered bad practice and not recommended:

var onclickEvent = 'window.open("https://www.google.com", "", "widht:20px height:30px")';
btn.onclick = function() { eval(onclickEvent); };

In this case you should consider what's really dynamic in this expression and use a variable for it instead of evaling entire javascript strings. For example if that's the url then you could have something like that:

var onclickEvent = function(url) {
    window.open(url, "", "widht:20px height:30px");
};

var url = 'https://www.google.com';
btn.onclick = function() { onclickEvent(url); };

Upvotes: 1

Related Questions