I want to replace the document.write with innerHTML. but it won’t create the links when I try it. I don’t know if there is an issue of how I am building the path variable so it won’t print out the links right. Right now it won’t print out any links.
<!DOCTYPE html>
<html lang="en">
<script>
var path = "";
var href = document.location.href;
var s = href.split("/");
for (var i=2;i<(s.length-1);i++) {
path+="<a class='crumb' href=\""+href.substring(0,href.indexOf("/"+s[i])+s[i].length+1)+"/\">"+s[i]+" </a>";
}
i=s.length-1;
path+="<a class='crumb' href=\""+href.substring(0,href.indexOf(s[i])+s[i].length)+"\">"+s[i]+" </a>";
var url = path;
//document.getElementById(".breadcrumb").innerHTML = url;
document.write(url);
</script>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/webjars/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="/webjars/bootstrap-fileinput/4.2.7/css/fileinput.min.css">
<link rel="stylesheet" href="/webjars/bootswatch/3.3.5+4/yeti/bootstrap.min.css">
<link rel="stylesheet" href="/webjars/font-awesome/4.5.0/css/font-awesome.min.css">
<link rel="stylesheet" href="/webjars/jquery-ui/1.12.1/jquery-ui.min.css">
<link rel="stylesheet" href="/static/app/css/app.css">
<link rel="stylesheet" href="/static/app/css/style.css">
<script src="/webjars/jquery/2.1.4/jquery.min.js"></script>
<script src="/webjars/jquery-ui/1.12.1/jquery-ui.min.js"></script>
<script src="/webjars/bootstrap-fileinput/4.2.7/js/fileinput.js"></script>
<script src="/webjars/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="/webjars/bootstrap-fileinput/4.2.7/js/fileinput_locale_ja.js"></script>
<script src="/static/app/js/app.js"></script>
<style>
.breadcrumb
{
witdh : 100%;
text-align: center;
border: 5px solid transparent;
}
.crumb
{
display: inline-block;
float : left;
font: 16px Helvetica, Arial, Sans-Serif;
color: white;
background-color: #4E95B6;
border: 1px solid black;
}
.crumb: hover
{
color: red;
}
</style>
</head>
<body>
{{>partials/browser-compatibility}}
<div class = "breadcrumb"> </div>
<div class="container-fluid">
you can try document.getElementsByClassName('breadcrumb')[0].innerHTML = url;
use document.ready to ensure have loaded the dom;
you have wrongly used the getElementById;
<div id ="breadcrumb"> </div>
<script>
var path = "";
var href = document.location.href;
var s = href.split("/");
for (var i=2;i<(s.length-1);i++) {
path+="<a class='crumb' href=\""+href.substring(0,href.indexOf("/"+s[i])+s[i].length+1)+"/\">"+s[i]+" </a>";
}
i=s.length-1;
path+="<a class='crumb' href=\""+href.substring(0,href.indexOf(s[i])+s[i].length)+"\">"+s[i]+" </a>";
var url = path;
document.getElementById('breadcrumb').innerHTML = url;
//document.write(url);
</script>
Related
I added 5 buttons in js to html and I want them to be defined with a one second delay, and because of this js, when it reaches the addEventListener line, those buttons are not defined and gives an error.
HTML:
<!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">
<link rel="stylesheet" href="./style.css">
<title>Document</title>
</head>
<body>
<div id="btn-adder"></div>
<script src="./script.js"></script>
</body>
</html>
CSS:
*{
padding: 0;
margin: 0;
box-sizing: border-box;
font-size: 20px;
}
body{
background: rgb(61, 61, 61);
}
#btn-adder{
margin-top: 40px;
text-align: center;
}
#btn-adder button{
padding: 5px;
margin: 5px;
}
JavaScript:
const btnAdder = document.getElementById("btn-adder");
for (let i = 0; i < 5; i++) {
setTimeout(function () {
btnAdder.innerHTML += `<button id="btn${i}">Button ${i}</button>`;
}, 1000);
}
for (let i = 0; i < 5; i++) {
document.getElementById(`btn${i}`).addEventListener("click", function () {
console.log(`Button ${i} clicked`);
});
}
Is there a way to make the addEventListener recognize the new variables?
Yes it's possible and you don't even need the second loop, which is slowing down your code. (even though you probably won't notice it)
Instead of adding the HTML directly to the btn-adder, you can create a new button and directly attach the eventlistener to it.
You can create a new HTML element with document.createElement() and then add all attributes, eventlisteners and everything else you need to the button.
Finally you'll add the newly created button with appendChild() as a new child element to your btn-adder element.
const btnAdder = document.getElementById("btn-adder");
for (let i = 0; i < 5; i++) {
setTimeout(function () {
// create button
const buttonElement = document.createElement('button');
buttonElement.id = `btn${i}`;
buttonElement.textContent = `Button ${i}`
// add eventlistener to the created button
buttonElement.addEventListener("click", function () {
console.log(`Button ${i} clicked`);
});
// add button to their parent
btnAdder.appendChild(buttonElement);
}, 1000);
}
*{
padding: 0;
margin: 0;
box-sizing: border-box;
font-size: 20px;
}
body{
background: rgb(61, 61, 61);
}
#btn-adder{
margin-top: 40px;
text-align: center;
}
#btn-adder button{
padding: 5px;
margin: 5px;
}
<!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">
<link rel="stylesheet" href="./style.css">
<title>Document</title>
</head>
<body>
<div id="btn-adder"></div>
<script src="./script.js"></script>
</body>
</html>
An approach close to what billyonecan mentioned but with use of appendChild instead of innerHTML which can lead to unwanted behaviour.
<!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">
<link rel="stylesheet" href="./style.css">
<style>
*{
padding: 0;
margin: 0;
box-sizing: border-box;
font-size: 20px;
}
body{
background: rgb(61, 61, 61);
}
#btn-adder{
margin-top: 40px;
text-align: center;
}
#btn-adder button{
padding: 5px;
margin: 5px;
}
</style>
<title>Document</title>
</head>
<body>
<div id="btn-adder"></div>
<script>
const btnAdder = document.getElementById("btn-adder");
for (let i = 0; i < 5; i++) {
setTimeout(function () {
let b = document.createElement('button');
b.id = "btn" + i;
b.textContent = "Button " + i;
btnAdder.appendChild(b);
document.getElementById("btn"+i).addEventListener("click", function () {
console.log(`Button ${i} clicked`);
});
},1000 );
}
</script>
</body>
</html>
I'm try to rotate an element but when choosing another element it's all rotate at the same time.
So I need to know how to rotate an element and it would be nice if you guys have a similar system. Because I want to learn more about this kind of system. Which is very necessary and important to me to study and work.
$(document).ready(function() {
var container = document.querySelector(".container");
var rotate = document.createElement("div");
rotate.className = "rotate";
//create Element
$("#add").click(function() {
container.appendChild(addElement());
addEvent();
});
const addElement = () => {
var element = document.createElement("div");
element.className = "resizable";
return element;
}
//add event
function addEvent() {
$(".resizable").click(function(e) {
if (e.currentTarget === this) {
$(this).append(rotate);
$(this).resizable({
handles: 'ne, se, sw, nw'
});
$(this).draggable().rotatable({
handle: $('.rotate')
});
}
});
}
});
.resizable {
width: 100px;
height: 100px;
border: 1px solid #000;
position: relative;
user-select: none;
z-index: 0;
}
.rotate {
width: 10px;
height: 10px;
border: 1px solid #000;
border-radius: 50%;
position: absolute;
top: -30px;
left: calc(50% - 5px);
cursor: move;
}
<!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>jquery</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery.ui.rotatable/1.0.1/jquery.ui.rotatable.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<button class="add" id="add">add</button> //for add element
<button class="save" id="save">save</button> //for save size and position
<div class="container"></div>
</body>
</html>
Thanks everyone in advance for helping me.
I Made a button using html, css and js which occurs randomly on the page.But i want the button inside the body tag and it keeps getting out.
HTML CODE:
<!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">
<script src="main.js" defer></script>
<link rel="stylesheet" href="style.css">
<title>SReflex</title>
</head>
<body>
<button class="random">1 </button>
</body>
</html>
CSS CODE:
*{
margin:0%;
padding:0%;
}
body{
height: 100vh;
width: 100vw;
position: fixed;
}
button.random {
/* looks of the button */
height: 3rem;
width: 3rem;
border: black;
border-style: solid;
border-radius: 50%;
display:block;
position:absolute;
}
JS CODE:
let temp= document.querySelector(".random");
temp.addEventListener("click",change);
function change(){
let posx = Math.floor(Math.random()*1000);
let posy = Math.floor(Math.random()*1000);
let posz = Math.floor(Math.random()*1000);
temp.style.left= posx + "vw";
temp.style.top= posy+ "vh";
temp.style.right= posz+ "vw";
}
How do i make the button to not go off screen, i want the page to not include the scroll bar.
Here is an easy way to do so, it works for the body or for a containing div because it's related to parent size.
check out the snippet.
let temp= document.querySelector(".random");
temp.addEventListener("click",change);
let maxw = temp.parentElement.clientWidth - 50;
let maxh = temp.parentElement.clientHeight - 50;
function change(){
let posx = Math.floor(Math.random() * (maxw));
let posy = Math.floor(Math.random() * (maxh))
temp.style.left= posx + "px";
temp.style.top= posy+ "px";
}
*{
margin:0%;
padding:0%;
}
body{
height: 100vh;
width: 100vw;
position: fixed;
}
button.random {
/* looks of the button */
height: 3rem;
width: 3rem;
border: black;
border-style: solid;
border-radius: 50%;
display:block;
position:absolute;
}
<!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">
<script src="main.js" defer></script>
<link rel="stylesheet" href="style.css">
<title>SReflex</title>
</head>
<body>
<button class="random">1 </button>
</body>
</html>
the -50 is to make sure it doesn't cross the edges, you can edit that to suit your needs.
I'm wondering how i'd put this into a coloured rounded box to make it pop from the background a bit. I will provide a picture of what i'm aiming for below + colour: #23272a or rgb(35, 39, 42)
I have pasted my app.js here:
let stockPriceElement = document.getElementById('shib-worth');
let lastPrice = null;
ws.onmessage = (event) => {
let stockObject = JSON.parse(event.data);
let price = parseFloat(stockObject.p).toFixed(8);
let shib_start_price = 0.00003442;
let shib_balance = 7263219;
let shib_start_worth = shib_start_price * shib_balance;
let shib_worth_now = price * shib_balance;
let convert_shib_worth_to_gbp = shib_worth_now / 100 * 73
stockPriceElement.innerText = parseFloat(convert_shib_worth_to_gbp).toFixed(2);
stockPriceElement.style.textAlign = "center";
stockPriceElement.style.color = convert_shib_worth_to_gbp === shib_start_worth ? '#9e9e9e' : convert_shib_worth_to_gbp > shib_start_worth ? '#4caf50' : '#f44336';
stockPriceElement.style.fontFamily = 'Sora', sans-serif;
lastPrice = convert_shib_worth_to_gbp
};
I have pasted my index.html here:
<!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>Test</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Sora:wght#800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
</head>
<body style="background-color:rgb(44, 47, 51);">
<h1 id="shib-worth"></h1>
<script src="app.js"></script>
</body>
</html>
I'm also looking to add a static "£" sign aligned to the number(inside the box with it) in the same font but in the colour: white
thanks and kind regards!
Use css classes instead of style properties, then investigate border-radius. For your £ consider using a CSS Pseudo element with that as the content.
body {
background-color: #333;
}
.stock-price {
/*Rounded corners*/
border-radius: 5px;
/*The following is basic styling adjust as needed*/
padding: 10px;
font-size: 16px;
font-family: 'Sora', sans-serif;
text-align: center;
background-color: #666;
margin: 6px;
width: 100px;
}
/*Pseudo element for pound sign*/
.stock-price::before {
content: '£';
color: white;
}
/*Classes to indicate price movement*/
.stock-price.no-change {
color: #9e9e9e;
}
.stock-price.loss {
color: #f44336;
}
.stock-price.gain {
color: #4caf50;
}
<div class="stock-price no-change">123</div>
<div class="stock-price loss">456</div>
<div class="stock-price gain">123</div>
Then update your js to (deleteing all your style code):
stockPriceElement.innerText = parseFloat(convert_shib_worth_to_gbp).toFixed(2);
/*Add base class*/
stockPriceElement.classList.add('stock-price');
/*Add appropriate price movement class*/
stockPriceElement.classList.add(convert_shib_worth_to_gbp === shib_start_worth ? 'no-change' : convert_shib_worth_to_gbp > shib_start_worth ? 'gain' : 'loss');
Just as #JonP mentioned, you can create CSS classes and remove the stockPriceElement.style.* uses in your JavaScript code. Simply add the classes you need to that DOM element with stockPriceElement.classList.add().
To include the "£" icon at the beginning of each stock price, create a ::before pseudo element and add the icon as the its content property.
let stockPriceElement = document.getElementById('shib-worth');
let lastPrice = null;
// `ws` wasn't defined in your code
ws.onmessage = (event) => {
let stockObject = JSON.parse(event.data);
let price = parseFloat(stockObject.p).toFixed(8);
let shib_start_price = 0.00003442;
let shib_balance = 7263219;
let shib_start_worth = shib_start_price * shib_balance;
let shib_worth_now = price * shib_balance;
let convert_shib_worth_to_gbp = shib_worth_now / 100 * 73
stockPriceElement.innerText = parseFloat(convert_shib_worth_to_gbp).toFixed(2);
// Add the text-align and font-family declaration
// to a CSS class
stockPriceElement.classList.add("stock-price");
// This could also be broken into separate color
// classes to add/toggle based on the conditional logic
stockPriceElement.style.color = convert_shib_worth_to_gbp === shib_start_worth ? '#9e9e9e' : convert_shib_worth_to_gbp > shib_start_worth ? '#4caf50' : '#f44336';
lastPrice = convert_shib_worth_to_gbp
};
:root {
--grey: #9e9e9e;
--green: #4caf50;
--red: #f44336;
}
body {
background-color: rgb(44, 47, 51);
}
.stock-price {
padding: 14px 1rem;
text-align: center;
font-size: 1.4rem; /* Vary this how you would like */
font-family: 'Sora', sans-serif;
border-radius: 3px;
color: var(--green);
background: rgb(35, 38, 41);
width: fit-content;
-moz-width: fit-content; /* For Firefox */
}
/* Create a Pseudo element to represent the icon */
.stock-price::before {
content: "£";
color: #fff;
margin: 0 6px 0 0; /* vary space around the coin - top right bottom left */
}
.red {
color: var(--red);
}
<!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>Test</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Sora:wght#800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1 id="shib-worth" class="stock-price">377.41</h1>
<h1 id="shib-worth" class="stock-price red">377.41</h1>
</body>
</html>
I would like to capture data from selected div(ie. name of country) by click and put in span , additionaly i want to find some way to mark selected divs, but also unmark others div which were selected previously.
https://codepen.io/tatasek/pen/PoojNGL
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div class="div div__first"></div>
<div class="div div__second"></div>
<div class="div div__third"></div>
<p>I have selected:<span class="selectedCountry"></span></p>
<script src="app.js"></script>
</body>
</html>
CSS
body{
display: flex;
height: 100vh;
justify-content: center;
align-items: center;;
}
.div{
margin-left: 10px;
padding: 3px;
border: 2px solid black;
background-color: skyblue;
cursor: pointer;
}
p{
margin-left: 10px;;
}
.active{
background-color: yellow;
}
JS
const countries = ['Lithuania', 'Latvia', 'Estonia'];
const divList = document.querySelectorAll('.div');
divList.forEach(function(div, index){
div.textContent = countries[index];
})
Thanks for your time!
Michal
Building on what you've done so far, I just added some event listeners to check for changes and add the selected items to the list. Let me know if you need any further clarification.
const countries = ['Lithuania', 'Latvia', 'Estonia'];
const divList = document.querySelectorAll('.div');
divList.forEach(function(div, index){
div.textContent = countries[index];
div.addEventListener('click', function(){
divList.forEach(function(el, i) {
el.classList.remove('active')
})
this.classList.toggle('active');
})
})
var choices = document.getElementsByTagName('div')
for(var i = 0; i < choices.length; i++) {
choices[i].addEventListener('click', function() {
document.getElementsByClassName('selectedCountry')[0].innerText =
document.getElementsByClassName('active')[0].innerText;
})
}
body{
display: flex;
height: 100vh;
justify-content: center;
align-items: center;
}
.div{
margin-left: 10px;
padding: 15px;
border: 2px solid black;
background-color: skyblue;
cursor: pointer;
}
p{
margin-left: 10px;
}
.active{
background-color: yellow;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div class="div div__first"></div>
<div class="div div__second"></div>
<div class="div div__third"></div>
<p>I have selected:<span class="selectedCountry"></span></p>
<script src="app.js"></script>
</body>
</html>
Try
for (let i = 0; i < document.getElementsByClassName('div').length; i++) {
document.getElementsByClassName('div')[i].addEventListener('click', appendToSpan, false);
}
function appendToSpan(e) {
document.getElementsByClassName('selectedCountry')[0].innerText += e.target.innerText;
}
Edit:
Change to:
const countries = ['Lithuania', 'Latvia', 'Estonia'];
const divList = document.querySelectorAll('.div');
divList.forEach(function(div, index){
div.textContent = countries[index];
div.addEventListener('click', function() {
this.classList.toggle('active');
if (this.classList.contains('active')) {
document.getElementsByClassName('selectedCountry')[0].classList.add(this.innerText);
} else {
document.getElementsByClassName('selectedCountry')[0].classList.remove(this.innerText);
}
let classes = document.getElementsByClassName('selectedCountry')[0].getAttribute('class').split(' ');
document.getElementsByClassName('selectedCountry')[0].innerText = '';
for (let i = 1; i < classes.length; i++) {
document.getElementsByClassName('selectedCountry')[0].innerText += classes[i]
}
})
})
I've used addEventListener on click event on each div. Also I've created selected variable which is an array and keeps selected items. On click I check if the selected value is in selected variable by indexOf() function which returns -1 if there is not. Then I push() value to the array if it's not selected yet or delete it by splice() and index of value.
Array is printed by join() function which concats each value of array,
const divList = document.querySelectorAll('.div');
const output = document.querySelector('.selectedCountry');
const countries = ['Lithuania', 'Latvia', 'Estonia'];
let selected = [];
divList.forEach((div, index) => {
div.textContent = countries[index];
div.addEventListener('click',()=> {
var indexOfDiv = selected.indexOf(countries[index]);
(indexOfDiv >= 0)
? (selected.splice(indexOfDiv,1) && div.classList.remove('selected'))
: (selected.push(div.textContent) && div.classList.add('selected'))
output.textContent = selected.join(', ');
});
});
.div { border: 1px solid lightgray; margin: 0.5rem; padding: 0.25rem 0.4rem; }
.div.selected { border-color: lightgreen; }
<div class="div div__first"></div>
<div class="div div__second"></div>
<div class="div div__third"></div>
<p>I have selected:<span class="selectedCountry"></span></p>
const countries = ['Lithuania', 'Latvia', 'Estonia'];
const divList = document.querySelectorAll('.div');
const selectedCountry = document.getElementsByClassName('selectedCountry')[0];
function clearSelection() {
divList.forEach(function(div) {
div.classList.remove('active');
})
}
divList.forEach(function(div, index){
div.textContent = countries[index];
div.addEventListener('click', function() {
clearSelection();
this.classList.add('active');
selectedCountry.innerText = document.getElementsByClassName('active')[0].innerText;
})
})
body{
display: flex;
height: 100vh;
justify-content: center;
align-items: center;
}
.div{
margin-left: 10px;
padding: 15px;
border: 2px solid black;
background-color: skyblue;
cursor: pointer;
}
p{
margin-left: 10px;
}
.active{
background-color: yellow;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div class="div"></div>
<div class="div"></div>
<div class="div"></div>
<p>I have selected:<span class="selectedCountry"></span></p>
<script src="app.js"></script>
</body>
</html>