How to fix a button with javascript function in html - javascript

I'm trying to get all title out of body text.
I created a button and linked my function to it.
However, when I click on it, it disappears and I want it to stay in the same place because I will add other buttons with other functions.
Do you know any idea how I could keep it always in there?
I tryed to use fixed position but soon realised that it just fixes the button on top if I scroll down for example.
Also, when I get the titles my text is in different shrift, I just wonder why is that?
Your guidance will be appreciated.
This is what I have at the moment:
<html>
<head>
<meta charset="utf-8">
<title>test</title>
<style>
#navigation li{
display:inline;
postion:absolute;
}
#navigation a{
padding:2px 2px;
background-color:#09F;
color:#FFFFFF;
}
#navigation a:hover{
background-color:#F90;
color:#666;
}
</style>
<div id="navigation">
<a href="#"><input type=button onclick="myFunction()">
</div>
</head>
<body>
<div>
<p id="demo">
<pre>
<b>This is one title</b>
I'm writing here
the text that I
don't need to get.
<b>Other title</b>
And so we'll test
whether this thing works.
</p>
</pre>
</div>
<script>
function myFunction() {
var text = document.body.innerText;
var titles =text.match(/^\n(.+?)\n\n/mg);
for (var i = 0; i < titles.length; i++) {
document.write(titles[i] + "<br />" + "<br />");
}
}
</script>
</body>
</html>

Basically you have an opening <a> tag but not a closing one. That makes your whole website a link. But apart from that you had a lot of invalid HTML. Closing tags that were mixed up and HTML between </head> and <body>.
Your HTML should look like:
<html>
<head>
<meta charset="utf-8"/>
<title>test</title>
<style>
#navigation li{
display:inline;
postion:absolute;
}
#navigation a{
padding:2px 2px;
background-color:#09F;
color:#FFFFFF;
}
#navigation a:hover{
background-color:#F90;
color:#666;
}
</style>
</head>
<body>
<div id="navigation">
<input type=button onclick="myFunction()" />
</div>
<div>
<p id="demo">
<pre>
<b>This is one title</b>
I'm writing here
the text that I
don't need to get.
<b>Other title</b>
And so we'll test
whether this thing works.
</pre>
</p>
</div>
<script>
function myFunction() {
var text = document.body.innerText;
var titles =text.match(/^\n(.+?)\n\n/mg);
for (var i = 0; i < titles.length; i++) {
document.write(titles[i] + "<br />" + "<br />");
}
}
</script>
</body>
</html>

Here you go. I have fixed the HTML, made it more semantic (by removing the onclick from the HTML), and made the algorithm simpler by using document.getElementsByTagName().
New code:
var r = document.getElementById('results');
document.getElementById('btn').onclick = myFunction;
function myFunction() {
var titles = document.getElementsByTagName('b');
for (var i = 0; i < titles.length; i++) {
r.innerHTML += titles[i].innerHTML + "<br />" + "<br />";
}
}

Related

How to syntax highlight a content-editable div without external libraries?

I'm trying to make a web text editor that has live syntax highlighting like Visual Studio Code but the problem is when I try to highlight, it puts my cursor in the back of the editor.
My code:
<html>
<head>
<title>Code</title>
<style>
body {
margin:0px;
padding:0px;
overflow:hidden;
}
#code {
background:#2b2e33;
color:white;
font-family:Monaco;
width:100%;
height:100%;
font-size:12px;
}
</style>
</head>
<body>
<div id="code" contenteditable="true"></div>
<script>
var div = document.getElementById("code");
setInterval(function() {
var code = div.innerText;
code = code.replace("var","<span style='color:magenta'>var</span>");
div.innerHTML = code;
},100)
</script>
</body>
The cursor seems to go to the back and the text is being reversed for no apparent reason...

How do I style a paragraph element created in JS

I am trying to style a paragraph element which I created in JavaScript.
I am developing a simple To do list so I can improve my skill set.
So I created a paragraph element in JavaScript and I am trying to style it using JS.
My HTML:
<head>
<link href='https://fonts.googleapis.com/css?family=Lato:100,300,400,300italic' rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<title>To Do List</title>
</head>
<body>
<h1>My Tasks</h1>
<h4><span id="number1"></span> tasks</h4>
<button id="addItem">Add item</button>
<div id="item-list">
</div>
<script src="js/script.js"></script>
</body>
My JS:
var toDoItems = [];
var i = 1;
document.getElementById("addItem").onclick = function (){
var userInput = prompt("Enter your Todo: ")
toDoItems.push(userInput);
document.getElementById("item-list").innerHTML += "<p>"+userInput+ "</p>";
}
Using innerHTML in this case (innerHTML+=) is a bad idea. Because per time that you click your button, previous p tags will be replace with new ps.
In first step, add your new todos with a function similar this:
var List=document.getElementById("item-list");
function AddNewTodo(t, styles/*{style1: "value",...}*/){
var todo=document.createElement("p");
todo.innerHTML=t;
for(var s in styles) todo.style[s]=styles[s];
List.appendChild(todo);
}
Real sample:
window.onload=function(){
var List=document.getElementById("item-list");
function AddNewTodo(t, styles/*{style1: "value",...}*/){
var todo=document.createElement("p");
todo.innerHTML=t;
for(var s in styles) todo.style[s]=styles[s];
List.appendChild(todo);
}
document.getElementById("addItem").onclick = function (){
AddNewTodo(prompt("Enter your Todo: "),
{color: "#900", display: "list-item", listStyle: "inside", paddingLeft: "20px"});
}
}
<h1>My Tasks</h1>
<h4><span id="number1"></span> tasks</h4>
<button id="addItem">Add item</button>
<div id="item-list">
</div>
But you can use stylesheet instead of inline style. For this, only change your function like this:
window.onload=function(){
var List=document.getElementById("item-list");
function AddNewTodo(t, styles/*{"simple style name": "simmple css value",...}*/){
var s=document.createElement("style");
document.head.appendChild(s);
var sty="";
for(var st in styles) sty+=st+":"+styles[st]+";";
s.sheet.insertRule("#item-list>p{"+sty+"}", 0);
var todo=document.createElement("p");
todo.innerHTML=t;
List.appendChild(todo);
};
document.getElementById("addItem").onclick=function(){
AddNewTodo(
prompt("Enter your Todo:"),
{"background-color": "#f0f0f0", display: "list-item", "list-style": "inside", padding: "15px"}
);
};
};
<h1>My Tasks</h1>
<h4><span id="number1"></span> tasks</h4>
<button id="addItem">Add item</button>
<div id="item-list">
</div>
TIP:
in first way, you must pass styles as CamelCase similar js syntax (border-top > borderTop), but in second method, pass them like css syntax (border-top, background-color ,...).
Other way:
you can define style in style tag:
<style type='text/css'>
#item-list>p{
color: #f90;
/*other styles*/
}
</style>
In this case, your function will be similar this:
function AddNewTodo(t){
var todo=document.createElement("p");
todo.innerHTML=t;
List.appendChild(todo);
}
full sample:
window.onload=function(){
var List=document.getElementById("item-list");
function AddNewTodo(t){
var todo=document.createElement("p");
todo.innerHTML=t;
List.appendChild(todo);
}
document.getElementById("addItem").onclick = function (){
AddNewTodo(prompt("Enter your Todo: "));
}
}
#item-list>p{
color: "#900";
display: list-item;
list-style: inside;
padding-left: 20px
}
<h1>My Tasks</h1>
<h4><span id="number1"></span> tasks</h4>
<button id="addItem">Add item</button>
<div id="item-list">
</div>
The easiest way to style an element using plain Javascript is as such:
document.getElementById("myDiv").style.borderColor = "red";
First you get the element by the id. You can give an element an id like this: <div id="myDiv"></div>
Then you get the element by using the document.getElementById() function.
And then you can style it using the style object.
But the best way to do it is by still using a stylesheet or to do it dynamically using jQuery.
What you should do is make variable for document.getElementById("item-list") and then add .style.backgroundColor('white'); or you can do
document.getElementById("item-list").style.backgroundColor('white');
Create your classes with set of style formatting you want to do. Then you can use function as example given below:
function addClass() {
var element = document.getElementById("myPara");
element.classList.add("mystyle");
}
function removeClass() {
var element = document.getElementById("myPara");
element.classList.remove("mystyle");
}
To change the style of an HTML element, use this syntax:
document.getElementById(id).style.property = new style
example : add document.getElementById("item-list").style.color ='red'; this line after toDoItems.push(userInput);
just add a class to the p-element and style it via css
document.getElementById("item-list").innerHTML += '<p class="foo">'+userInput+'</p>';
You can add a class name to p tag and write css for that class This may help yours
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var toDoItems = [];
var i = 1;
document.getElementById("addItem").onclick = function (){
var userInput = prompt("Enter your Todo: ")
toDoItems.push(userInput);
document.getElementById("item-list").innerHTML += "<p class='className'>"+userInput+ "</p>";
}
});
</script>
<style>
.className {
border:1px solid #ccc;
}
</style>
</head>
<body>
<h1>My Tasks</h1>
<h4><span id="number1"></span> tasks</h4>
<button id="addItem">Add item</button>
<div id="item-list">
</div>
</body>
</html>
Thanks i figured it out by adding a class to the paragraph tag.

Why is the text getting appended to the wrong html element?

Overview: I have an editable div section. Below the div, there is a button which creates a span element, inserts the text "tag" in the span element and finally appends the span element in that editable div
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style type="text/css">
#sample-div
{
border-style: solid;
border-width: 1px;
border-color: black;
height:100px;
overflow: auto;
}
</style>
<script type="text/javascript">
function addTags()
{
var tag = document.createElement("span");
tag.className = "tag"
tag.innerHTML = "tag";
$('#sample-div').append(tag);
}
</script>
</head>
<body>
<div id="sample-div" contenteditable="true"></div>
<input type="button" value="date" id="sample-tags" onclick="addTags()">
</body>
</html>
Observation: I click on the button, the span element is added to the div as expected
<div id="sample-div" contenteditable="true">
<span class="tag">tag</span>
</div>
<input type="button" value="date" id="sample-tags" onclick="addTags()">
However, after I start typing inside the div, I noticed the following:
<div id="sample-div" contenteditable="true">
<span class="tag">tag this is a continuation</span>
</div>
My expectation was:
<div id="sample-div" contenteditable="true">
<span class="tag">tag</span> this is a continuation
</div>
So, my question is why the text "this is a continuation" also getting appended inside the span element? How do I achieve the one stated under my expectation?
The easiest solution would be to set the contentEditable attribute of your span to be false:
function addTags() {
var tag = document.createElement("span");
tag.className = "tag"
tag.innerHTML = "tag";
tag.contentEditable = false;
$('#sample-div').append(tag);
}
Side note: since you are using jQuery you don't need to manually create the tag:
function addTags() {
var tag = '<span class="tag" contenteditable="false">tag</span>'
$('#sample-div').append(tag);
}

Call a javaScript url when a visitor clicks inside div

How to execute a javaScript url when a visitor clicks inside div
Like this example :
<html>
<head>
<meta charset="UTF-8">
<style>
.youtube .play,.youtube img{cursor:pointer;position:absolute}
.youtube{position:relative;padding-bottom:56.23%;height:0;overflow:hidden;max-width:100%;background:#000;margin:5px}
.youtube embed,.youtube iframe,.youtube object{position:absolute;top:0;left:0;width:100%;height:100%;z-index:100;background:0 0}
.youtube img{bottom:0;display:block;left:0;margin:auto;max-width:100%;width:100%;right:0;top:0;border:none;height:auto;-webkit-transition:.4s all;-moz-transition:.4s all;transition:.4s all}
.youtube img:hover{-webkit-filter:brightness(75%)}
.youtube .play{height:72px;width:72px;left:50%;top:50%;margin-left:-36px;margin-top:-36px;background:url(//i.imgur.com/TxzC70f.png) no-repeat}
</style>
</head>
<body>
<div class="youtube" data-id="YQHsXMglC9A"></div>
</body>
<script>
/* Light YouTube Embeds by #labnol */
/* Web: http://labnol.org/?p=27941 */
document.addEventListener("DOMContentLoaded",
function() {
var div, n,
v = document.getElementsByClassName("youtube");
for (n = 0; n < v.length; n++) {
div = document.createElement("div");
div.setAttribute("data-id", v[n].dataset.id);
div.innerHTML = labnolThumb(v[n].dataset.id);
div.onclick = labnolIframe;
v[n].appendChild(div);
}
});
function labnolThumb(id) {
var thumb = '<img src="https://i.ytimg.com/vi/ID/hqdefault.jpg">',
play = '<div class="play"></div>';
return thumb.replace("ID", id) + play;
}
function labnolIframe() {
var iframe = document.createElement("script");
iframe.setAttribute("src", "https://www.youtube.com/embed/" + this.dataset.id + "?autoplay=1");
iframe.setAttribute("frameborder", "0");
iframe.setAttribute("allowfullscreen", "1");
this.parentNode.replaceChild(iframe, this);
}
</script>
</html>
Like this picture
image
.
Html code + javascript :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div id="a" style="background-color:#999; height:90px; width:250px;" >Click here</div>
</body>
</html>
Javascript :
<script type="text/javascript">
document.write("Hello World!");
</script>
Or :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
How do I run javaScript url when a visitor clicks inside div ?
Something liked this would do it...
function clickMe() {
alert("You clicked me!")
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div id="a" style="background-color:#999; height:90px; width:250px;" onclick="clickMe()" >Click here</a></div>
</body>
</html>
First of all, instead of trying to run a script, you should try to run a function.
For example
function test(){
document.write("Hello World!")
}
function test2(){
document.getElementById("output").innerHTML = "Hello World!"
}
<div onclick="test()">
<p> Click me </p>
</div>
<div onclick="test2()">
<p> Click me (won't remove screen) </p>
</div>
<div id="output">
</div>
Clicking on the first div will call the test() function. This function will however overwrite everything on the screen, that's not what you want.
The second method doesn't do that, instead it sets the content of the third div to "Hello World!"
I believe you want to run a JavaScript function when your div gets clicked. You just need to add an onclick() event to your <div> tag and declare that function. So your div would be something like this:
<div id="a" style="background-color:#999; height:90px; width:250px;" onclick="writeFunction();">Click here</div>
And the function, with the same name as you declared on your onclick:
<script type="text/javascript">
function writeFunction(){
document.write("Hello World!");
}
</script>
As you have used document.write and i have kept that, it does not show the result that you have illustrated in your picture and your div is vanishing. In order to do as you have imagined, you have to add a <p> element which is initally blank:
<p id='text'></p>
and then ask your function to set its text, like this:
document.getElementById('text').innerHTML = "Hello World!";
You can learn more here: https://www.w3schools.com/jsref/event_onclick.asp

Displaying text when link is clicked

This is inside my CSS:
div.hide {
display:none;
}
div.show {
color: #66CCFF;
}
This is in my HTML:
16:10
<script language="JavaScript">
function showText(show,hide)
{
document.getElementById(show).className = "show";
document.getElementById(hide).className = "hide";
}
</script>
<a name="16:10" onclick="showText('text1')" href="javascript:void(0);"></a>
<div id="text1" class="hide">This is your monitors aspect ratio.</div>
I'm trying to make the first link display the "This is your monitors aspect ratio." text lower on the page.
Any help is much appreciated.
Pure CSS Answer
Ok, if you just want to append text after you have moved to a position in a page using an anchor tag, you could do it with nothing but CSS similar to the following:
a:target:after{
content: " Test";
background-color: #ccffcc;
}
What this does is appends the text "Test" after the active anchor and colors. Here is an example page with implementation:
<!DOCTYPE html>
<html>
<head>
<title>Link Printer 2</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<style>
a:target:after{
content: " Test";
background-color: #ccffcc;
}
.bigSection{
height: 200px;
}
</style>
</head>
<body>
<div class="bigSection">
<div><a name="first">First</a></div>
<div>To First</div>
<div>To Second</div>
<div>To Third</div>
</div>
<div class="bigSection">
<div><a name="second">Second</a></div>
<div>To First</div>
<div>To Second</div>
<div>To Third</div>
</div>
<div class="bigSection">
<div><a name="third">Third</a></div>
<div>To First</div>
<div>To Second</div>
<div>To Third</div>
</div>
</body>
</html>
Answer using JavaScript
You need to bind an eventListener and prevent it from moving to the next page. Here is a way to do it with JavaScript or CSS. The JavaScript way will actually set the text to whatever you want. The CSS way will hide actually hide the element.
<!DOCTYPE html>
<html>
<head>
<title>Link Printer</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<style>
.hide{
display: none;
}
</style>
<script>
function jsShowText(event) {
var divToManip = document.getElementById("text");
if (divToManip.innerHTML === "") {
divToManip.innerHTML = "Hello";
}
else {
divToManip.innerHTML = "";
}
event.preventDefault();
}
function cssShowText(event) {
var divToManip = document.getElementById("text");
if (divToManip.className === "") {
divToManip.className = "hide";
}
else {
divToManip.className = "";
}
event.preventDefault();
}
function setListeners() {
document.getElementById("jsPrinter").addEventListener("click", jsShowText, false);
document.getElementById("cssPrinter").addEventListener("click", cssShowText, false);
}
window.onload = setListeners;
</script>
</head>
<body>
<div><a id="jsPrinter" href="" onclick="showText();">Click With JavaScript</a></div>
<div><a id="cssPrinter" href="" onclick="showText();">Click With CSS</a></div>
<div id="text">I'm text</div>
</body>
</html>
"showText" must receive an id parameter to be used with the call to "document.getElementById"
Try this, just 1 link that will display the text below after click:
<a name="16:10" onclick="showText('text1')" href="javascript:void(0);">16:10</a>
<script language="JavaScript">
function showText(id)
{
document.getElementById(id).style.display = "block";
}
</script>
<div id="text1" style="display:none;">This is your monitors aspect ratio.</div>
I'm just using style display to hide/show the element. Hope it helps.
just change your css like this:
div.show {
display:block;
color: #66CCFF;
}
Here I am going to provide an example with something that I was working, thank you Alberto Montellano for the example, that gave me an idea, however what was required at the end was something a little different, with the option not to show the data and display it only when I click and make it disappear when click again. In this example I am going to give you two options; you can have a button or a link to trigger the JS function to display and hide the body text, you can choose if you want the button or link that is way I put a comment (optional), both behave as the same, it is up to you which one you want to use.
<!DOCTYPE html>
<html>
<head>
<!-- CSS -->
<style>
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top:20px;
}
</style>
</head>
<body>
<!-- text before the button or link -->
<p>Click the "PIN" button (or link) to display PIN options:</p>
<!-- The Pin button (optional) -->
<button type="button" onclick="myFunction()">PIN button:</button>
<!-- The Pin link (optional) -->
</br></br></br>
<a onclick="myFunction()" href="javascript:void(0);">PIN link:</a>
<!--Data will display or hide (toggle)-->
<div id="myDIV"style="display:none;">
These are the steps to get your PIN number: Bla bla bla.
</div>
<p><b>Note:</b> The text display when you click the button or link will take space, if you click again will be toggle.</p>
<!-- JS -->
<script>
function myFunction() {
var x = document.getElementById('myDIV');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
</script>
</body>
</html>

Categories

Resources