How to set textarea value to a hero text? - javascript

I'm trying to create a webpage. But it's main is this. If, somebody types something to the textarea, get it's value maybe with javascript, and display it in a hero text. Is it possible?
* {
margin: 0;
padding: 0;
}
h1 {
margin-left: 500px;
}
<textarea id="input"></textarea>
<h1 id="hero_text"></h1>
<button class="test" id="test">Enter</button>

Let's assume the text that of the hero image is in this:
<h1 id='hero_text'></h1>
And that your text area is:
<textarea id='input'></textarea>
Then you can use the textarea's onchange event to track when the user changes the text in the textarea, and update the hero text accordingly:
EDIT: To track changes while the user is typing (not after they de-select the textarea, use oninput instead of onchange).
var h1 = document.getElementById('hero_text');
var textarea = document.getElementById('input');
textarea.oninput = function() {
//note that inside this event handler, 'this' points to the textarea
h1.innerHTML = this.value;
}
Edit 2: Here's a snippet that's based on the code you just provided:
var h1 = document.getElementById('hero_text');
var textarea = document.getElementById('input');
var btn = document.getElementById('test');
btn.onclick = function() {
//note that inside this event handler, 'this' points to the button
h1.innerHTML = textarea.value;
}
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
</head>
<body>
<style>
*
{
margin: 0;
padding: 0;
}
h1
{
margin-left: 500px;
}
</style>
<script src="test.js"></script>
<textarea id="input"></textarea>
<h1 id="hero_text"></h1>
<button class="test" id="test">Enter</button>
</body>
</html>

Related

add a button using javascript to an existing DIV

On my page I have:
<div id='something'></div>
and I want to append this type of 'button' to it using JS:
<span class="picon-p-add-news"></span>Read more news
I tried to use document.createElement but I'm not sure how to make it not just append it as text. How do I do this ?
Something like this, where you can pass your element ID and URL through function arguments.
<!DOCTYPE html>
<html>
<head>
<script>
function appendButton(elementId, url){
var buttonEl = document.createElement("a");
buttonEl.href = url;
var buttonTextEl = document.createElement("span");
buttonTextEl.className = "picon-p-add-news";
buttonTextEl.innerText = "Read more news";
buttonEl.appendChild(buttonTextEl);
document.getElementById(elementId).appendChild(buttonEl);
}
</script>
</head>
<body>
<div>
<button id="button">Click to add</button>
<div id='something'></div>
</div>
<script>
document.getElementById("button").addEventListener('click', () => appendButton("something", "/news_events/"));
</script>
</body>
</html>
Use document.createElement to create the specified HTML elements. Then you can append those to your #something root element using Node.appendChild function. You can also use Element.innerHTML to gets or sets the HTML markup contained within the element.
The Node.appendChild() method adds a node to the end of the list of children of a specified parent node.
const something = document.getElementById('something');
// creating the span element, then add a class attribute
const span = document.createElement('span');
span.setAttribute('class', 'picon-p-add-news');
span.innerHTML = 'span'; // some text to improve visualization
// create the anchor element with the href attribute
const a = document.createElement('a');
a.setAttribute('href', '/news_events/');
// append the span element inside the <a>
a.appendChild(span);
a.innerHTML += 'anchor'; // add extra text for display
// add the <a> element tree into the div#something
something.appendChild(a);
#something {
border: 1px solid;
text-align: center;
font-size: 2rem;
}
#something > a {
padding: 8px;
}
.picon-p-add-news {
background: red;
padding: 0 4px;
}
<div id="something"></div>
Like this? You can use the innerHTML attribute to add HTML inside of an Element
document.getElementById("something").innerHTML += '<span class="picon-p-add-news"></span>Read more news';
<div id='something'></div>
Or, if you created this as an Element with createElement, you can use appendChild:
let a = document.createElement("a");
a.setAttribute("href", "/news_events/");
let span = document.createElement("span");
span.setAttribute("class", "picon-p-add-news");
a.appendChild(span);
a.innerHTML += "Read more news";
document.getElementById("something2").appendChild(a);
<div id="something2"></div>
1) Create a element:
var aEl = document.createElement('a');
aEl.href = "/news_events/"
2) Create span element:
var spanEl = document.createElement('span');
spanEl.classList.add('picon-p-add-news');
3) Append span element to a element
aEl.appendChild(spanEl);
4) Insert text in a element
aEl.insertAdjacentText('beforeend','Read more news');
5) Append whole a tree to you div
var divEl = document.getElementById('something');
divEl.appendChild(aEl);
<html>
<head>
<style>
#myDIV {
border: 1px solid black;
margin-bottom: 10px;
}
</style>
</head>
<body>
<p>Click the button to create a P element with some text, and append it to DIV.</p>
<div id="myDIV">
A DIV element
</div>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var para = document.createElement("P");
var t = document.createTextNode("This is a paragraph.");
para.appendChild(t);
document.getElementById("myDIV").appendChild(para);
}
</script>
</body>
</html>
Give something like this a try: I used https://www.w3schools.com/jsref/met_document_createelement.asp for reference.

How can I make multiple buttons to change a different div background color?

Take a look at what I am trying to make:
https://codepen.io/SomeRandomGuy0/pen/aWvGxO
I was able to make the color of the square change color using the button "Blue". What I want to do is make multiple buttons to change the color of the square to what it says in the button. For example if I clicked on a button that says "Green", the square will turn green and if I clicked on another button that says "Purple", it will turn purple.
I am getting introduced to DOM in JavaScript so sorry for such a basic question.
HTML:
<html>
<head>
<meta charset = "UTF-8" />
<title>DOM Practice</title>
</head>
<body>
<div id = 'square'></div>
<button onClick = changeColor() >Blue</button>
</body>
</html>
CSS:
#square{
width: 100px;
height: 100px;
background-color: red;
}
JavaScript:
function changeColor(){
var elem = document.getElementById( 'square' );
elem.style.backgroundColor = 'blue';
}
You can pass the color as parameter on calling function at button
check this code pen
https://codepen.io/anon/pen/BRoPJo
<button onClick = changeColor('Blue') >Blue</button>
<button onClick = changeColor('green') >green</button>
<button onClick = changeColor('yellow') >yellow</button>
JS
function changeColor(color){
var elem = document.getElementById( 'square' );
elem.style.backgroundColor =color;
}
The simplest approach could be to update changeColor() to take an argument of color.
So for example,
Javascript:
function changeColor(color){
var elem = document.getElementById( 'square' );
elem.style.backgroundColor = color;
}
Then in the HTML we could do:
<html>
<head>
<meta charset = "UTF-8" />
<title>DOM Practice</title>
</head>
<body>
<div id = 'square'></div>
<button onClick = changeColor('blue') >Blue</button>
<button onClick = changeColor('red') >Red</button>
</body>
</html>
This will allow us to generalize the changeColor() function, and make it more reusable for future applications!
Use an if/else statement in your function, I'm not going to do it for you, but the logic should be, if blue button is clicked, change to blue, if red button is clicked change to red and so on.
data-attributes are great for this: https://jsfiddle.net/sheriffderek/0hm9wnk7/ I also like to use rel to hook the js into the markup instead of classes to keep things really clear.
<div class='square' rel='box'></div>
<ul class='color-list' rel='box-colors'>
<li class='color' data-color='red'>red</li>
<li class='color' data-color='blue'>blue</li>
...
</ul>
...
.square {
width: 100px;
height: 100px;
background: lightgray;
}
.color-list .color {
cursor: pointer;
}
...
// $('selector/element') - 'queries'(looks for) for the object in the DOM / j-'query' get it?
// var $thing (with $sign is just a convention to remind you that it's a jQuery object / that comes with some jQuery specific stuff)
var $box = $('[rel="box"]'); // cache the element with rel='box' to a pointer(variable) for use later
var $boxColors = $('[rel="box-colors"]'); // same idea
var $colorTriggers = $boxColors.find('.color'); // same idea / see .find() method
$colorTriggers.on('click', function() {
// .on() is a method for attaching event handlers - in this case, 'click'
thisColor = $(this).data('color'); // get the clicked element's data-attr for data-color
$box.css('background', thisColor); // set the box css background to the color you just retrieved from the data-attr
});
EDIT -- this approach is simplest IMO
Codepen DEMO
HTML:
<html>
<head>
<meta charset = "UTF-8" />
<title>DOM Practice</title>
</head>
<body >
<div id='preview'></div>
<input id="colorpicker" type="color" />
</body>
</html>
JS:
document.addEventListener('DOMContentLoaded', e => {
const preview = document.getElementById('preview');
const picker = document.getElementById('colorpicker');
preview.style.backgroundColor = picker.value;
picker.addEventListener('input', e => {
preview.style.backgroundColor = e.currentTarget.value
})
})
ORIGINAL -- an excuse to play with css vars
Here's an approach:
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
const getRandomColor = () => colors[Math.floor(Math.random() * colors.length)]
const selectColor = (color) => document.body.style.setProperty('--current', color);
document.addEventListener('DOMContentLoaded', e => {
const preview = document.getElementById('square');
const changeColor = (e) => {
let color = getComputedStyle(e.currentTarget).getPropertyValue('--color-name');
selectColor(color);
let logStyles = `
color: black;
font-weight: bold;
background-color: ${color};
font-size: 18px;`;
console.log(`color changed to %c ${color} `, logStyles);
}
// 1. select purple for starting color
// 2. create buttons
// NOTE: I created the buttons programatically, but you could just as easily
//
// <button style="--color-name:red;">red</button>
// <button style="--color-name:orange;">orange</button>
// etc...
selectColor('rebeccapurple')
colors.forEach((color, i) => {
let button = document.createElement('button');
button.style.setProperty('--color-name', color);
button.onclick = changeColor;
button.textContent = color;
document.body.appendChild(button);
})
})
body {
--current: 'green';
}
#square{
background-color: var(--current);
width: 150px;
height: 150px;
margin-bottom: 15px;
}
button {
padding: 8px 16px;
background: white;
border: 1px solid #f3f3f3;
color: var(--color-name);
margin-right: 8px;
}
<html>
<head>
<meta charset = "UTF-8" />
<title>DOM Practice</title>
</head>
<body >
<div id = 'square'></div>
</body>
</html>

How to make UI more responsive for other screen sizes?

I have an html page in which I have a textbox (Type your text) and TextArea list. I need to type into the textbox and then click Add button so that whatever is there in textbox goes to my TextArea list. I need to type in this below format in the textbox.
Name=Value
This textbox will be used by the user to quickly add Name Value pairs to the list which is just below that textbox. let's say if we type Hello=World in the above textbox and click add, then in the below list, it should show as
Hello=World
And if we again type ABC=PQR in the same textbox, then in the below list, it should show like this so that means it should keep adding new Name Value pair just below its original entry.
Hello=World
ABC=PQR
But if the syntax is incorrect like if it is not in Name=Value pair then it should not add anything to the list and instead show a pop up that wrong input format. Names and Values can contain only alpha-numeric characters. I also have three more buttons Sort by name, Sort by value and Delete button. Once I click either of these buttons, then it should sort entries in TextArea list using either name or value and delete entries as well. Now I have all above things working fine without any issues.
Here is my jsfiddle. I need to use plain HTML, CSS and Javascript, I don't want to use any library yet as I want to keep it simple as I am still learning. Now I am trying to see whether we can make UI more responsive like the UI should adjust based on what screen size is viewing it. For example, if viewed on a mobile phone (i.e. Android or iPhone), the page should automatically adjust to present the layout in a better way. This also applies to re-sizing the browser on desktop, and viewing the page on a tablet.
What are the changes I need to make in my CSS or HTML to make it more responsive? Any improvements I can make here? Since my UI is very simple so there should be some easy way or some improvements I can make here.
Below is my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
<style type="text/css">
.main{
background:white;
padding: 35px;
border-radius: 5px;
}
#my-text-box {
font-size: 18px;
height: 1.5em;
width: 585px;
}
#list{
width:585px;
height:300px;
font-size: 18px;
}
.form-section{
overflow:hidden;
width:700px;
}
.fleft{float:left}
.fright{float:left; padding-left:15px;}
.fright button{display:block; margin-bottom:10px;}
html, body {
height: 100%;
font-family: "Calibri";
font-size: 20px;
}
html {
display: table;
margin: auto;
}
body {
display: table-cell;
vertical-align: middle;
background-color: #5C87B2;
}
</style>
<script language="javascript" type="text/javascript">
document.getElementById('add').onclick = addtext;
function addtext() {
var nameValue = document.getElementById('my-text-box').value;
if (/^([a-zA-Z0-9]+=[a-zA-Z0-9]+)$/.test(nameValue)){
var x = document.getElementById("list");
var option = document.createElement("option");
option.text = nameValue;
x.add(option);
}
else
alert('Incorrect Name Value pair format.');
}
document.getElementById('btnDelete').onclick = deleteText;
function deleteText(){
var myList = document.getElementById('list');
var i;
for (i = myList.length - 1; i>=0; i--) {
if (myList.options[i].selected) {
myList.remove(i);
}
}
}
document.getElementById('sortByValue').onclick = sortByValue;
function sortByValue(){
var myList = document.getElementById('list');
var values = new Array();
for (var i=0;i<myList.options.length;i++) {
values[i] = myList.options[i].text;
}
values.sort(function(a, b){
if(a != "" && b != ""){
return a.split('=')[1].localeCompare(b.split('=')[1])
} else {
return 0
}
});
clearList(myList);
fillList(myList, values);
}
document.getElementById('sortByName').onclick = sortByName;
function sortByName(){
var myList = document.getElementById('list');
var values = new Array();
for (var i=0;i<myList.options.length;i++) {
values[i] = myList.options[i].text;
}
values.sort(function (a, b){
if(a != "" && b != ""){
return a.split('=')[0].localeCompare(b.split('=')[0])
} else {
return 0
}
});
clearList(myList);
fillList(myList, values);
}
function clearList(list) {
while (list.options.length > 0) {
list.options[0] = null;
}
}
function fillList(myList, values){
for (var i=0;i<values.length;i++) {
var option = document.createElement("option");
option.text = values[i];
myList.options[i] = option;
}
}
</script>
</head>
<body>
<div class = 'main'>
<h3>Test</h3>
<label for="pair">Type your text</label></br>
<div class="form-section">
<div class="fleft">
<input type='text' id='my-text-box' value="Name=Value" />
</div>
<div class="fright">
<button type="button" id='add' onclick='addtext()'>Add</button>
</div>
</div>
<label for="pairs">Name/Value Pair List</label></br>
<div class="form-section">
<div class="fleft">
<select id="list" multiple></select>
</div>
<div class="fright">
<button type="button" id='sortByName' onclick='sortByName()'>Sort by name</button>
<button type="button" id='sortByValue' onclick='sortByValue()'>Sort by value</button>
<button type="button" id='btnDelete' onclick='deleteText()'>Delete</button>
<button type="button">Show XML</button>
</div>
</div>
</div>
</body>
</html>
W3 have a number of resources on responsive web design:
http://www.w3schools.com/html/html_responsive.asp
http://www.w3schools.com/css/css_responsive_intro.asp
Without using PHP to detect the browser/user agent, your responsive design will typically involve ensuring the site is more fluid and flowing, allowing for changing browser widths (as in the first example above) and/or by delivering differing stylesheets depending on the viewport size and media type in CSS (second example).

Javascript check if event handler has been clicked

I want to display paragraphs with the help of js, and I want for every time that user clicks button "right" to display a paragraph but instead all of the paragraphs are being showed. How can I check if a user has clicked a button, so that I can display only ONE next paragraph when the button was clicked.
Thanx in advance.
<style type="text/css">
p {
border:1px solid black;
width:100px;
height:30px;
display:none;
}
</style>
<p>some text1</p>
<p>some text2</p>
<p>some text3</p>
<p>some text4</p>
<p>some text5</p>
<input type="button" value = "left" />
<input type="button" value = "right"
onclick = "
var p = document.getElementsByTagName('p');
for(var i = 0; i <p.length; i++){
show_paragraphs(i);}
"
id = "right"/>
You need to Itrate over each para and check if the previous para is displayed;if displayed set as display none for the previous and for display block as for current one and return.
here is the sample code
<html>
<style type="text/css">
p {
border:1px solid black;
width:100px;
height:30px;
display:none;
}
</style>
<p style="display:block">some text1</p>
<p>some text2</p>
<p>some text3</p>
<p>some text4</p>
<p>some text5</p>
<input type="button" value = "left" />
<input type="button" value = "right"
onclick = "navigate()"
id = "right"/>
<script>
function navigate(){
var p = document.getElementsByTagName('p');
for(var i = 1; i <p.length; i++){
if( p[i-1].style.display == 'block')
{
p[i].style.display = 'block' ;
p[i-1].style.display ='none';
return;
}
}
}
</script>
</html>
Check out the Content Swapper jQuery plug-in which does exactly what you're trying to do.
Or if you must do it your way, here's your code modified to work:
<!doctype html>
<html>
<head>
<style type="text/css">
p {
border:1px solid black;
width:100px;
height:30px;
display:none;
}
</style>
<script>
var i=0, paras = document.getElementsByTagName('p');
function hideAllPara() {
for(var j=0; j<paras.length; j++) {
paras[j].style.display = 'none';
}
}
</script>
</head>
<body>
<p>some text1</p>
<p>some text2</p>
<p>some text3</p>
<p>some text4</p>
<p>some text5</p>
<input type="button" value = "left" />
<input type="button" value = "right" onclick = "hideAllPara(); paras[i].style.display = 'block'; i = (i < paras.length-1) ? i+1 : 0;" id = "right"/>
</body>
</html>
You must note though, working with inline click events or JavaScript is never recommended.
Anyway, so basically each time you click the right button, first we need to hide all paragraphs, then display only the one required; to do that we need to keep track of the index/pointer and reset it once we've reached the end.
And if you wish to show a paragraph when the page load, you could do any of the following in CSS:
p:first-child {display: block;}
p:nth-child() /* specify whatever index you wish to show off all the selected paragraphs on the page */
Give a class name called "active" to the paragraph you wish to show and declare it in CSS as so; p.active {display: block;}
What about:
var left=document.getElementById("left");
var right=document.getElementById("right");
var show=function(){
var paragraphs=document.getElementsByTagName("p");
var current=0;
var len=paragraphs.length;
return function(event){
var button=event.target.id;
var direction=0;
var visi="visible";
if(button==="left"){
visi="hidden";
direction=(current>0)?-1:0;
} else {
direction=(current<len-1)?1:0;
}
paragraphs[current].style.visibility=visi;
current+=direction;
};
}();
left.addEventListener("click", show);
right.addEventListener("click", show);
jsFiddle

Letter Shadows from User Input

Goal: User types name into user input field, selects Animate button, and name is printed vertically with each letter containing a drop shadow of each letter. The Javascript library Raphael may be desirable.
Problem: So far what I have is the name being printed vertically twice side by side. Obviously the second column should be the letters as drop shadows, but I don't know how to change the style of them to look like shadows.
My manager gave me one hint: "I had to create a 2nd text line placed underneath the text...and I used the .blur() method on it. If I have to give you another hint I'll be hinting you to the door."
I'm in some real trouble here. If anyone has suggestions, solutions, anything it would be very much appreciated.
<html>
<head>
<script src="raphael-min.js"></script>
<script src="jquery-1.7.2.js"></script>
<script type="text/javascript">
function animate() {
var txt = document.getElementById("words").value;
var area = txt;
var splittxt = txt.split("");
document.getElementById("letters").innerHTML = "";
document.getElementById("letters2").innerHTML = "";
var i;
for (i = 0; i < splittxt.length; i++) {
document.getElementById("letters").innerHTML = document.getElementById("letters").innerHTML + splittxt[i] + "<br>";
document.getElementById("letters2").innerHTML = document.getElementById("letters2").innerHTML + splittxt[i] + "<br>";
}
//displays how many symbols are in text box and what is in text box
document.getElementById("num").innerHTML= txt.length;
document.getElementById("msg").innerHTML = txt;
r.clear();
// Make our pink rectangle
ellipse = r.ellipse(40, 15, 30, 5).attr({"fill": "#969696", "stroke": "none"});
ellipse.glow({width:10});
}
</script>
<style type="text/css">
#letters
{
background-color:yellow;
width:25px;
float:left;
}
#letters2
{
letter-spacing:0px;
display:block;
-moz-transform: rotate(80deg);
margin-left:90px;
margin-top:80px;
width:25px;
color:#DEDEDE;
}
</style>
</head>
<body>
Text: <input type="text" id="words" value="" />
<input type="button" value="Animate" onclick="animate()" />
<div id='msg'></div>
<div id='num'></div>
<div id='letters'></div>
<div id="letters2"></div>
<div id="draw-here-raphael" style="height: 200px; width: 400px; margin-top:0px;">
</div>
<div id="elps" style="margin-left:100px;"/>
<script type="text/javascript"> //all your javascript goes here
var r = new Raphael("draw-here-raphael");
</script>
</body>
</html>
Live Long and Prosper.
Do you really need raphael? What I did was simply print out your words onto an element and get the shadow with css's text-shadow. To get the vertical text I added a </br> after each letter.
Take a look at the fiddle: http://jsfiddle.net/joplomacedo/wVGbF/
Here's the code in case you can't see the fiddle:
HTML
Text: <input type="text" id="words" value="" />
<input id="animateBtn" type="button" value="Animate" />
<div class="print"></div>
CSS
.print {
font: 44px/0.8em "Lobster", cursive;
color: gold;
text-shadow: 2px 2px 3px rgba(0, 0, 0, 0.6);
}​
JS
var join = Array.prototype.join;
$('#animateBtn').on('click', function() {
var txt = $('#words').val(),
spaced_txt = join.call(txt, "</br>");
$('.print').html(spaced_txt);
});​
Here is also the text output function with Raphael:
function draw_text() {
var txt = document.getElementById("words").value;
var posy = txt.length*10;
r.clear();
var attr = {font: "50px Helvetica", opacity: 0.5};
var text = r.text(40, 40+posy, txt).attr(attr).attr({fill: "#0f0"}); // underlayer or "shadow"
text.attr({transform: "r270"}); // rotate 270 degrees
var text2 = r.text(43, 43+posy, txt).attr(attr).attr({fill: "#aa0"}); // text above
text2.attr({transform: "r270"}); // rotate 270 degrees
r.safari();
}
var r = new Raphael("draw-here-raphael");
The full script, based on this example, is here.

Categories

Resources