Simply update your code to,
<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>
Example: https://jsfiddle.net/1usopvda/2/
Further Explaining
There are 2 ways of doing this. See the examples below, how to use data-attribute
in JavaScript.
var colorLink = document.getElementById("setcolor");
Using DOM's getAttribute()
property
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
And I'm not sure what you are trying to achieve by the click()
in the question. So if you want to change the value onclick, see the example below
<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>
Example: https://jsfiddle.net/1usopvda/4/