I have a simple HTML page where I show the buttons, the buttons are added by the user, user can add multiple buttons. the buttons have anchors, which I need to pass variables.
So far I am doing it manually like this:
The Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="ad.size" content="width='320',height='320" />
<link rel="stylesheet" href="css/styles.css" />
<title>interactive Interactive Images</title>
</head>
<script>
let buttons = [
{
buttonId: 103676,
link: "ww.google.com",
},
{
buttonId: 432549,
link: "www.yahoo.com",
},
];
var clickTag1 = "www.google.com";
var clickTag2 = "www.yahoo.com";
</script>
<body>
<div class="conatiner">
<a href="javascript:window.open(window.clickTag1)">
<div data-id="103676" class="button-simple">first points</div>
</a>
<a href="javascript:window.open(window.clickTag12)">
<div data-id="432549" class="button-simple">first points</div>
</a>
</div>
</body>
</html>
Because users can have multiple buttons I do not want to add the variables to the anchors manually as I do know.
How can create those variables clickTag1, clickTag2 clickTag3 ….. etc based on available buttons and pass them to anchors?
Expected result
For example, if we have an array of buttons like this
let buttons = [
{
buttonId: 103676,
link: "ww.google.com",
},
{
buttonId: 432549,
link: "www.yahoo.com",
},
];
The final html should be like this
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<script>
var clickTag1 = "www.google.com";
var clickTag2 = "www.yahoo.com";
</script>
<body>
<div class="conatiner">
<a href="javascript:window.open(window.clickTag1)">
<div data-id="103676" class="button-simple">first points</div>
</a>
<a href="javascript:window.open(window.clickTag12)">
<div data-id="432549" class="button-simple">first points</div>
</a>
</div>
</body>
</html>
2
Answers
I have removed the button because like people said you cant have buttons inside of anchor tags. I have reused your buttons variable. Looped through it and created a link for each button. You can modify this to be a button that calls a function that opens a page if you want to use buttons instead of anchors.
The script has also moved to the bottom so that the container exists before executing.
Not sure why you want it like that, but to make a dynamic variable, you can use this syntax:
Example:
That should generate something like:
You can verify that the new clickTags are added as new variables from the console: