When the user visits the page, this HTML text must display.
<p id="exampleText">Hit The "Change Text" Button Below To Change <span id="thisText"><strong>This</strong></span> Text and see how the innerHTML property tag works </p>
After clicking this button:
<button id="changeButton" type="button" value="default Text" onclick="textChanger()">Change Text</button>
Display This Text:
var txtExmp1 = "Hooooooooooooraayy!!, You Clicked and Changed The Text..." + "<br><br><br>" + "but now you have to fix me so i can change again";
Now user should be able to click the button and see previous text and back to the "Hooray" message in var txtExmp1.
I've tried to use an if statement but didnt work. Here's the code:
var defaultText = document.getElementById("exampleText");
if (defaultTex.innerHTML === defaultText){
defaultText.innerHTML = txtExmp1;
}
else {
defaultText.innerHTML = defaultText;
}
How can I make this texts toggle between each other considering one is html and the other is javascript. What is the simple and most effective way to toggle this texts?
Heres what it looks like (Screenshot image):
i.Before Click
ii.After click, but wont change again
This is relatively simple, when changing the text you need to take the current visible one and save it in a variable, then show the other stored text you have in txtExmp1 then when the use click again you take the other visible text store it and show the one you stored before, doing it this is highly inefficient.
From the start you store both strings in variables or array then toggle between them.
Of course this is just one way to achieve this.
let text = ["Hooooooooooooraayy!!, You Clicked and Changed The Text... <br><br><br>but now you have to fix me so i can change again", "Hit The Change Text Button Below To Change <span id='thisText '><strong>This</strong></span> Text and see how the innerHTML property tag works "];
let index = 0;
function textChanger() {
// Get the p Element refrence so we can modify it
var pElement = document.getElementById("exampleText");
// text[index] will return one of the texts from the array
// depening on the index if 0 its the first one
// if 1 it's the second one
// that's why we're altering index's value after every change
if (index == 0) {
pElement.innerHTML = text[index];
index = 1;
} else if (index == 1) {
pElement.innerHTML = text[index];
index = 0;
}
}
<p id="exampleText">Hit The Change Text Button Below To Change <span id='thisText '><strong>This</strong></span> Text and see how the innerHTML property tag works </p>
<button id="changeButton" type="button" value="default Text" onclick="textChanger()">Change Text</button>
The word you are searching is toggle. Try switch case:
var theToggle = document.getElementById("changeButton");
var toggleMe = document.getElementById("exampleText");
toggleMe.toggleStatus = "on";
theToggle.onclick = function(){
switch(toggleMe.toggleStatus){
case "on":
toggleMe.toggleStatus="off";
toggleMe.textContent = "Hooooooooooooraayy";
break;
case "off":
toggleMe.toggleStatus="on";
toggleMe.textContent = " Hit The Change Text Button Below To change...";
break;
}
Good luck!
Related
I have a button with a var that start with a 0 and when you click a another button it increases to 1. But if you click the second button first, the var goes negative. The button is disabled at the beginning, but when it increases to 1 the button should be enabled.
When the page is loaded the button disabled, but when the var goes to 1 the button is still disabled.
I tried: if(var == 0){document.getElementById("button1").disabled = true; return false;}
You can do something like in below snippet :
You can use any tag instead of input like div span h1 ... which ever you wish and style according to need .
This thing you will need to change will be change .value to .innerHTML everywhere like this(1 example) :
var units = document.getElementsByClassName("unitsMain")[0].innerHTML
function decreaseUnits() {
var units = document.getElementsByClassName("unitsMain")[0].value
if (units > 0) {
units--;
document.getElementsByClassName("unitsMain")[0].value = units;
}
}
function increaseUnits() {
var units = document.getElementsByClassName("unitsMain")[0].value
units++;
document.getElementsByClassName("unitsMain")[0].value = units;
}
<button class="decOrderUnits" onclick="decreaseUnits()"><i class="fa fa-minus"></i>-</button>
<input class="unitsMain" value="0" maxlength="3">
<button class="incOrderUnits" onclick="increaseUnits()"><i class="fa fa-plus"></i>+</button>
I have this idea where if you press a button, it'll display a text, but not only one text, but multiple, just not at once. If you press the button again, it'll display another text after it. So far, I'm only limited to only one text being displayed. I'm not really sure how to go from what I'm trying to achieve. I had an idea about using arrays but arrays and buttons didn't seem to work all that great, at least for me. I might have done something wrong for it to not work. Anyways, the idea was that the button would call from the array each time you'd click it so it'd display a different text.
So if you press the button once, it would output: "Hello"
And if you press it again, it would output: "How are you?"
and so on and so forth.
How would I do this in terms of making something like this happen?
Disclaimer: I don't want the text to be replaced with a new text. I want it solely outputted afterwards.
<button id = "age-button" button onClick = "ageButton()">AGE!</button>
<script>
function ageButton() {
var text = "You are born.";
document.getElementById("age1").innerHTML = text;
}
</script>
This code above only displays one text. How would I let it display another text after I press the button again?
// Define array of string that you would like to show on each click
const labels = [
"String 1",
"String 2",
"String 3"
// ... so on (add as many as you like)
];
// lets start from zero index
let currentIndex = 0;
// get the button HTMLElement
const nextBtn = document.querySelector("#next-btn");
const contentsEl = document.querySelector("#contents");
// attach onClick event handler / listner
nextBtn.addEventListener("click", function(event) {
// get the label string to show
const label = labels[currentIndex];
const p = document.createElement("p");
p.textContent = label;
contentsEl.append(p);
// increment the index
currentIndex++;
// set a trap
if (currentIndex === labels.length) {
//(bonus) disable the button when you reach the end
this.disabled = true;
}
});
<button id="next-btn">Show Next</button>
<div id="contents"></div>
Here is an example how you can do that.
let texts = ["You are born", "Hi there", "I'm ready"];
function ageButton() {
let line = texts.shift(); //use shift to get the first element in array
if (line) {
//use += operator to append to previous content
document.getElementById("age1").innerHTML += "<p>" + line + "</p>";
}
}
<button id="age-button" onclick="ageButton()">AGE!</button>
<div id="age1"></div>
I want to know how to change the background color or may be color of the text that was modified in a textarea.
Like suppose, consider a textarea with a pre-defined value as "Hello World".
Now if you try to change the text inside the textarea to "Hello Universe", it should show Universe highlighted (may be background color change, or color change or make it bold, anything.
I just want to get the modified text to be highlighted so it is visible what was changed.
Highlighting is possible if you make the textarea partially transparent and then had a div behind it where you can clone the content and put span tags around the changed values. The hard part is in figuring out how to diff the string. For an example of highlight certain parts of text "in the text area" see this fiddle:
https://jsfiddle.net/mcgraphix/tn0ahcfx/
<div class="container">
<div id="highlighter"></div>
<textarea id="editor" onkeyup="updateHighlight()"
value="This is some text in the editor"></textarea>
</div>
JS
function updateHighlight() {
//calculate index of changes
//assume chars 1-10 are different //see my comment for how to calculate what to highlight
var content = document.getElementById('editor').value;
var highlighted = '';
var i = 0;
while (i < content.length) {
if (i === 1) {
highlighted += '<span class="highlighted">';
} else if (i > 10) {
highlighted += '</span>'
}
highlighted += content.charAt(i);
i++;
}
document.getElementById('highlighter').innerHTML = highlighted;
}
Basically, as you type the text in the text area is parsed and as text is identified as being in need of highlight, a span tag is wrapped around it. After parsing the text, the copy with the spans is put inside the div that is behind the textarea. With the right css you can hide the text in that div and just put a background color such that it looks highlighted. The fiddle gives you the basic idea but you would have to account for the user resizing the text area as you need to make sure the text area and the "highlighter" behind it are aligned.
The hard part is figuring out what to highlight. such that you don't highlight every character after the first change. Take a look at Levenshtein distance algorithm for determining which characters you need to highlight when comparing two strings.
Keep old value in variable.
Split the value using delimiter as space
Check indexOf new value after spitting by space
Use Array#indexOf to listen the change in value!
Most important point, you can not apply style over characters in textarea. Example given below has a demonstration in div element considering value from textarea
var input = $('textarea');
var div = $('div');
var oldVal = input.val();
var oldArr = oldVal.split(' ');
input.on('input', function() {
var newVal = this.value;
var html = [];
newVal.split(' ').forEach(function(el) {
if (oldArr.indexOf(el) === -1) {
html.push('<span style="color:green">' + el + '</span>');
} else {
html.push('<span>' + el + '</span>');
}
});
div.html(html.join(' '));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<textarea>Hello World</textarea>
<div></div>
I want to do something similar to what this website and wordpress does. When a user highlights text on the screen, then clicks a button on the toolbar it will wrap an html tag around the text. In jquery I would probably use the .wrap class but how would I detect if the user highlighted something.
For example, when the user writes Hello World then clicks on the bold button it will say <b>Hello World</b>
This mainly requires (1) accessing the selectionStart and selectionEnd properties of the input/textarea element and (2) replacing the substring of the value property across that range with the same text, but wrapped in the desired start and end tags. Also, I think it makes sense to reselect the replaced text, which requires a couple of calls to select() and setSelectionRange(). Also, if there's no selection (meaning start equals end) it's probably a good idea to do nothing at all.
window.selWrapBold = function(id) { selWrap(id,'<b>','</b>'); };
window.selWrapItalic = function(id) { selWrap(id,'<i>','</i>'); };
window.selWrap = function(id,startTag,endTag) {
let elem = document.getElementById(id);
let start = elem.selectionStart;
let end = elem.selectionEnd;
let sel = elem.value.substring(start,end);
if (sel==='') return;
let replace = startTag+sel+endTag;
elem.value = elem.value.substring(0,start)+replace+elem.value.substring(end);
elem.select();
elem.setSelectionRange(start,start+replace.length);
} // end selWrap()
<input type="button" value="bold" onclick="selWrapBold('ta1');"/>
<input type="button" value="italic" onclick="selWrapItalic('ta1');"/>
<br/>
<textarea id="ta1"></textarea>
Get the text of the html element which is wrapping the text, then add as html the text embedded in the <b> tag.
See jQuery DOM Manipulation for tutorials.
I used this question to get the selected text. And this question to
get the element with selected text in it. I combined them in a single function.
function updateHighlightedText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
var node = $(window.getSelection().anchorNode.parentNode); //Get the selected node
node.html(node.text().replace(text, "<b>"+text+"</b>")); //Update the node
}
I am not sure if I confused everyone with the above title. My problem is as follows.
I am using standard javascript (no jQuery) and HTML for my code. The requirement is that for the <select>...</select> menu, I have a dynamic list of varying length.
Now if the length of the option[selectedIndex].text > 43 characters, I want to change the option[selectecIndex] to a new text.
I am able to do this by calling
this.options[this.selectedIndex].text = "changed text";
in the onChange event which works fine. The issue here is once the user decides to change the selection, the dropdownlist is showing the pervious-selected-text with changed text. This needs to show the original list.
I am stumped! is there a simpler way to do this?
Any help would be great.
Thanks
You can store previous text value in some data attribute and use it to reset text back when necessary:
document.getElementById('test').onchange = function() {
var option = this.options[this.selectedIndex];
option.setAttribute('data-text', option.text);
option.text = "changed text";
// Reset texts for all other options but current
for (var i = this.options.length; i--; ) {
if (i == this.selectedIndex) continue;
var text = this.options[i].getAttribute('data-text');
if (text) this.options[i].text = text;
}
};
http://jsfiddle.net/kb7CW/
You can do it pretty simply with jquery. Here is a working fiddle: http://jsfiddle.net/kb7CW/1/
Here is the script for it also:
//check if the changed text option exists, if so, hide it
$("select").on('click', function(){
if($('option#changed').length > 0)
{
$("#changed").hide()
}
});
//bind on change
$("select").on('change', function(){
var val = $(":selected").val(); //get the value of the selected item
var text = $(':selected').html(); //get the text inside the option tag
$(":selected").removeAttr('selected'); //remove the selected item from the selectedIndex
if($("#changed").length <1) //if the changed option doesn't exist, create a new option with the text you want it to have (perhaps substring 43 would be right
$(this).append('<option id="changed" value =' + val + ' selected="selected">Changed Text</option>');
else
$('#changed').val(val) //if it already exists, change its value
$(this).prop('selectedIndex', $("#changed").prop('index')); //set the changed text option to selected;
});