newline doesn't work in javascript - javascript

When I use the new line character in java-script it is not working. I post my code below.
var i=1;
while(i<=5)
{
document.write(i+"\n");
i++;
}
The outcome looks like this.
1 2 3 4 5

since you are writing into HTML Document, you should write <br>
var i=1;
while(i<=5){
document.write(i+"<br/>");
i++;
}

Instead of "\n", use "<br/>", as the code below:
var i=1;
while(i<=5)
{
document.write(i+"<br/>");
i++;
}
Here is the JSFiddle. When accessing it, click run to see the code.

The reason that you are not seeing the newline characters as you expected is because you are likely trying to render this in HTML. If that is the case, "\n" is not rendered as a newline. Which is why #Yuriy Galanter said to include <br/> which is. If you were to write to the console.log then it would work as you have it written.

Related

Getting started with javascript, got a questions

I'm following w3school beginner tutorial for JS. There's something I don't understand from code below:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var cars = ["Saab","Volvo","BMW"];
var text = "";
for(var i = 0; i < cars.length; i++) {
text+=cars[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Can someone explain me the logic of text+=cars[i]? I understand that += means increment, but I canĀ“t understand the logic behind adding the array element to variable text.
Thank you so much for your quick replies! I've got a follow up question: is there an alternative to display the same type of information with having to use the
var text = "";
and
text+=cars[i]
pieces of code? If so, how would the snippet of code look like and what should I insert into HTML if not
text
?
Thanks again!
a+=b is short for a=a+b. In your case you have text = text + cars[i] + "<br>".
text is a string, and you are using + to append a value from the array (that contains strings), and then append "<br>"
The value of text at the end of the loop is going to be
Saab<br>Volvo<br>BMW<br>
where br stands for line break. So that each of them gets printed on new line.
And the last line of code
document.getElementById("demo").innerHTML = text;
changes the value of html element which has id of demo to that of text.
text += cars[i] + '<br>';
Concatenates element i of the cars array to the text, separated by a <br> tag.
Consider it like this,
text+=cars[i] + "<br>";
is actually
text=text+cars[i]+"<br>";
so that rather than deleting the old value it will concatenate the new word with existing string.(String Concatenation).
PS:As a fellow beginner a small piece of advice rather than following W3 Schools please go to site like codecademy which helps you to learn along with practice and proper explanation.
Don't think of += as incrementing, that's ++.
a = a + b
a += b;
Those two statements are the same. The bottom one takes the variable on the left side (a) and appends the right side to it (b), and then assigns it all back to he left side (a). So it's just a shorthand.
So what you're doing in your code is appending the string from cars[i] to your variable text.
This would do the same thing:
text = text + cars[i] + "<br>";
Once the loop runs, you will have the following in text:
Saab<br>Volvo<br>BMW
In javascript + is used for string concatenation
The code
for(var i = 0; i < cars.length; i++) {
text+=cars[i] + "<br>";
}
is picking each element from the array and concatenating "" to it.
If you console log the text before setting the innerHTML, it looks something like this -
"Saab<br>Volvo<br>BMW<br>"
here they do it actually just to show theres no point of doing it this way they just wanna show to reach each individual inside an array and concatanate it into a string the very same thing you can do with Array.prototype.join() method dont think here that u must use as they show always concatanate into a string if you want you can simply use every single individual inside as u wish as well
+= is not increment. It's adding (in this case concatenation) and saving result in the same variable.
var a +=b;
Is the same to:
var = a + b;
In your case script concatenates all array elements into one string and adding <br> tags between them.

How to repeat a code in html without writing the same code again and again

Well I wish to show a given piece of code multiple times on a given page but I wish to minimize the redundant code being repeated everywhere (simple copy/paste) . Well I heard of people using Javascript or JQuery to store the given piece of code say HTML or CSS and than they use some simple div renders or the <!--data--> tag multiple number of times in wherever place they want the code to appear, which I have no idea how to use that is store a info in the scripts or html and then render it multiple number of places with a single div or comment.
Can anyone illustrate how to do this with an example. A bit more info on such tricks will be very resourceful.
Have a look at server side includes
Include it like this in your page :
<?php include ('content.html'); ?>
Here is simple JavaScript code to repeat text: (which can be modified as per requirement may be to insert innerHTML)
function repeat(n,Txt){
for(i=0; i<n;i++)
document.write(Txt+ char(13)); //char(13) to draw new line
}
Just call this function as per requirement, on window.Load or onclick of a button..
Update: Check this fiddle to Enter repeating HTML fiddle
Code for innerHTML:
function repeat(n,Txt){
for(i=0; i<n;i++){
document.getElementById("repeater").innerHTML =
document.getElementById("repeater").innerHTML + "<br /> "
+ Txt;
}
}
An example of reusable code could look like the following (JavaScript example).
var application = {
addition: function (sum1, sum2) {
return sum1 + sum2;
},
multiplication: function (sum1, sum2) {
return sum1 * sum2;
}
};
And you could call it as follows
application.addition(5, 10); /* returns 15 */
Or more complexly
application.multiplicaton(application.addition(5, 10), 2) /* returns 30 */
Try Like
<!--#include virtual="/menu.shtml" -->
It will support by most of web servers.
More Info.

Javascript not outputting left angle bracket

I have some code which creates a 'typing text effect' on a page - i.e. javascript takes a string and outputs it on the screen in a way that makes it look like it is being typed. I took the code from a demo here.
The problem is that I want it to output html code, e.g. the output on the screen should be something like:
<html>
<body>
Something here etc etc...
</body>
</head>
In chrome, this works in a rather erratic fashion - sometimes it works perfectly, but other times it doesn't display the first left angle bracket, leaving me with the output of 'html>' rather than '<html>'. In safari, the left angle bracket doesn't display at all. I've tried various things, using '<' instead of the bracket, using unicode, but that everything I do seems to end with the same result.
Here is a github gist of the code, and here is a bl.ocks page to showing it in action. I tried to make a jsfiddle but couldn't get it to run properly, sorry!
Any help is much appreciated, it's been driving me nuts.
Cheers
Nick
Instead of
$span.append(thisLine[letterIndex]);
try
$span.text($span.text() + thisLine[letterIndex]);
Or, per crush's comment below, you could do a string replace:
$span.append(thisLine[letterIndex].replace(/</g,'<').replace(/>/g,'>'));
This works because when you want to display HTML tags, you need to use < and > rather than just < and >, otherwise the browser thinks you're putting in an actual HTML tag, if that makes sense to you. The jquery text method automatically escapes the brackets for you, and in my second example, we're just doing a string replace before passing the string to append.
It looks as if the code appends '<' as '&','l','t',';'. Not verified this but you might want to try:
function typeLetter(lineIndex, letterIndex, $span, line, callback) {
var thisLine = line;
var thisLength = line.length;
var chunk='';
// add the letter
chunk=thisLine[letterIndex];
if ('&'==thisLine[letterIndex]) {
for (var i=1; i<5; i++) {
letterIndex++;
chunk+=thisLine[letterIndex];
if (';'==thisLine[letterIndex] || letterIndex>=thisLength-1) break;
}
}
$span.append(chunk);
...

How to get the line number of image where alt/title is missing..?

I'm using a javascript function that uses regular expressions to get a list of images without an alt/title attribute:
function AltTitle(aSourceHTML, aResultField) {
try {
regexp = /<img((?:(?!alt)[^<>])*)>/gim;
var vArray = aSourceHTML.match(regexp);
var vLinks = vArray.join("\n\n");
aResultField.value = vLinks;
} catch (err) {
alert("No Images Found");
}
}
Is there any way to get the line numbers along with the image list?
Try using DOM instead to grab the images.
var imgs = [].filter.call(document.images, function(img) {
return !img.alt && !img.title;
});
This will grab all images that don't have alt or title attribute or is empty, but it won't tell you what line the image is at. Try using http://validator.w3.org/ to find that out.
I would say "The Pony He Comes", but this seems to be more dealing with the plain text than the actual HTML.
The way I would do this is to first just split the whole thing on newlines, then loop through each line and run your regex against it. Since you're iterating through the lines, just print out the current iterator value and there you have your line number.
If you already have the source code in a variable, you can split it up by line breaks, and then run your regex against each line.
function AltTitle(aSourceHTML, aResultField) {
aSourceHTML = aSourceHTML.split('\n');
for (var i = 0; i < aSourceHTML.length; i++ {
// run your regex against aSourceHTML[i]...
}
}
If you are trying to do this for a specific page, such as the one you are on, you can do an ajax request for it, and then split that by line breaks and run through it. Try running the following code right here on Stack Overflow in a console. It will show the HTML of this page, with line numbers.
$.get(window.location, function(data){
data = data.split('\n');
for (var i = 0; i < data.length; i++) {
console.log('line ' + i, data[i]);
}
});
But unless you're trying to write a tool for this in javascript, you should just use http://validator.w3.org/. It will find any images without alts/titles for you.
Edit: Wrote an example of how this could work on jsfiddle: http://jsfiddle.net/c8X4K/

How do you check for equality between a jquery .html() variable and ruby on rails generated html?

Currently I am trying to compare two variables, newhtml and oldhtml.
I get the old html using:
var oldhtml = $('#pop').html();
I get the new html using:
var newhtml = ("<%= escape_javascript render(:file => 'shared/_content') %>");
I'm then trying to compare them using:
if(newhtml == oldhtml)
{
//is never called
$('#pop').hide();
}
else
{
//is always called
$('#pop').html(newhtml);
}
but it's not working. In this scenario the oldhtml variable is actually just the previous newhtml variable. So, if you click on the same content on the main page newhtml should actually just be a ruby on rails generated version of oldhtml (the html present in <div id="pop">). I've tried appending them to see where there difference lies, but it looks exactly the same to me. I was hoping someone could nudge me in the right direction? Thanks!
I'd try to put the newhtml in a hidden DOM element and then get that content back from jquery .html()
$('#HiddenDOM').html(newhtml);
if ($('#HiddenDOM').html() === $('#pop').html()) { ... }
Not tested but might cancel out html rendering issues.
Also, use triple equality comparison for javascript: === instead of == . See Cockford on Javascript The Good Parts on youtube for an explanation.
Overall, I'd rethink your design because the comparison might not be truly possible and would open your architecture to all sort of browser mysteries. Sometimes, you first have to find out what doesn't work to get to the working solution.
I can't recall any guarantees regarding the formatting of the html returned by html(), particularly whitepace.
But, at least when I pull a chunk of HTML out of a page in firefox, what comes out seems to be formatted the same as how it was sent by the server.
So, perhaps there are only trivial differences between the strings, e.g. in leading and trailing whitespace. Try using a function line this to compare the two HTML snippets:
function compare_html(a,b) {
a = a.replace(/^\s+/,"").replace(/\s+$/,"");
b = b.replace(/^\s+/,"").replace(/\s+$/,"");
return a == b;
}
The jQuery documentation warns that with .html() "some browsers may not return HTML that exactly replicates the HTML source in an original document". This will also apply to dynamically inserted HTML.
Your best bet is to compare two javascript strings, neither of which is read back from the DOM.
eg:
var newhtml = ("<%= escape_javascript render(:file => 'shared/_content') %>"),
oldhtml = newhtml;
...
if(newhtml == oldhtml)
{
$('#pop').hide();
}
else
{
oldhtml = newhtml;
$('#pop').html(newhtml);
}
It's undoubtedly more complicated than this but I'm sure you get the idea.
That was all very helpful and I actually sort of combined the answers to get something that worked. What ended up working is this:
Get the oldhtml like before:
var oldhtml = $('#pop').html();
Then insert the new html into the div:
$('#pop').html("<%= escape_javascript render(:file => 'shared/_content') %>");
Following that, get the newhtml from the div, the same way I retrieved the oldhtml:
var newhtml = $('#pop').html();
The if statement then works, but you want to make sure to change the div to something arbitrary that can't be retrieved from your database:
if(newhtml == oldhtml)
{
$('#pop').html("<h>toggled_off</h>");
$('#pop').hide();
}
else
{
$('#pop').html(newhtml);
}
strip the tags of both htmls and then compare with ==
`var StrippedString = OriginalString.replace(/(<([^>]+)>)/ig,"");

Categories

Resources