To update your code, simply make the following changes:
<script>
window.onload = function(){
var color = "red",
setcolorLink = document.getElementById("setcolor");
setcolorLink.setAttribute("data-value", color);
setcolorLink.click();
}
</script>
<a id="setcolor" class="colors" href="javascript:void(0)" role="button" data-value="mycolor">Choose color</a>
For an example, you can check out this link: https://jsfiddle.net/1usopvda/2/
Further Explanation
There are multiple ways to achieve this. Below are examples demonstrating how to utilize the data-attribute
in JavaScript.
var colorLink = document.getElementById("setcolor");
Using DOM's getAttribute()
method
var getColor = colorLink.getAttribute("data-value") //returns "mycolor"
colorLink.setAttribute("data-value", "red") //changes "data-value" to "red"
colorLink.removeAttribute("data-value") //removes "data-value" attribute entirely
Using JavaScript's dataset
property
var getColor = colorLink.dataset.value //returns "mycolor"
colorLink.dataset.value = 'red' //changes "data-value" to "red"
colorLink.dataset.value = null //removes "data-value" attribute
If you are uncertain about the purpose of the click()
function in the question, here's an example of how to change the value onclick
<script>
window.onload = function(){
var color = "red",
setcolorLink = document.getElementById("setcolor");
setcolorLink.onclick = function(){
this.setAttribute("data-value", color);
};
}
</script>
<a id="setcolor" class="colors" href="javascript:void(0)" role="button" data-value="mycolor">Choose color</a>
For a demonstration, visit: https://jsfiddle.net/1usopvda/4/