简体   繁体   中英

Can i manually change <input type="color"> actual displayable color by DOM with native JS?

I'm working on a gradient generator, and there is a Randomize button that creates a new gradient from two random colors. The problem is that the random function bypasses and making it on its own. I want to assign new color values to the inputs, so the user sees what color "Randomize" button just generated and changed it if he wants.

I've seen some guy had the same issue, and the help of StackOverflow users goes it, but the problem is that I use native JS, and he is using jQuery library.

Here is his solution:

$("#click").click(function () {
    $("#test").val("#ff66ff");
});

But I need a solution without using any libraries. Just provide me a line of code that will change the actual color of the input.

Here are two more screenshots so you can see what I want to do:

Before the click

After

Like this?

 document.getElementById("click").addEventListener("click", function () { document.getElementById("test").value = "#ff66ff" });
 <input id="test" type="color"/>&nbsp;<button id="click">Click</button>

Perhaps this more generic version. You can use data-attributes if you do not want to use innerHTML

 document.getElementById("container").addEventListener("click", function (e) { let tgt = e.target; if (tgt.tagName==="BUTTON") { tgt.previousElementSibling.value = tgt.innerHTML; } });
 <div id="container"> <input type="color"/>&nbsp;<button class="click">#ffaaff</button><br/> <input type="color"/>&nbsp;<button class="click">#ffffaa</button><br/> <input type="color"/>&nbsp;<button class="click">#66ffff</button><br/> </div>

Yes, that works, document.querySelector would get the element. value property changes the value of input .

Alternatives for finding elements can be document.getElementById or document.getElementsByTagName .

 document.querySelector("#click").addEventListener("click", function () { document.querySelector("#test").value = "#ff66ff"; });
 <input type="color" id="test"/> <button id="click">click</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM