How can I combine two event functions of properties such as JavaScript? - javascript

var input = document.querySelector('input');
var button = document.querySelector('button');
var question = document.querySelector('.p1')
var result = document.querySelector('.p2')
button.addEventListener("click",function(e){
e.preventDefault;
question.innerHTML = input.value;
input.value = "";
input.placeholder = question.textContent[question.textContent.length-1]+ " finished word?";
input.focus();
})
/*
button.addEventListener("click",function(ev){
ev.preventDefault;
if(question.textContent[question.textContent.length-1] === input.value[0])
{
question.innerHTML = input.value;
input.value = "";
result.innerHTML = "good"
input.focus();
}
else{
input.value = "";
result.innerHTML = "bad"
input.focus();
}
})
*/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p class="p1"></p>
<input type="text" placeholder="input first word">
<button type="button">submit</button>
<p class="p2"></p>
<script src="끝말잇기2.js"></script>
</body>
</html>
I am sorry that I asked you a question using a translator because I can't speak English.
I have a question in the JavaScript code.
First, the first function is input the first word, and the event is click.
The second function is the same as the first letter of the word you received, and the last letter is the same, so you put the first letter in the first letter.
These two functions can be combined, but I think both functions are duplicated because they are event clicks.
How can i write code that combines two functions and performs sequential functions?

One Function Solution
There is no need for two functions, you can write it as one function. Consider here that you don't reset the input.value twice when you combine both. Just reset it at the end of the function.
var input = document.querySelector('input');
var button = document.querySelector('button');
var question = document.querySelector('.p1')
var result = document.querySelector('.p2')
button.addEventListener("click", function() {
question.innerHTML = input.value;
input.placeholder = question.textContent[question.textContent.length - 1] + " finished word?";
input.focus();
if (question.textContent[question.textContent.length - 1] === input.value[0]) {
question.innerHTML = input.value;
input.value = "";
result.innerHTML = "good"
input.focus();
} else {
input.value = "";
result.innerHTML = "bad"
input.focus();
}
})
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p class="p1"></p>
<input type="text" placeholder="input first word">
<button type="button">submit</button>
<p class="p2"></p>
<script src="끝말잇기2.js"></script>
</body>
</html>
Call Consecutively Wrapper Function
If you want to use two functions you can do a wrapper function and inside it you can call your two other functions.
Then when the button get's pressed you call the wrapper function which will proceed the two other functions consecutively.
var input = document.querySelector('input');
var button = document.querySelector('button');
var question = document.querySelector('.p1')
var result = document.querySelector('.p2')
button.addEventListener("click", wrapperFunction);
function a() {
question.innerHTML = input.value;
input.placeholder = question.textContent[question.textContent.length - 1] + " finished word?";
input.focus();
}
function b() {
if (question.textContent[question.textContent.length - 1] === input.value[0]) {
question.innerHTML = input.value;
input.value = "";
result.innerHTML = "good"
input.focus();
} else {
input.value = "";
result.innerHTML = "bad"
input.focus();
}
}
function wrapperFunction() {
a();
b();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p class="p1"></p>
<input type="text" placeholder="input first word">
<button type="button">submit</button>
<p class="p2"></p>
<script src="끝말잇기2.js"></script>
</body>
</html>

I removed the preventDefault, then I added a setTimeout to changing input.value so both functions can run(with the input.value resource shared)
Because setTimeout is asynchronous, it would work well in situations like this, since it would wait until the other things finish running(I'm paraphrasing so don't quote me) then it will run.. making both functions work at the "same time"
var input = document.querySelector('input');
var button = document.querySelector('button');
var question = document.querySelector('.p1')
var result = document.querySelector('.p2')
button.addEventListener("click",function(e){
//e.preventDefault;
question.innerHTML = input.value;
setTimeout(()=>{input.value = "";},0)
input.placeholder = question.textContent[question.textContent.length-1]+ " finished word?";
input.focus();
})
button.addEventListener("click",function(ev){
//ev.preventDefault;
if(question.textContent[question.textContent.length-1] === input.value[0])
{
question.innerHTML = input.value;
setTimeout(()=>{input.value = "";},0)
result.innerHTML = "good"
input.focus();
}
else{
setTimeout(()=>{input.value = "";},0)
result.innerHTML = "bad"
input.focus();
}
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p class="p1"></p>
<input type="text" placeholder="input first word">
<button type="button">submit</button>
<p class="p2"></p>
<script src="끝말잇기2.js"></script>
</body>
</html>

Related

Why isnt my button displaying value onto the div

I want the button with the id of number1 to display the value of 1 on to the input box which has the id of quest which is short for question.I also want to know if my code can be made more readable.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calucator</title>
<style>
body{
text-align: center;
}
</style>
<script>
const quest = document.getElementById("quest");
const data = quest.value;
const yourElement = document.createElement("div");
function nums(){
const num1 = document.getElementById('number1').innerText = 1;
data.textContent = num1;
}
function run() {
nums()
yourElement.textContent = data
quest.appendChild(yourElement);
}
</script>
</head>
<body>
<h1>Calucator</h1>
<input type="number" placeholder="Enter now" name="" id="quest">
<button onclick="run()">=</button>
<br>
<button onclick="" id="number1">1</button>
</body>
</html>
<script>
const quest = document.getElementById("quest");
const data = quest.value;
const yourElement = document.createElement("div");
//PROBLEM 1: You are not attaching yourElement to the DOM. See Element.insertBefore / Element.appendChild
function nums(){
const num1 = document.getElementById('number1').innerText = 1;
data.textContent = num1;
}
function run() {
nums()
yourElement.textContent = data
quest.appendChild(yourElement);
}
</script>
And
<button onclick="run()">=</button>
Problem 2: Don't use inline element event handling. It isn't safe and Content-Security-Policy won't allow it. Instead, use JavaScript Element.addEventListener(...)

How can I make multiple inputs every time I enter an input?

I am creating a google extension called manga extension. It all went well until I crossed with input. I like to put an input number every time I enter a manga name in the main input, naming it with chapter with input. But when I enter a new manga name, the value of every input I entered is lost. And I don't know how to put it inside of localStorage. How should I make it?
const divInput = []
const mangaName = document.getElementById('mangaNameInList')
// the manga name
const deleteBtn = document.getElementById('deleteBtn')
let mangaChapters = document.createElement('input')
let mangaLists = document.getElementById('mangaLists')
// the div i created in html
let count = 0
mangaName.addEventListener('keyup', function (event) {
if (event.key == 'Enter') {
count += 1
mangaLists.innerHTML += `<p> ${mangaName.value}
<em>chapter</em>
<input type="number" class="mangaChapters ${count}"
onkeyup="getValue(event)">
</p>`
// the input that i was conflicted with
}
})
function getValue(event) {
if (event.key == 'Enter') {
mangaChapters = document.getElementsByClassName(`mangaChapters`)
divInput.push(mangaChapters.value)
}
}
every time I entered the main input (mangaName) and displaying it in the innerHTML, I just concatenate it with and and that's the problem, how can I get the value of every declared input that I make in inside the mangaName?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Manga Extension</title>
</head>
<body>
<h1>Manga Name Lists</h1>
<input type="text" id="mangaNameInList">
<button id="deleteBtn">DELETE ALL</button>
<div id="mangaLists"></div>
<script src="script.js"></script>
</body>
</html>
here's the html code. thanks for taking time to answer my coding question :)))

How to make the button extract text from othere elements?

I have made a small "Note Taker" application for educational purposes, and I want to add one more functionality there. I want the "View Detail" button to show the whole note in a modal appearing in the middle of the screen, but I'm not actually sure how I am supposed to do this and how to make the button extract the text from the initial note.
I attach html, javascript code and a screenshot for better understanding of the problem.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/style.css">
<script src="/app.js" defer></script>
<title>Document</title>
</head>
<body>
<h1>Note Taker</h1>
<h2>Add A New Note:</h2>
<div id="inputField">
<p id="note">Note:</p>
<textarea name="" id="textField" cols="30" rows="10" placeholder="Put your text here"></textarea>
</div>
<button id="addNoteBtn">Add Note</button>
<div id="noteContainer">
</div>
</body>
</html>
HTML here ^
const addNoteBtn = document.getElementById("addNoteBtn")
const noteContainer = document.getElementById("noteContainer")
addNoteBtn.addEventListener("click", renderHTML)
window.addEventListener("DOMContentLoaded", callStorage)
function renderHTML(){
const noteBox = document.createElement("div")
noteBox.classList.add("noteBox")
const noteTitle = document.createElement("h3")
const noteText = document.createElement("p")
const insideNoteBtn = document.createElement("button")
insideNoteBtn.classList.add("insideNoteBtn")
noteContainer.appendChild(noteBox)
noteBox.appendChild(noteTitle)
noteBox.appendChild(noteText)
noteBox.appendChild(insideNoteBtn)
let noteStorage
if(localStorage.getItem("notes")=== null){
noteStorage = []
}else{
noteStorage = JSON.parse(localStorage.getItem("notes"))
}
noteStorage.push(textfield.value)
localStorage.setItem("notes", JSON.stringify(noteStorage))
noteStorage.forEach(function(value, index){
noteTitle.textContent = `Note ${index + 1}`
noteText.textContent = value
insideNoteBtn.textContent = "View Detail"
})
}
function callStorage(){
let noteStorage
if(localStorage.getItem("notes")=== null){
noteStorage = []
}else{
noteStorage = JSON.parse(localStorage.getItem("notes"))
}
noteStorage.forEach(function(value, index){
const noteBox = document.createElement("div")
noteBox.classList.add("noteBox")
const noteTitle = document.createElement("h3")
const noteText = document.createElement("p")
const insideNoteBtn = document.createElement("button")
insideNoteBtn.classList.add("insideNoteBtn")
noteContainer.appendChild(noteBox)
noteBox.appendChild(noteTitle)
noteBox.appendChild(noteText)
noteBox.appendChild(insideNoteBtn)
noteTitle.textContent = `Note ${index + 1}`
noteText.textContent = value
insideNoteBtn.textContent = "View Detail"
})
}
Javascript here ^
screenshot ^

Javascript cloneNode for adding new elements

what I'm trying to do is. when I click
function runIt(text) {
var counter = 1;
var comment = document.getElementById("name");
comment.innerText = text;
comment.cloneNode(true);
comment.id += counter;
}
document.addEventListener("click", function(e){
runIt("test")
}, true);
I want it to ADD a new element underneath that output "test".
it's keep getting replaced. :(
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>t</title>
</head>
<body>
<p id="name" class="someclass"></p>
</body>
</html>
cloneNode returns the new code, which you can then append to the DOM. Also counter should be defined outside the function and then incremented each time.
var counter = 1;
function runIt(text) {
var comment = document.getElementById("name");
newcomment = comment.cloneNode(true);
newcomment.innerText = text;
newcomment.id += counter;
counter++;
document.querySelector('body').append(newcomment)
}
document.addEventListener("click", function(e){
runIt("test")
}, true);
<p id="name" class="someclass">-</p>

Mask original e-mail on registration page using Javascript

I need to setup a page that allows users to register using their e-mail but as a requirement the e-mail shouldn't be "visible" for human eyes, I guess there's got to be a better way to do it, but so far I came up with this option using JQuery:
I created a fake control that handles the masking and captures the text so that it can be assigned to a hidden field (so that the previously working code will keep working without changes).
var emailControl = $("#eMail");
var firstHalf = "";
var secondHalf = "";
var fullMail = "";
emailControl.keyup(function(e){
var control = e.currentTarget;
var currentText = $(control).val();
if (currentText.length == 0){
fullMail = '';
firstHalf = '';
secondHalf = '';
$(control).attr('type', 'password');
}
else{
var components = currentText.split("#");
var hiddenPart = "•".repeat(components[0].length);
detectChanges(currentText);
if (components.length == 2) {
secondHalf = '#' + components[1];
}
$(control).attr('type', 'text');
$(control).val(hiddenPart + secondHalf);
fullMail = firstHalf + secondHalf;
}
});
function detectChanges(originalText) {
var position = originalText.indexOf('#');
if (position == -1) {
position = originalText.length;
}
for (var i = 0; i < position; i++){
if (originalText[i] != "•"){
firstHalf = firstHalf.substring(0, i) + originalText[i] + firstHalf.substring(i+1);
}
}
}
I did manage to get it working here: https://codepen.io/icampana/pen/KbegKE
You could give the input tag type of password: type="password".
It may cause some janky things to happen with autofill.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form>
email: <input type="password" name="email">
</form>
</body>
</html>
You could also do something similar with CSS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
input {
-webkit-text-security: circle;
}
</style>
</head>
<body>
<form>
email: <input name="email">
</form>
</body>
</html>

Categories