I have been trying to practice some exercises using Javascript. Here are some challenges I have been facing. Please suggest if there is a mistake or something that I am missing.
Note: I do not want to use Jquery at this stage.
Exercise:
Ask the user to input some text. On the click of a button, the entered text needs to be displayed as rotating.
The first approach I took gets me the result the first time. But if I enter a new text, and click the button, the rotation fluctuates between the old text and new. I am not sure if I am explaining it right. Here's the first attempt:
Test the result: http://learningharvest.co.in/
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Enter the text to be reversed</p>
<div id="texttoberotated">
<input type="text" id="texttobeRot"></p>
</div>
<div>
<button id="rotateText">Rotate Text</button>
<p id="rotatedText"></p>
</div>
<script>
document.getElementById("rotateText").onclick=function (){
var text=null;
text= document.getElementById("texttobeRot").value;
var finaltext=text;
document.getElementById("rotatedText").innerHTML=finaltext;
setInterval(rotatetext, 500);
var numberofRotations=0;
var length=0;
length=text.length;
var i=0;
function rotatetext(){
i=length;
if(numberofRotations<=text.length){
getText();
}else{
numberofRotations=0;
length=text.length;
i=length;
preText=null;
postText=null;
finaltext=null;
getText();
}
}
function getText(){
preText=text.slice(length);
postText=text.slice(0,i);
i--;
finaltext=preText+" "+postText;
numberofRotations++;
length--;
document.getElementById("rotatedText").innerHTML=finaltext;
}
}
</script>
</body>
2. The second attempt I am making is using the childNodes method. However, I am unable to get the nodeValue of the input tag. The nodeValue is working if I try with any other element, but not with the input element.
Also, the function rotatetext is being executed on page load and not when the button is clicked. Works well if I add the onclick event inline in the button tag itself.
Here's the error i get in console:
Rotate text parent child method.html:27 Uncaught TypeError: Cannot read property 'nodeValue' of undefined
at rotatetext (Rotate text parent child method.html:27)
at Rotate text parent child method.html:23
Here's the body content I have drafted so far. At this stage, I am just trying to replace the text "Show Rotated Text here" with the text entered by the user.
<body>
<p>Enter the text to be reversed</p>
<input type="text" id="texttobeRot">
<button id="rotateText">Rotate Text</button>
<p id="rotatedText">Show Rotated Text here</p>
<script>
document.getElementById("rotateText").onclick= rotatetext();
function rotatetext(){
var element=document.getElementById("texttobeRot");
var textNode=element.childNodes[0];
var text=textNode.nodeValue;
var texttobeRotated;
texttobeRotated= text;
document.getElementById("rotatedText").innerHTML=texttobeRotated;
};
Look forward to all of your inputs.
Using the first approach if you add
document.getElementById("texttoberotated").onkeyup = function() {
text = '';
}
to the bottom of your script it will clear the text value when you begin to type and you can enter a new word without the issue of them being jumbled together as you described.
I put a working example of your code at https://codepen.io/chaosmaths/pen/LrwrpQ
Related
I have one <textarea> tag in my website where the user can put there HTML code and see its preview. My problem is when the user enter code below mention in my <textarea> my preview functionality getting fail :
<html>
<textarea>Some code to show</textarea>
</html>
So question is how can I escape this html code in my <textarea> tag as I know the problem is coming because </textarea> tag.
Any solution on this please.
Edit
Question is about using </textarea> within a textarea.
Problem visible here: http://jsfiddle.net/hrP6F/
EDIT: for your purpose this would do:
<textarea>
Outside Textarea
<textarea>Inside Textarea</textarea>
</textarea>
source: How can I embed a textarea inside of another textarea in HTML?
Or use contenteditable like someone already mentioned -> click
FIRST ANSWER: Im not sure I understand perfectly but still. You want to display the code inside text area somewhere else for instance?
You could do that on click like this (I reckon you are not statically putting nested text areas in html?):
HTML:
<textarea id="textarea" >Something code to show</textarea>
<button onclick="show()">show</button>
<div id="showArea"></div>
JS:
function show(){
var t = document.getElementById('textarea').value;
document.getElementById('showArea').innerHTML = t;
}
This is of course if what you want is to display html that is inside textarea. you could also put another textarea inside first one and it will work.
If you want the results to display dynamically you could use
<textarea id="textarea" onkeyup="show()">Something code to show</textarea>
This works even if you put your code (html and text area) inside text area - it displays it, I tested it
You can add a output div for preview purpose. Below is the jQuery script
HTML
<textarea placeholder="Enter your html"><b>test</b></textarea>
Run
<div class="op"></div>
JS
$('.run').click(function(){
$('.op').html($('textarea').val());
return false;
});
DEMO
I have a situation with sample code as follows:
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<p>
<h1>The header</h1>
<div>
matter ia always matter matter ia <strong>bold matter</strong> matter matter <em>italics matter</em>matter ia <em><strong>bold italics matter</strong></em>lways matter
</div>
</p>
</body>
</html>
I am just trying to retrieve the specific tags like body->p->div->em->strong when I click on "bold italics matter" using jQuery. Is there any standard method to retrieve as per the click event?
If you wan to get the tag name of the element which is clicked, then you can use:
$('*').click(function(e) {
e.stopPropagation();
console.log($(this).prop('tagName'));
});
Fiddle Demo
I'm not completely sure about what you are trying to accomplish. If you are trying to retrieve the tag itself that the text is contained in, i would recommend that you put a <span> tag in around the the text in question and do an onclick="function()" or simply put the onclick right on the <strong> tag.
As far the the JQuery/Javascript goes, if you want to retrieve the content, it looks like
var foo = document.getElementById.innerHTMl("id");
However, this requires you to have an id in your tags which is probably the best, if not
'standard' method of retrieving the content that is within the tag.
After reading your comments, i am editing this post:
The best way to get the parent elements is to use the JQUery .parent() function. I'd imagine that you would just recursively state something like this:
var foo = $("nameofelement").parent();
I hope this is more of what your looking for.
Thanks for contributing everybody. At last I made it myself with the following code.
$(document.body).click(function(e){
var Tags=[], Target=e.target, stat_msg="";
Tags.push(Target.tagName);
while($(Target).parent().get(0).tagName!=="BODY")
{
Tags.push($(Target).parent().get(0).tagName);
Target=$(Target).parent();
}
Tags.push("BODY");
for(i=Tags.length;i>0;i--)
stat_msg=stat_msg+Tags[i-1]+" ";
alert(stat_msg);
});
Here is my code:
<html>
<head>
<script type="text/javascript">
var x= document.getElementById("2").value;
document.getElementById("1").innerHtml = x;
</script>
</head>
<body>
<p hidden="hidden" id="2">This paragraph should be hidden.</p>
<p>This is a visible paragraph.</p>
<p><b>Note:</b> The hidden attribute is not supported in IE.</p>
<p id="1"></p>
</body>
</html>
in this code i have a hidden tag as you can see. I want that the javascript code read text value of the p tag with an id 2 and then print the same value to other <p> tag wiht id="1". But this is not working. Earlier i even tried to use nodeValue but also this is not working and when i checked out in google developer tool then it was showing an error as following:
Cannot read property 'value/nodeValue' of null
please note:
after a quick experiment i noted that after adding a event handler <body onload="y();>" there was no error but there was no expected result!
please help!
hidden is an input element type, not a p attribute:
<input type="hidden" id="2" value="This input should be hidden." />
There are three problems:
there is no innerHtml, innerHTML is the correct syntax.
the hidden "p" does not have a value, it is not an input field. use innerHTML for accessing it.
your javascript code runs before the browser knows about paragraps, so they don't exist when you want them to be accessed. put javascript after the paragraphs or run the code after the page is loaded.
this should work:
<html>
<head>
</head>
<body>
<p hidden="hidden" id="2">This paragraph should be hidden.</p>
<p>This is a visible paragraph.</p>
<p><b>Note:</b> The hidden attribute is not supported in IE.</p>
<p id="1"></p>
<script type="text/javascript">
var x= document.getElementById("2").innerHTML;
document.getElementById("1").innerHTML = x;
</script>
</body>
</html>
Don't use numbers for ID.
Try something like <p id="hello"></p>
I think you need to change your tag to then you can set a CSS class with .hidden { display:none; }.
Wrap your Javascript in a function and call it when you need to or go back to your
Also as Maaz said, try not to use numbers in your ID's.
var hiddenValue = document.getElementById('2').innerHTML;
document.getElementById('1').innerHTML = hiddenValue;
The problem with this (and if you try and style it also) is that classes and ID's should not start with (or include) numbers.
Rename your ID's to one and two and then update your javascript accordingly.
e.g
<p id="one">Some stuff</p>
Also hidden cannot be used with a p element as it's for inputs only.
You're better off using display:none; in CSS.
If you NEED to access it via css as a number, you can use
[id='1']{
/*code*/
}
but your javascript still wont work.
As James has pointed out, using numbers for ID's is perfectly valid in HTML5.
Take the following page:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"/>
</head>
<body>
<div class="hashtag">#one</div>
<div class="hashtag">#two</div>
<form accept-charset="UTF-8" action="/home/index" method="post">
<textarea id="text-box"/>
<input type="submit" value ="ok" id="go" />
</form>
<script type="text/javascript">
$(document).ready(function() {
$(".hashtag").click(function() {
var txt = $.trim($(this).text());
$("#text-box").append(txt);
});
});
</script>
</body>
</html>
The behavior I would expect, and that I want to achieve is that when I click on one of the divs with class hashtag their content ("#one" and "#two" respectively) would be appended at the end of the text in textarea text-box.
This does happen when I click on the hash tags just after the page loads. However when I then also start editing the text in text-box manually and then go back to clicking on any of the hashtags they don't get appended on Firefox. On Chrome the most bizarre thing is happening - all the text I type manually gets replaced with the new hashtag and disappears.
I probably am doing something very wrong here, so I would appreciate if someone can point out my mistake here, and how to fix that.
Thanks.
2 things.
First, <textarea/> is not a valid tag. <textarea> tags must be fully closed with a full </textarea> closing tag.
Second, $(textarea).append(txt) doesn't work like you think. When a page is loaded the text nodes inside the textarea are set the value of that form field. After that, the text nodes and the value can be disconnected. As you type in the field, the value changes, but the text nodes inside it on the DOM do not. Then you change the text nodes with the append() and the browser erases the value because it knows the text nodes inside the tag have changed.
So you want to set the value, you don't want to append. Use jQuery's val() method for this.
$(document).ready(function(){
$(".hashtag").click(function(){
var txt = $.trim($(this).text());
var box = $("#text-box");
box.val(box.val() + txt);
});
});
Working example:
http://jsfiddle.net/Hhptn/
Use the val() function :)
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div class="hashtag">#one</div>
<div class="hashtag">#two</div>
<form accept-charset="UTF-8" action="/home/index" method="post">
<textarea id="text-box"></textarea>
<input type="submit" value ="ok" id="go" />
</form>
<script type="text/javascript">
$(document).ready(function(){
$(".hashtag").click(function(){
var txt = $.trim($(this).text());
$("#text-box").val($("#text-box").val() + txt);
});
});
</script>
</body>
</html>
Does that help?
The reason append does not seem to work is because the value of the textarea is made up of the child node, but by treating it as multiple seperate nodes the screen won't update, according to my Firebug. Firebug will show me the updated child nodes, but NOT the text I typed manually into the textarea, whereas the screen shows me the manually typed text but not the new nodes.
You can reference by value of textarea.
$(document).ready(function () {
window.document.getElementById("ELEMENT_ID").value = "VALUE";
});
function GetValueAfterChange()
{
var data = document.getElementById("ELEMENT_ID").value;
}
works fine.
if(data.quote) $('textarea#message').val($('textarea#message').val()+data.message +' ').focus();
here's an easy one (that I'm struggling with)! I have a textarea, a button, and an empty div. All I want to do is insert the updated contents of the textarea into the div onClick of the button. Here's what I've got so far:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function get_text() {
$("#preview").replaceWith( $("#editor").val() );
}
</script>
</head>
<body>
<form>
<textarea name="editor" id="editor">GrumbleCakes</textarea>
<input type="button" value="Preview" onclick="get_text();" />
</form>
<div id="preview"></div>
</body>
</html>
It works the first time you click the button... with the value that was in the textarea on page load ("GrumbleCakes"), but that's it. It won't work with any updated text.
You can set the innerHTML or text content of the preview div by using the html or text functions:
$("#preview").html($("#editor").val());
.replaceWith actually replaces the DOM element. So the div is removed and replaced with the text. Subsequent calls to the function will no longer find the div, since it's been removed.
I think you want to use
.html($("#editor").val()).
Both
$('#preview").html($("#editor").val())
and
$("#preview").text( $("#editor").val())
should work.
However, .html will allow anyone to inject html or javascript into your site leaving it wide open for cross-site scripting attacks...
jikes!!
man you are replacing div with the contents of the textarea. use this function instead:
function get_text(){
var t=$("editor").val();
$("#preview").text(t);
}