30
loading...
This website collects cookies to deliver better user experience
Before you proceed: This post is not about creating a safe or the best HTML generator rather it's just something for fun that you can try by using template literals in JavaScript. It was a fun experiment for me.
template literals
in JavaScript which will generate HTML code for you!let string = `first part of the string ${expression} second part of the string`;
<div id="contains">
<label for="title" class="title">Title</label>
<input type="text" id="title" name="title">
<label for="url" class="url">URL</label>
<input type="url" id="url" name="url">
<label for="tag" class="tag">Tag</label>
<input type="text" id="tag" name="tag">
<button id="submit">Generate</button>
</div>
textarea
field in which the resultant code will be displayed as well as create a button to copy the code to the clipboard.<div class="result">
<textarea class="result_text" type="text" rows="5"></textarea>
<button class="copy_btn"><i class="fas fa-clipboard"></i></button>
</div>
generate()
. This function has three parameters — title
, url
and tag
. It will take in the value of the title
, the url
, and the tag
that we have input in the field as arguments.function generate(title, url, tag){
//code
}
title
, the url
& the tag
into the string. Then, set the value of the result
field to the string that is generated.let title = document.querySelector("#title");
let url = document.querySelector("#url");
let tag = document.querySelector("#tag");
let result = document.querySelector(".result_text");
function generate(title, url, tag){
let final_string = `<a href="${url}"><div class="link"><div class="banner">${tag}</div>${title}</div></a>`;
result.value = final_string;
}
let submit_btn = document.querySelector("#submit");
submit_btn.addEventListener("click", () => {
generate(title.value, url.value, tag.value);
title.value = "";
url.value = "";
tag.value = "";
});
textarea
, we can define a function called copy()
and then call the function when the user clicks on the 'copy to clipboard' button.let copy_btn = document.querySelector(".copy_btn");
copy_btn.addEventListener("click", () => {
copy();
})
function copy(){
result.select();
document.execCommand("copy");
}