I know this gets asked a lot and I've already tried some examples from SO, but no luck.
I have a function that allows me to change text in a div and it works, but only as plain text. I want it to work as HTML, but I've tried placing in innerHTML, perhaps in the wrong spot, and separated HTML in my script with + symbols. Nothing seems to work. Either I get the HTML in my text raw or the function simply does not work.
Here's my script as of this time:
$(function() {
var copyStack = [
'<strong>This is bold text within strong tags,</strong>' + ' this is the remainder of my copy.',
'<strong>This is more bold text within strong tags,</strong>' + ' this is the remainder of my second copy.'
];
$("#swatch-0").click(function () {
$(".product-shop-description").text(copyStack[0]);
console.log(copyStack[0]);
});
$("#swatch-1").click(function () {
$(".product-shop-description").text(copyStack[1]);
console.log(copyStack[1]);
});
});
I think This is what you want to do:
var copyStack = [
'<strong>This is bold text within strong tags,</strong>' + ' this is the remainder of my copy.',
'<strong>This is more bold text within strong tags,</strong>' + ' this is the remainder of my second copy.'
];
swatchOne = document.getElementById("swatch-0");
const changeInnerHTML = (elm, inner) => (elm.innerHTML = inner);
swatchOne.addEventListener("click", () => {
changeInnerHTML(swatchOne,copyStack[0]);
});
swatchTwo = document.getElementById("swatch-1");
swatchTwo.addEventListener("click", () => {
changeInnerHTML(
swatchTwo,copyStack[1]);
});
.btn{
background: #cecece;
padding: 1em;
width: max-content;
margin-bottom:1em;
}
#swatch-0{
background: #000;
color:#fff
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div class='btn' id='swatch-0' >Hello</div>
<div class='btn' id='swatch-1' >Hello22</div>
<script src="./script.js"></script>
</body>
</html>
The getElementById property is used to access an HTML element
more info [HERE][]
The innerHTML property is used to access and modify the HTML inside of an HTML element
more info HERE
Solved it! Thanks to some help and some guesswork, here's the answer:
$("#swatch-0-peanut-butter-chocolate-chip").click(function () {
$(".product-shop-description").html(copyVariety[0]);
console.log(copyVariety[0]);
});
Related
I am new to Javascript and I can't figure out why am I getting this error.
Here is my code:
const bckg = document.querySelector(".bckg");
const compStyle = getComputedStyle(bckg);
body {
box-sizing: content-box;
position: relative;
}
.visible {
position: relative;
top: 50px;
margin: auto;
background-color: bisque;
height: 300px;
width: 600px;
overflow: hidden;
}
.bckg {
position: absolute;
left: 0px;
width: 1200px;
height: 300px;
background-image: url("bckg.jpg")
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>New Game</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<script src="script.js"></script>
<div class="visible">
<div class="bckg" id="bckg">
<div class="player"></div>
<div class="obstacle"></div>
</div>
</div>
</body>
</html>
This error I get in Mozilla: "Uncaught TypeError: Window.getComputedStyle: Argument 1 is not an object."
What could it be?
Your script tag needs to be moved to the very end of the body. The script loaded to early.
This error I get in Mozilla: "Uncaught TypeError: Window.getComputedStyle: Argument 1 is not an object." What could it be?
If you read the error message it says it could not find the argument.
The reason for this is that browsers loads JavaScript tags synchronously. It has been a standard since JavaScript was first introduced.
Solution snippet
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>New Game</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="visible">
<div class="bckg" id="bckg">
<div class="player"></div>
<div class="obstacle">
</div>
</div>
</div>
<!-- I moved the script to the end of the body -->
<script src="script.js"></script>
</body>
</html>
Adding a console.log you could have seen that the argument for Window.getComputedStyle is indeed not an object
const bckg = document.querySelector(".bckg");
console.log(bckg); // will return undefined
You can also try out the "defer" attribute, however it has been best practice to move the script tags to the end of the body for compatibility with different older browsers. See https://www.w3schools.com/tags/att_script_defer.asp
Another alternative is to use the "DOMContentLoaded" event
https://developer.mozilla.org/en-US/docs/Web/API/Document/DOMContentLoaded_event
document.addEventListener("DOMContentLoaded", function() {
// code...
});
Delta Boukensha is right - your document hasn't finished loading.
So either put your script at the bottom of your markup as Delta suggests or use a utility function to run code once the document has rendered such as :
function whenDOMready( func ) {
switch( String( document.readyState ) ) {
case "complete":
case "loaded":
case "interactive":
func();
break;
default:
window.addEventListener("DOMContentLoaded", (e) => func());
}
}
Then call it from wherever you want like this :
let bckg;
let compStyle;
function domReady() {
bckg = document.querySelector(".bckg");
compStyle = getComputedStyle(bckg);
/* ...other code here */
}
whenDOMready( domReady );
There are two benefits this utility gives you :
No matter when you call it it will work - either calling your function (func) immediately or when the DOMContentLoaded event fires. If you just add the event listener directly you have to worry about if it has already fired or not.
You are guaranteed that your DOM is ready for inspection and access.
Ok, so all I want to do is : whenever I write something in the Input and press the Button, a new HTML page gets created. But I also want to set the page's name and location. Tried searching it, couldn't find any results...
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Books test</title>
<link rel="stylesheet" href="https://cdn.rawgit.com/Chalarangelo/mini.css/v3.0.1/dist/mini-default.min.css">
</head>
<body>
<input type="text" id="book-input">
<button id="book-button">Create a book</button>
<h1>All the books</h1>
<ul id="books-list"></ul>
<script src="/app.js" defer></script>
</body>
</html>
Javascript
const bookNameInput = document.getElementById("book-input");
const bookCreateButton = document.getElementById("book-button");
var bookName;
var bookId;
bookCreateButton.addEventListener('click', createBook);
function generateRandomNumber() {
var randomNumber = Math.floor(1000000000 + Math.random() * 900000000);
var rn = randomNumber.toString();
return rn;
}
function createBook() {
bookName = bookNameInput.value;
bookId = generateRandomNumber();
fbn = bookName + '_' + bookId
var bookLi = document.createElement("li");
bookLi.classList.add("book-li")
var bookLiA = document.createElement("a");
bookLiA.innerText = bookName;
bookLiA.href = fbn + ".html";
document.getElementById("books-list").appendChild(bookLi);
bookLi.appendChild(bookLiA);
bookNameInput.value = "";
}
Tried using :
const newDoc = document.implementation.createHTMLDocument(title)
But doesn't creates any page...
I already answered your question in comments, so I'm writing this down as a answer so it might be helpful for others too.
So as i was saying it is totally possible to save the file directly from the client side without any need of server or special file system permission on client side -
In Short You can do something like this, Follow this step-by-step -
Get the value of the text input using input.value
Create a Blob out of It
Create a DOM element of anchor element with download attribute
Convert the Blob to an URL Using URL.createObjectURL and Chane the href of previously created anchor element to the returning url
Click on the anchor element without appending it to the DOM
Here is the Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Generate HTML Page</title>
<style>
* {
padding: 0;
box-sizing: border-box;
margin: 0;
}
</style>
</head>
<body style="padding: 20px">
<textarea
placeholder="Enter Your Content Here"
style="width: 100%; height: 500px; font-size: 18px; padding: 18px"
></textarea>
<br /><br />
<button>Download Text as HTML page</button>
<script>
let btn = document.querySelector("button");
let text = document.querySelector("textarea");
btn.addEventListener("click", () => {
if (!/^\s*$/.test(text.value)) {
let a = document.createElement("a");
a.setAttribute("download", "download.html");
let blob = new Blob(text.value.split(""));
let url = URL.createObjectURL(blob);
a.href = url;
a.click();
text.value = "";
} else {
alert("Blank text");
text.value = "";
}
});
</script>
</body>
</html>
Why I am asking this: There are many questions similar to this one, but none of them are having a satisfactory answer.
Question:
It seems like, using Regular expression in a content editable HTML element for replacing specified string badly disturbs user's experience with caret positioning
What happens after using Ragex:
1:'Enter key'(earlier which was able to add line break) will stop working.
2:During any manual edit, caret assumes initial position (which is beginning of the editable HTML element).
So far the answers that I was able to find, have bugs!
My snippet with contenteditable="true" HTML element
```
<!DOCTYPE html>
<html>
<head>
<title>Experiment</title>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<meta name="viewport" width="device width, initial-scale=1.0">
<style>
#spanone{
color:red;
}
#spantwo{
color:yellow;
}
</style>
</head>
<body style="background:royalblue;">
<p id="inp" contenteditable="true" style="height:90vh; width:90vw; background:black; color:white; font-weight:bold;">
{This} [is] {HTML} [rendered], {replaced string} [using ragex]! edit me!
</p>
<script>
$(function(){
$("#inp").on("input" , function(){
var str = $("#inp").text();
var new_str = str.replace(/(\[(?:[\w\s]*)*\])/g, function(match){
return match.replace(/(\w+)/g, '<span id="spanone">$1</span>');
});
var result = new_str.replace(/(\{(?:[\w\s]*)*\})/g, function(match){
return match.replace(/(\w+)/g, '<span id="spantwo">$1</span>');
});
$("#inp").html(result);
});
});
</script>
</body>
</html>
I am trying to practice Javascript but I am getting the
document.getElementById(...) is null error. I am not sure why it is not working. ........................................................................................................................................................................................................................................
<!DOCTYPE html>
<html>
<title></title>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body style="max-width: 960px; margin: 0px auto; background-color: green;">
<section id="practice">
</section>
</body>
<script>
window.onload = function create() {
var newDiv = document.createElement('div');
var newp = document.createElement('p');
var pTextNode = document.createTextNode('First time creating elements on my own.');
newDiv.className = 'contentContainer';
newDiv.id = 'container1';
newDiv.setAttribute('title', 'hello');
newp.appendChild(pTextNode);
newDiv.appendChild(newp);
document.getElementById("#practice").appendChild(newDiv);
}
</script>
</html>
The document.getElementById API takes an ID parameter as a string. You don't need to use the CSS selector method of selecting IDs, so the # should be omitted. The line should read:
document.getElementById("practice").appendChild(newDiv);
For more information about the API, see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
You have it all correct! The issue is your syntax in the getElementById method. Remove the octothorpe ("#") and you'll get the results you're expecting.
Happy Coding!
Is there any change to have input element similar like is on my screenshot.
I would like to change value via javascript and highlight part of text with different color if it will be wrapped with *
Thanks for any help.
You cannot do it with an input element. Here is one alternative:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<style>
/*style it to look like input element*/
[contenteditable] {
border: 1px solid gray;
}
</style>
</head>
<body>
<div id="contentDiv" contenteditable>sdfsdtokendfdfsdfs</div>
<br/>
<input type="button" onclick="test()" value="Click me"/>
<script type="text/javascript">
function test() {
// this is our token
var valueToSelect = "tokendfdf";
var contentDiv = document.getElementById('contentDiv');
// check if div contains wanted token
if (contentDiv.innerHTML.indexOf(valueToSelect) >= 0) {
// create span with wanted color
var replaceString = '<span style="color: red">*' + valueToSelect + '*</span>';
// replace the string with colored span
contentDiv.innerHTML = contentDiv.innerHTML.replace(valueToSelect, replaceString);
}
}
</script>
</body>
</html>
Here is JS Bin example