How do you make a button that marks the same word in two div in JS? - javascript

illustration of the execution of the button:

You can add mark tag in your Html code with JS. But mark tag works only in HTML5. It will be okay in new Browsers.
Forexample this is your html code:
<div>
Word1 Word2 Word3 Word1
</div>
<div>
Word1
</div>
<input type="button" id="button" value="Click" onclick="" />
This is css code:
div { width:200px;height:200px;border:1px solid black;float:left; }
And this is our javascript code:
var commonWord = 'Word1';
var button = document.getElementById('button');
button.addEventListener('click', function () {
var divs = document.getElementsByTagName('div');
divs[0].innerHTML = divs[0].innerHTML.replace(commonWord, '<mark>' + commonWord + '</mark>');
divs[1].innerHTML = divs[1].innerHTML.replace(commonWord, '<mark>' + commonWord + '</mark>');
});
But this javascript code marks only first words in divs
If you want to mark all words, you can use this:
var commonWord = 'Word1';
var button = document.getElementById('button');
button.addEventListener('click', function () {
var divs = document.getElementsByTagName('div');
divs[0].innerHTML = divs[0].innerHTML.replace(/Word1/g, '<mark>' + commonWord + '</mark>');
divs[1].innerHTML = divs[1].innerHTML.replace(/Word1/g, '<mark>' + commonWord + '</mark>');
});

Welcome to Stack Overflow!, This will work for you -
function myFunction() {
var div = document.getElementsByTagName("span");
div[0].innerHTML += 'Hello';
div[1].innerHTML += 'Hello';
}
div {
display: inline-block;
width: 48%;
float: left;
border: 1px solid;
text-align: center;
height:50px;
}
button {
border: 1px solid;
text-align: center;
margin-top: 30px;
}
<div>
<span></span> world
</div>
<div>
<span></span>
</div>
<button class="button" onclick="myFunction()">Button </button>
Note: Do read How to Ask for tips on asking questions. This is your first time so that's why am answering this question if there is any doubt do ask me in the comments. Hope this is helpful to you.

Related

changing the content of a div

I would like to change the content of a div. I have three divs:
<div
class="box1"
style="height: 200px; width: 200px; background-color: red"
>
A
</div>
<br />
<div
class="box2"
style="height: 200px; width: 200px; background-color: blue"
>
<label for="">tex</label>
<input type="text" />
</div>
<br />
<div
class="box3"
style="height: 200px; width: 200px; background-color: yellow"
>
C
</div>
when the page is ready the 2 and 3rd box displays none:
function hideElementBoxOnLoad() {
let box1 = document.querySelector(".box1");
let box2 = document.querySelector(".box2");
let box3 = document.querySelector(".box3");
box2.style.display = "none";
box3.style.display = "none";
}
$(document).ready(hideElementBoxOnLoad);
I want a click that toggles the content of box2 and box3 into box1 and then back to box1 content:
function changeContent() {
let chang = true;
let box1 = document.querySelector(".box1");
let box2 = document.querySelector(".box2");
let box3 = document.querySelector(".box3");
let box2Content = box2.textContent;
let box3Content = box3.textContent;
if (chang) {
box1.textContent = box2Content;
chang = !chang;
if ((box1.textContent === box2Content)) {
box1.textContent = box3Content;
}
}
}
let btn = document.getElementById("btn");
btn.addEventListener("click", changeContent);
So far it worked but it does not display the content of box2 only box3. what did i do wrong and what better way can i toggle with a boolean.
See below
Instead of trying to swap content between each div just use JS to go through the array of them and swap an active class between them;
var boxes = document.getElementsByClassName('box');
var change = document.getElementById('change');
var counter = 0;
change.addEventListener('click', function(){
boxes[counter].classList.remove('active');
boxes[counter].nextElementSibling.classList.add('active');
counter++;
if(counter === boxes.length) {
counter = 0;
boxes[0].classList.add('active');
}
});
.box {
display: none;
width: 100px;
height: 100px;
background-color: gray;
}
.box.active {
display:block
}
<div class="box active">A</div>
<div class="box">B</div>
<div class="box">C</div>
<button id="change">Change Content</button>
im not completely sure if i understood ur question.
but below u can see and even test with the snippet button.
the button now add what ever content in in the yellow box, and whats in the input field of the blue box into the red box. listing them downwards.
if you want to replace the content completely.
just change the logic to box1.innerHTML += spacer+box3.innerHTML+spacer+input.value
this is the most simple way to do it thats easy to understand just by reading the code i think.
hope this helps!
function changeContent() {
//the button
const btn = document.getElementById("btn");
//the boxes
const box1 = document.getElementById("box1");
const box2 = document.getElementById("box2");
const box3 = document.getElementById("box3");
//a spacer
const spacer = "<br>";
//the input field
const input = document.getElementById("input");
//logic
box1.innerHTML += spacer+box3.innerHTML+spacer+input.value
}
div{
border-radius: 5px;
text-align: center;
font-family: sans-serif;
}
#box1{
min-height: 200px;
width: 200px;
padding: 5px;
background-color: rgb(255, 73, 73);
}
#box2 {
height: 200px;
width: 200px;
padding: 5px;
background-color: rgb(0, 195, 255);
}
#box3 {
height: 200px;
width: 200px;
padding: 5px;
background-color: yellow;
}
button{
padding: 3px;
margin-top: 10px;
}
<div id="box1">
<p>contetnt A</p>
</div>
<br />
<div id="box2" >
<label for="">tex</label>
<input id="input" type="text" />
<button id="btn" onclick="changeContent()">click me</button>
</div>
<br />
<div id="box3">
contetnt C
</div>
List of bugs :-
You had declared the var chang locally instead of globally, which make it true whenever you runs the function.
You are directly writing value from one tag to another, which causing the data loss, when you run your function second time.
For example :- When you click the button first time, the data is swapped, but for the second click, the data first div is lost and cannot be brought back...
Solution :- Store the data in an array in document.ready event handler and extract data from the array to update you html tags.
function hideElementBoxOnLoad() {
let box1 = document.querySelector(".box1");
let box2 = document.querySelector(".box2");
let box3 = document.querySelector(".box3");
box2.style.display = "none";
box3.style.display = "none";
content = [box1.textContent, box2.textContent, box3.textContent];
let btn = document.getElementById("btn");
btn.addEventListener("click", changeContent);
}
var content = [];
window.onload = (hideElementBoxOnLoad);
var index = 0;
function changeContent() {
let chang = true;
let box1 = document.querySelector(".box1");
/* let box2 = document.querySelector(".box2");
let box3 = document.querySelector(".box3");
let box2Content = box2.textContent;
let box3Content = box3.textContent;
if (chang) {
box1.textContent = box2Content;
chang = !chang;
if ((box1.textContent === box2Content)) {
box1.textContent = box3Content;
}
}
*/
function cycle(n, x = 0, y = content.length - 1, a = 1) {
n += a;
if (n > y) return x;
if (n < x) return y;
return n;
}
index = cycle(index);
box1.textContent = content[index];
}
<div class="box1" style="height: 200px; width: 200px; background-color: red">
A
</div>
<br />
<div class="box2" style="height: 200px; width: 200px; background-color: blue">
<label for="">tex</label>
<input type="text" />
</div>
<br />
<div class="box3" style="height: 200px; width: 200px; background-color: yellow">
C
</div>
<button id="btn"> CLICK ME </button>
Explaination
Here I first stored the tags textContent in a array content, in the starting of the code.
Then, inside the button click handler, a simple cycle function to cycle on the values stored inside the content array.

Problems targeting the correct div id with dynamically (javascript) created divs

I'm having troubles targeting the correct div id with dynamically (javascript) created divs.
How it should function..
Each time you press the add text button a new text input is created with an incrementing id
When you type into this box the text appears in the results div
The same will repeat each time you press the add text button.
So far all of the above functions as I would expect.
The problem..
When you add a second text then try to edit the first text the id is wrong so the first text does not update.
How can I make this function as expected so no matter how many texts you add you can edit a previous one and it updates the correct id?
let textcount = 0;
function addtext() {
textcount++
//create textarea with incrimenting id
var newtext = document.createElement("div");
newtext.id = "text" + (textcount);
newtext.innerHTML = "text id = " + (textcount) + "<br><textarea placeholder=\"Start Typing\" id=\"textarea" + textcount + "\" class=\"textarea\" oninput=\"updatetext();\" autocomplete=\"off\" ></textarea>";
document.getElementById("newtextboxappend").appendChild(newtext);
//create results div with matching id
var shownewtext = document.createElement("div");
shownewtext.id = "showtext" + (textcount);
document.getElementById("resultsappend").appendChild(shownewtext);
document.getElementById("showtext" + (textcount)).innerText = document.getElementById("textarea" + (textcount)).value;
}
function updatetext() {
document.getElementById("showtext" + (textcount)).innerText = (textcount) + ") " + document.getElementById("textarea" + (textcount)).value;
//console log id when typing to see what id is being targeted
console.log(textcount);
};
.newtextboxescontain {
width:100%;
border: 1px black solid;
}
.resultscontain {
width: 100%;
border: 0.5px black solid;
}
textarea {
width: 95%;
height: 20px;
}
<button onclick="addtext();">Add Text</button>
<br /><br />
Text Inputs: <br />
<div id="newtextboxescontain" class="newtextboxescontain">
<div id="newtextboxappend"></div>
</div>
<br />
Results: <br />
<div id="resultscontain" class="resultscontain">
<div id="resultsappend"></div>
</div>
When you was getting the id to use, you was getting the number of the index. Like length. You was getting the last number. I changed a little and it worked, see below:
let textcount = 0;
function addtext() {
textcount++
//create textarea with incrimenting id
var newtext = document.createElement("div");
newtext.id = "text" + (textcount);
newtext.innerHTML = "text id = " + (textcount) + "<br><textarea placeholder=\"Start Typing\" id=\"textarea" + textcount + "\" class=\"textarea\" oninput=\"updatetext(event);\" autocomplete=\"off\" ></textarea>";
document.getElementById("newtextboxappend").appendChild(newtext);
//create results div with matching id
var shownewtext = document.createElement("div");
shownewtext.id = "showtext" + (textcount);
document.getElementById("resultsappend").appendChild(shownewtext);
document.getElementById("showtext" + (textcount)).innerText = document.getElementById("textarea" + (textcount)).value;
}
function updatetext(e) {
var ideditaded = e.target.getAttribute("id").replace("textarea", ""); // get the id of what you are editing and remove the textarea to get only its textcount.
document.getElementById("showtext" + (ideditaded)).innerText = (ideditaded) + ") " + document.getElementById("textarea" + (ideditaded)).value;
//console log id when typing to see what id is being targeted
//console.log(ideditaded);
};
.newtextboxescontain {
width:100%;
border: 1px black solid;
}
.resultscontain {
width: 100%;
border: 0.5px black solid;
}
textarea {
width: 95%;
height: 20px;
}
<button onclick="addtext();">Add Text</button>
<br /><br />
Text Inputs: <br />
<div id="newtextboxescontain" class="newtextboxescontain">
<div id="newtextboxappend"></div>
</div>
<br />
Results: <br />
<div id="resultscontain" class="resultscontain">
<div id="resultsappend"></div>
</div>

Broken Javascript Code

I'm trying to create a website where three things happen, but I am stuck.
(1) When the button “ADD” button is clicked it will create a new paragraph
and add it to the output. The contents of the paragraph should come from the text area that is below the [ADD] button.
(2) If the “delete” button is pressed I need to delete the first paragraph in the div.
(3) If the user tries to delete when there are no paragraphs, create an “alert" that says:"No Paragraphs to delete".
I got my JS to put each paragraph into the div, but I'm not really sure how to delete it... Any help would be much appreciated.
window.onload = function() {
var button = document.getElementById("add");
button.onclick = insertItem;
}
function insertItem() {
var added = document.getElementById("output");
var textToAdd = document.getElementById("input");
if (textToAdd.value != "") {
var newp = document.createElement("p");
newp.innerHTML = textToAdd.value;
added.appendChild(newp);
}
}
var deletebutton = document.getElementsByTagName("delete");
deletebutton.onclick = deleteItem;
function deleteItem() {
var output = document.getElementById("output");
var pars = output.getElementsByTagName("p");
if (pars.length > 0) {
output.removeChild(pars[0]);
}
}
#output {
border: blue 5px solid;
padding: 10px;
margin-bottom: 10px;
margin-top: 10px;
width: 50%;
}
#output p {
padding: 10px;
border: black 1px dashed;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js" type="text/javascript"></script>
<script src="task3.js"></script>
</head>
<body>
<h2> TASK 3 - Creating, Appending and Deleting Nodes in the DOM Tree </h2>
<p> Type in text below, click add to add as paragraph. <button id="add"> Add </button> </p>
<textarea id="input" rows="10" cols="60">
</textarea><br>
<button id="delete">Delete Last Paragraph</button>
<br><br>
<h2> Added Paragraphs </h2>
<div id="output">
</div>
</body>
</html>
You're fetching the delete button wrong. You're using getElementsByTagName instead of by id.
When deleting, you will probably delete the first <p> you have in your markup that doesnt belong to your output. To fix this you could simply fetch all children of your output div and remove the first one:
function deleteItem() {
let output = document.getElementById('output')
if (output.hasChildNodes()) {
let outputs = output.childNodes
outputs[0].remove()
}
}

HTML JS form to div comments (temporary change)

I have seen many similar problems but when I try them they end up failing. It has gotten to the point where my code is totally messed up and I need some help both cleaning it up and fixing my issue. (using chrome)
So far I have tried selecting the value of the form and putting that into a div,
I have tried to use the button as just a link to start the script so that the page doesn't reset and also many other answers found on-line, none of them are helping so I am asking for a personalised help.
function on_comment_add() {
var main = document.getElementById("div1");
var add_user_name = document.createElement("div");
var add_user_comment = document.createElement("div");
add_user_name.setAttribute("id", "add_user_name");
add_user_comment.setAttribute("id", "add_user_comment");
<!-- var node = document.createTextNode("This is new."); -->
var node_1 = document.getElementById("user_name").value;
var node_2 = document.getElementById("user_comment").value;
add_user_name.appendChild(node_1);
add_user_comment.appendChild(node_2);
var element = document.createElement("div");
element.setAttribute("id", "display_comment_div");
element.appendChild(add_user_name);
element.appendChild(add_user_comment);
main.appendChild(element);
main.innerHTML = element;
return false;
}
body {
background-color: lightGreen;
}
div.middle {
width: 80%;
margin-left: 10%;
background-color: #47e077;
height: 940px;
font-size: 10pt;
font-family: aubrey;
border: 3px solid gold;
}
.comments-form {
text-align: center;
}
#display_comment_div {
background: rgba(200, 54, 54, 0.1);
width: 80%;
margin-left: 9%;
border: 0.1px solid lightGreen;
border-radius: 25px;
}
#add_user_name {
width: 45%;
float: left;
}
#add_user_comment {
width: 45%;
display: inline-block;
float: right;
}
<div class="middle">
<div class="comments-form">
<form>
<label for="name" style="width:100px; display:inline-block;">Name</label>
<input id="user_name" type="text" placeholder="name goes here" style="width:300px; margin-left:5px;" />
<br><br>
<label for="comment" style="width:100px; display:inline-block;">Comment</label>
<textarea id="user_comment" placeholder="comment goes here" maxlength="150" style="width:300px;max-width:300px;"></textarea><br>
<button style="margin-left:310px;" onmousedown="return on_comment_add">Submit</button>
</form>
<div id="div1">
</div>
</div>
</div>
I guess what I am asking is if anyone can help me display the username and comment below the form but it seems tricky for me because I have gone through so many answers that don't work for me that I cannot think of any other ways to do it.
For clarification this code is not meant to keep the comments from the form nor is it meant to be a fully functioning site. I am just making slight modifications to some code so that I can hand it in as a college assignment.
Using onclick and pass the event inside:
<button style="margin-left:310px;" onclick="on_comment_add(event)">Submit</button>
And disable the default form submit action:
function on_comment_add(e) {
e.preventDefault()
var main = document.getElementById("div1");
var add_user_name = document.createElement("div");
var add_user_comment = document.createElement("div");
add_user_name.setAttribute("id", "add_user_name");
add_user_comment.setAttribute("id", "add_user_comment");
var node_1 = document.createElement("div");
node_1.innerHTML= document.getElementById("user_name").value;
var node_2 = document.createElement("div");
node_2.innerHTML = document.getElementById("user_comment").value;
add_user_name.appendChild(node_1);
add_user_comment.appendChild(node_2);
var element = document.createElement("div");
element.setAttribute("id", "display_comment_div");
element.appendChild(add_user_name);
element.appendChild(add_user_comment);
main.appendChild(element);
return false;
}
Workable example: https://jsfiddle.net/kingychiu/z6gnqswn/
Change type to "button" to prevent automatical form sending and add parentheses to onmousedown expression:
<button type="button" style="margin-left:310px;" onmousedown="return on_comment_add()">Submit</button>
Then change this
add_user_name.appendChild(node_1);
add_user_comment.appendChild(node_2);
to this (since node_1, node_2 are values, not elements):
add_user_name.innerHTML = node_1;
add_user_comment.innerHTML = node_2;
And remove that line
main.innerHTML = element;
above
return false;
That should work.

Remove a portion of text using javascript

Here's the code:
function bold() {
var text = document.getElementById("post-body");
var t = text.value.substr(text.selectionStart, text.selectionEnd - text.selectionStart);
var text = '**';
$('#post-body').val(function(_, val) {
return val + text + t + text;
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name="post-body" id="post-body" rows="20" style="margin-left: 0px; margin-right: 0px; width: 400px;"></textarea>
<div>
<button id="bold" value="**" onclick="bold()">B</button>
</div>
What I am trying to do is similar to how comments on Stack Overflow work: you highlight text in the text box, and click a button. The button then appends and prepends the proper syntax to the text. I am able to apply the proper syntax, but the highlighted text is duplicated.
I know it's because in my code, I have
return val + text + t + text;
where val is all of the text in the textarea, and t is the highlighted text, but I'm not sure how to remove the highlighted text from val and add the new version in the form of t.
Any help would be greatly appreciated.
You can record the text before and after and then return the text before, the selection and the text after.
function bold() {
var text = document.getElementById("post-body");
var t = text.value.substr(text.selectionStart, text.selectionEnd - text.selectionStart);
var before = text.value.slice(0, text.selectionStart);
var after = text.value.slice(text.selectionEnd);
var text = '**';
$('#post-body').val(function(_, val) {
return before + text + t + text + after;
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name="post-body" id="post-body" rows="20" style="margin-left: 0px; margin-right: 0px; width: 400px;">Select some text here.</textarea>
<div>
<button id="bold" value="**" onclick="bold()">B</button>
</div>

Categories