0

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}

1 Answer 1

1

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); };
Sign up to request clarification or add additional context in comments.

3 Comments

but i want to use onclickEvent as an string so i can change the function. onclickEvent is an string from an textbox.
That's very bad practice because you will need to use eval as shown in my answer to execute this code. I would recommend you rethinking your design.
Why does it need to be a string? What do you need to change in the string? Can't you pass an argument to the function that updates the string?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.