Styling JS-Generated Code - javascript

I am using a "find and replace" type javascript function, and replacing all the backticks in the HTML with <code> tags, and all the pound signs with </code> tags. For some reason my styles are not working unless I code them in on the JS file with the .css() method.
Ideally, the combo should output the code between backticks and pound signs as blocked <code> content, (the <code> tags are generated from JavaScript) with a soft gray background. However, for some reason the styles just don't show up.
If any one can help, I'd greatly appreciate it.
This is my html file test.html:
<!DOCTYPE html>
<head>
<title>Script Test</title>
<script src="http://code.jquery.com/jquery-2.1.1.js"></script>
<link rel="stylesheet" href="styles/code/style.css" type="text/css">
</head>
<body>
<p>This is some code:
`var p = 10; #
`var a = 5; #
`var x; #
`x = a * p; #
`console.log(x); #
All I want is for this to work!
</p>
<script src="codeStyle.js"></script>
</body>
My CSS file (compiled from SASS) style.css:
body {
color: #121212;
font-family: 'Helvetica Neue', serif;
font-weight: 300;
letter-spacing: .25px; }
body div.container {
padding: 10px; }
body div.container code.styled {
font-family: arial, serif;
background-color: #f9f9f9; /* soft gray bg color */
display: block; /* block display style */
margin: 2px 0 2px 2.5%;
padding: 3px;
width: auto;
background-color: #fafafa;
border: 1px solid #f5f5f5; }
/*# sourceMappingURL=style.css.map */
And my js file codeStyle.js:
$('p').each(function() {
var text = $(this).html(); // Grab HTML from each <p>
text = text.replace(/`/gi,"<code class='styled'>"); // Replaces every ` with <code>
text = text.replace(/#/gi,"</code>"); // Replaces every # with </code>
$(this).html(text); // Set <p> html as replaced code
});

To put Partick's answer up: Your CSS is trying to target an element that doesn't exist.
The problem is in this bit of CSS:
body div.container code.styled { }
There is no content that matches this selector, as there is no <div class="container">
To get around this, you can either remove the offending selector from the CSS:
body code.styled {}
or add the requied selector to your HTML:
<div class="container">
<p>Some text <code class="styled">some code</code>.</p>
</div>
Here's a Fiddle of it working.

Related

2 Newline Characters if There is an Empty Line in Textarea

I'm trying to get the number of lines that a textarea has for a line counter (for a text editor), but if there is an emtpy line in the textarea, there are two new lines added. Here is the output:
["// Hello World!","","","The line above was empty","","","Same here!","The line on the bottom of this one is empty!","",""]
My code:
function getLines() {
var textValue = document.querySelector('#editor').value;
var lines = textValue.split("\n");
console.log(lines);
}
At someone's request, here is the HTML:
<div id="visible" contenteditable="true"
onkeyup="updateLineCount()">// Hello World!</div>
<textarea id="code-editor">
Basically I plan on adding syntax highlighting, so the div is content editable, and the JS sends the stuff in the div to the textarea, just to calculate the lines of code. Here is the JS that does this:
textarea.value = document.querySelector("#code-editor").innerText;
The issue you are running into has to do with pulling the innerText value of your contenteditable div and placing it into a <textarea>. This is where the extra newline characters \n are coming from.
Unless you are required to use the <textarea> I would just get the line count from the contenteditable div directly. The only weird quirk here is that there is an extra newline character \n added to the very end of the innerText, but this can just be removed using .split(0, -1).
const updateLineCount = () => {
document.querySelector(".lines").innerHTML = [...Array(document.querySelector("#code-editor").innerText.slice(0, -1).split("\n").length).keys()].map(v => v+1).join("<br>")
}
document.querySelector("#code-editor").addEventListener("keyup", updateLineCount)
.code {
padding: .2em .4em;
border: 1px solid #CCC;
box-sizing: border-box;
display: inline-block;
}
.lines {
color: #555;
font-family: monospace;
width: 2em;
vertical-align: top;
border-right: 1px solid #CCC;
display: inline-block;
}
#code-editor {
font-family: monospace;
width: 40em;
vertical-align: top;
display: inline-block;
}
#code-editor:focus { outline: none; }
<div class="code">
<div class="lines">1</div>
<div id="code-editor" contenteditable="true">// Hello World!</div>
</div>

Multiple script tags in HTML are not executing sequentially

PLEASE VIEW THE RESULT OF CODE SNIPPET IN FULL PAGE
I'm trying to fetch the text contents from a set of nested HTML elements that apparently are appended at runtime by a script/API.
Please note that quote_text & children[j] are elements appended at
runtime by API/script. hence it is not in my control directly. (I found them out using inspect element) So I am trying to change
them using javascript as they are not in my control directly.
However, it happens to be that even though the script/API which is responsible for appending the styled quote HAS CONTENTS IN IT, it is shown BLANK when tried to set its contents to another div using a script
Why is this happening and how do I go about achieving this?
The reason for me to do this is, I do not want the format style given by API. Rather I want it styled in my way.
html,
body {
margin: 0;
padding: 0;
/*height:100%;
overflow:hidden;*/
overflow: hidden;
}
header {
background-color: black;
height: 100vh;
background-size: cover;
background-position: center;
}
/******* QUOTE *********************************************************/
.center_bottom {
position: absolute;
right: 10px;
bottom: -20px;
}
a {
pointer-events: none;
cursor: default;
}
.quote_div2 {
display: block;
color: white;
font-size: 20px;
font-family: Arial;
position: absolute;
left: 10px;
top: 15px;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="1.css">
<script type="text/javascript" src="https://theysaidso.com/gadgets/v3/theysaidso.js"></script>
</head>
<body>
<header>
<!-- PART1 -->
<!-- DIV1: This below script fetches a Quote & displays it in styled fashion -->
<div id="quote_div" class="tso_simple_borders center_bottom q-t">
<script id="sc1">
TheySaidSo.render({
qod_category: 'inspire'
});
//document.getElementById("quote_div").style.display = "none";
</script>
</div>
<!-- PART2 -->
<!-- DIV2: This is division where i want to paste the plain text from DIV1-->
<div class="quote_div2">
<span id="spn"></span>
</div>
<!-- PART3 -->
<!-- In this script, I'm trying to fetch Quote contents and set it onto other div -->
<script>
var txt = "This text should be replaced by ONLY TEXT CONTENTS of below quote";
var qttxt = document.getElementsByClassName("quote_text");
Array.from(qttxt).forEach((el) => {
var children = el.childNodes;
if (el.nodeName.toLowerCase() == 'span') {
el.style.color = "white";
}
for (var j = 0; j < children.length; j++) {
if (children[j].nodeName.toLowerCase() == 'a') {
txt = txt + children[j].innerHTML;
}
}
});
document.getElementById("spn").innerHTML = txt;
</script>
</header>
</body>
</html>
**
for those who are confused about quote_text, It is appended at
backend(Please check the image below for reference):
**
The problem seems to be in the sequence of execution of scripts.
For it to work, the PART1 script should first finish executing and
rendering the Quote Box, and after that PART3 script should execute.
But it seems to be that BEFORE PART1 even finishes executing, PART3 is
executed!! (Which shouldn't happen)

Get all <em> from a <p> and output them like a tag

for example i have a <p> tag which contain some sentences with <em> like below
<p>There's <em>a</em> script that he's
written that is <em>a</em> really cool Batman idea.</p>
and I use some javascript to add a class to all em element
$("em").addClass("Keyword-Result");
And now i'd like to know how am i able to print out all <em class="Keyword-Result") like tags?
However there's no need to add class dynamically here but here is snippet which also appends tags to #tags:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>There's <em>a</em> script that he's
written that is <em>a</em> really cool Batman idea.</p>
<div id="tags"></div>
<style>
em.Keyword-Result {
background-color: grey;
padding: 4px;
border-radius: 2px;
margin:2px;
color:#fff;
}
</style>
<script>
$(document).ready(function(){
$("em").clone().addClass("Keyword-Result").appendTo('#tags');
});
</script>
The easy way:
console.log($("em.Keyword-Result"));
But you don't want to print it in the console but rather on screen? Then you don't need to print them (they are already there) but use css to format them.
<style>
em.Keyword-Result {
background-color: lightgrey;
padding: 5px 10px;
margin-right: 10px;
border-radius: 3px;
}
</style>
See https://jsfiddle.net/d2xrrukh/
Or, if you want to copy the em's to a separate div without needing a loop:
https://jsfiddle.net/d2xrrukh/3/

Why float element does not overlap on h3 element?

My observation is, float elements overlap on its previous elements, but in the below code, div element did not over lap body element.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>All selector</title>
<style type="text/css">
h3{
margin: 0;
heigth: 10px;
}
div, span, p{
width: 80px;
height: 40px;
float: left;
padding: 10px;
margin: 10px;
background-color: #EEEEEE;
}
</style>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.min.js">
</script>
</head>
<body>
<div>DIV</div>
<span>SPAN</span>
<p>P<button>BUTTON</button></p>
<script type="text/javascript">
var elementCount = $('*').css("border", "3px solid red").length;
$('body').prepend("<h3>" + elementCount + " elements found</h3>");
</script>
</body>
</html>
Actual output is:
As per my understanding on float:left,
Expected output is,
Why 3 float elements div, span & p are not overlapping on body element?
Floating element is shown floating against the content that follows it. There is no content after the div / span / p tags. Note: you are prepending the h3 tag to body. Try appending and see what output you get.

Displaying two dynamically added elements in different rows

I've an HTML page like following:
<html>
<body>
<div id="emaildiv" class="main" style="width:150px;height:80px;"></div>
</body>
</html>
I want to add a DIV with a TEXT and BUTTON in to it dynamically. All these are made by using the following javascript.
function newEmailForContact() {
var parentDiv = document.getElementById('emaildiv');
var newEmailDiv = document.createElement('div');
newEmailDiv.setAttribute('id','newEmailDiv');
newEmailDiv.setAttribute('style', 'display:table;');
var newEmail = document.createElement('INPUT');
newEmail.setAttribute('type','text');
newEmail.setAttribute('name','newEmail');
newEmail.setAttribute('class', 'textfield_addemail');
newEmail.setAttribute('id','newEmail');
var addEmailBtn = document.createElement('INPUT');
addEmailBtn.setAttribute('type','button');
addEmailBtn.setAttribute('name','addEmail');
addEmailBtn.setAttribute('id','addEmail');
addEmailBtn.setAttribute('value', 'Add');
newEmailDiv.appendChild(newEmail);
newEmailDiv.appendChild(addEmailBtn);
parentDiv.appendChild(newEmailDiv);
}
But the TEXT and Button are displayed in two different rows.
EDIT :-
CSS class :-
.textfield_addemail {
border-width: 1px;
border-style: solid;
border-color: #999999;
background-repeat: repeat-x;
font-family: Arial, Helvetica, sans-serif;
font-size: 12px;
color: #333333;
width: 120px;
height: 15px;
}
I want to display both in same row. Any solution?
The problem is your initial <div> isn't wide enough at 150px, just increase the size a bit, like this:
<div id="emaildiv" class="main" style="width:250px;height:80px;"></div>​
You can see a working/updated example with only this change here.
Leave out the
newEmailDiv.setAttribute('style', 'display:table;');
Then your span will be displayed as inline and your button should appear next to it

Categories