Javascript: document.createElement('div') seems to add margin - javascript

so I was just messing around with some Javascript for learning purposes and noticed a weird behavior.
I created buttons that, on click, create a duplicate of themselves. The first newly created button has a left margin that I cannot find an explanation for. Does anyone know the reason for that and how to remove that unwanted spacing?
var makeNewBtn = function() {
var newBtn = document.createElement('button');
newBtn.className = 'btn';
newBtn.textContent = 'Click Me';
newBtn.onclick = makeNewBtn;
document.getElementById('buttons').appendChild(newBtn);
};
document.getElementsByClassName('btn')[0].onclick = makeNewBtn;
body {
padding: 25px;
}
.btn {
height: 100px;
width: 100px;
background: beige;
font: 18px Arial;
border: 0;
border-radius: 10px;
outline: none;
}
<div id="buttons">
<button class="btn">Click Me</button>
</div>
result here

There are two issues here:
You have a space after the first button in the HTML
Remove the spaces between the <div> and the <button>.
<div id="buttons"><button class="btn">Click Me</button></div>
Here's a great article about the many ways to "fight" against this space: https://css-tricks.com/fighting-the-space-between-inline-block-elements/
You didn't set margin/padding for the button styles
If not explicitly set, the browser may use a margin/padding, or inherit these from another style.
.btn {
padding: 0;
}
Here is a working fiddle: https://jsfiddle.net/1cg6uvdh/ I changed the background color to red so that the gaps are more visible.

Related

Why does the shadow host get focus even with delegatesFocus being false?

Consider the following example:
let template = document.querySelector('.quote-template').innerHTML;
let shadowElement = document.querySelector('.quote-app');
let shadow = shadowElement.attachShadow({
mode: 'open'
});
shadow.innerHTML = `
<style>
.quote {
font-family: Arial;
font-size: 20px;
padding: 25px 40px;
background-color: #000;
font-weight: 300;
line-height: 24px;
color: #fff;
margin-bottom: 15px;
}
.quote:focus {
color: red;
}
</style>
${template}
`;
console.log(document.querySelector('.quote-app').shadowRoot.delegatesFocus)
.quote-app:focus {
outline: 2px dotted red;
}
<template class="quote-template">
<div class="quote">
Use mouse right click on the test button and you will see red outline on the shadow root.
<button>Test focus</button>
</div>
</template>
<div class="quote-app"></div>
As you can notice, when the "test focus" button gets focus, the parent shadow host also get :focus styles. Now, the MDN docs say that
If true(delegatesFocus), when a non-focusable part of the shadow DOM is clicked, the first focusable part is given focus, and the shadow host is given any available :focus styling.
It doesn't say anything about when a focusable part gets focused. Here in my scenario delegatesFocus is false, why does the shadow host get the :focus styling?
P.S: The observed behaviour contradicts google web.dev's documentation. They mention:
If you were to set delegatesFocus: false, here's what you would see instead:
The outer black dotted outline turns into red in reality, contradicting the image.

How to change color of text in a textarea

I have a textarea and when I type something, for some words the color should change.
For example, if the typed text is next one: He went to the market to buy an apple
The "market" word should become green
The "apple" word should become red
This is my current code:
var str = 'market';
var value = str.includes('market');
if (value == str) {
document.getElementById("text").style.color = "green";
} else {
document.getElementById("text").style.color = "red";
}
<textarea rows="9" cols="100" id="text" onClick="changeText();"></textarea>
Unfortunately, you can't add markup inside a textarea, but here is an idea you could take as a starting approach, it comes from this link. The approach will be based on this:
The basic idea is to carefully position a <div> behind the <textarea>. Then JavaScript will be used to copy any text entered into the <textarea> to the <div>. A bit more JavaScript will make that both elements scroll as one. With everything perfectly aligned, we can add markup inside the <div> to give colors to some particular words, and we going to set text color to transparent on the <textarea>, completing the illusion.
Base Implementation:
// Initialization.
const colorMap = {"apple": "red", "market": "green", "banana": "orange"};
let textArea = document.getElementById("myTextArea");
let customArea = document.querySelector(".custom-area");
let backdrop = document.querySelector(".backdrop");
// Event listeners.
textArea.addEventListener("input", function()
{
customArea.innerHTML = applyColors(textArea.value);
});
textArea.addEventListener("scroll", function()
{
backdrop.scrollTop = textArea.scrollTop;
});
function applyColors(text)
{
let re = new RegExp(Object.keys(colorMap).join("|"), "gi");
return text.replace(re, function(m)
{
let c = colorMap[m.toLowerCase()];
return `<spam style="color:${c}">${m}</spam>`;
});
}
.backdrop, #myTextArea {
font: 12px 'Open Sans', sans-serif;
letter-spacing: 1px;
width: 300px;
height: 100px;
}
#myTextArea {
margin: 0;
position: absolute;
border-radius: 0;
background-color: transparent;
color: transparent;
caret-color: #555555;
z-index: 2;
resize: none;
}
.backdrop {
position: absolute;
z-index: 1;
border: 2px solid transparent;
overflow: auto;
pointer-events: none;
}
.custom-area {
white-space: pre-wrap;
word-wrap: break-word;
}
<div class="container">
<div class="backdrop">
<div class="custom-area">
<!-- Cloned text with colors will go here -->
</div>
</div>
<textarea id="myTextArea"></textarea>
</div>
Note this is just a base approach to understand the underlying idea. But with some work on it, maybe you can get a generalized version. For example, by now, the textarea can't be resizable. But maybe you can detect that event and rezise the backdrop dinamically.
You can style the text in the textarea as a whole, but since a textarea does not have sub-elements such as or you cannot give separate text within that textarea separate styles.
on the other hand if you had a separate div displaying a copy of the text you could in the innerHTML of the div assign
apple
to replace the word apple in the .. but the text in the textarea would remain unchanged.. possibly overlay div on top of the textarea but hidden until text is entered in the textarea. Not certain of the precise code to do that piece or if it would work. but at least it is a viable logic chain that I hope may help you find a solution.
To color a specific word from that text you must wrap that word with a html tag. But textarea doesn't support html tag.
You can do it outside of the textarea field.

JS Hover Over One Item to Make Another Move

I've got a simple text button with an image of an arrow next to it. I'm wanting the arrow image to move when someone hovers over the button.
I currently have this working in one instance with JS 'document.getElementById...', but I have several buttons across my site that I'd like to have the same behavior. My first thought would be to use a class instead of an id, and use the same functions.
For whatever reason, document.getElementsByClassName doesn't work - even in one instance.
Here's a simpler version to demonstrate - View on Codepen: https://codepen.io/sdorr/pen/JxYNpg
HTML
<HTML>
hover over me
<div id="block"></div>
hover over me
<div class="block"></div>
CSS
* {
margin: 0;
padding: 0;
}
.button {
color: #000000;
text-decoration: none;
background-color: cyan;
margin: 0;
display: block;
width: 300px;
padding: 20px;
text-align: center;
}
#block {
width: 30px;
height: 30px;
background-color: red;
}
.block {
width: 30px;
height: 30px;
background-color: green;
}
JS
function move() {
document.getElementById("block").style.marginLeft = "35px";
}
function moveBack() {
document.getElementById("block").style.marginLeft = "0px";
}
function moveAlt() {
document.getElementsByClassName("block").style.marginLeft =
"35px";
}
function moveBackAlt() {
document.getElementsByClassName("block").style.marginLeft =
"0px";
}
First off, why isn't the behavior with a class working but an id works fine?
Secondly, would a class solve this issue and be scalable across all buttons with the same two functions (onmouseover / onmouseout)?
If not, any ideas on a solution? I currently have a solution I found using jQuery that does work, but when hovering over one button, all arrow images move across the site. I don't necessarily mind this behavior because only one button is really in view at a time - but I'm trying to learn JS and solve problems with my own solutions!
I greatly appreciate your desire to learn on your own and not rely on premade solutions. Keep that spirit and you will go places!
When it comes to getElementsById, we know this should work for one element, since the function returns a single Element.
However, what does getElementsByClassName return?
(see: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName)
It returns an HTMLCollection which you can iterate over to change an single element's style.
So, to get this to work with JavaScript you need to write a function that will be able to identify the particular div.block you want to move. But, this puts you back to where you started, needing some particular identifier, like an id or a dataset value to pass to the function.
Alternately, based on the HTML structure you provide, you could look for nextElementSibling on the a that get's clicked. But I would set up an eventListener rather than adding a JS function as a value to the onmouseenter property.
const btns = document.getElementsByTagName('a');
/*** UPDATE forEach is a NodeList method, and will fail on HTMLCollection ***/
/* this fails -> Sorry! ~~btns.forEach(button=>{~~
/* the following will work
/**********/
for (let i = 0; i < btns.length; i++){
btns[i].addEventListener('mouseenter', function(e) {
//we pass e to the function to get the event and to be able to access this
const block = this.nextElementSibling;
block.style.marginLeft = "35px";
})
btns[i].addEventListener('mouseleave', function(e) {
const block = this.nextElementSibling;
block.style.marginLeft = "0";
})
}
But with siblings, there is a CSS-only solution.
We can use the Adjacent Sibling Selector combined with the :hover state selector and no JavaScript is needed, if we are just moving back and forth.
.button:hover+.block {
margin-left: 35px;
}
See the Snipped Below
* {
margin: 0;
padding: 0;
}
.button {
color: #000000;
text-decoration: none;
background-color: cyan;
margin: 0;
display: block;
width: 300px;
padding: 20px;
text-align: center;
}
.block {
width: 30px;
height: 30px;
background-color: green;
}
.button:hover+.block {
margin-left: 35px;
}
hover over me
<div class="block"></div>
hover over me
<div class="block"></div>
As Vecta mentioned, getElementsByClassName returns an array-like. You'll need to do something like this to get the first element:
function moveAlt() {
document.getElementsByClassName("block")[0].style.marginLeft = "35px";
}
function moveBackAlt() {
document.getElementsByClassName("block")[0].style.marginLeft = "0px";
}
However a better solution might be to use document.querySelector, which operates similarly to jQuery's $() syntax:
function moveAlt() {
document.querySelector(".block").style.marginLeft = "35px";
}
function moveBackAlt() {
document.querySelector(".block").style.marginLeft = "0px";
}

HTML/CSS/Javascript delete button

I have a list of items inside a div that is determined by the contents of two arrays.
product_codes=[code1, code2, code3];
quantities=[1, 34, 67,];
Every time a new code and quantity is added to its respective array, I have a javascript function that does this:
document.getElementById('cart_body').innerHTML='';
cart_text='';
elf='<br class="none"/>';
for(i=0; i<product_codes.length; i++){
cart_text+=(product_codes[i]+" (x"+quantities[i]+")"+elf);
}
document.getElementById('cart_body').innerHTML=cart_text;
and acts upon This HTML:
<div id='cart_body'></div>
with this CSS:
.none{margin-top: 0px;}
(the CSS simply overrides another styling I gave to ALL tags)
What I want to do, is at the end of each line added to cart_text (before the inserted line break), is to add a small circular button with an x in the center (I imagine that there's something like that in Bootstrap, but I am unable to use it or any other libraries) that when clicked, deletes the text next to it ON THAT LINE ONLY (the product code and quantity) from the div, AND deletes the two items(product code and quantity) from their respective arrays. Ideally, the aforementioned delete button would look something like the button that lets you delete a your comment that you've posted(here on Stack Overflow).
Please only Vanilla CSS and Javascript answers only. No libraries, please.
If it's not too much to ask, a working JsFiddle would be great too.
Thanks!
Edit
Attempt at the button: #1
#close_button{
border: 1px solid black;
padding-top: 0;
max-width: 15px;
max-height: 15px;
background-color: lightBlue;
border-radius: 90px;
font-size: 14px;
text-align: center;
}
<div id='close_button'>x</div>
This does not work because I cannot get a proper size with the x in the exact center of the circle. I tried padding, all that good stuff, but to no avail.
You can use the following code at https://jsfiddle.net/osha90/krrhvdmj/
<div id='cart_body'>
<p>
code1 x1 <span style="display:inline-block;width:30;height:30;background-color:#d2d2d2; border-radius: 50%;font-size:12px;line-height:18px;">X</span>
</p>
var product_codes=["code1", "code2", "code3"];
var quantities=[1, 34, 67,];
document.getElementById('cart_body').innerHTML='';
for(i=0; i<product_codes.length; i++){
var p = document.createElement("p");
p.appendChild(document.createTextNode(product_codes[i] +" X "+quantities[i]));
var span = document.createElement("span");
span.appendChild(document.createTextNode("X"));
span.classList.add("delete");
var a = document.createAttribute("data-productCode");
a.value = product_codes[i];
span.setAttributeNode(a);
p.appendChild(span);
span.addEventListener("click",removeElm);
document.getElementById('cart_body').appendChild(p);
}
function removeElm(){
var div = this.parentNode.parentNode;
for(i=0; i<product_codes.length; i++){
if(product_codes[i] == this.getAttribute("data-productCode"))
{product_codes.splice(i,1);
quantities.splice(i,1);
console.log(product_codes);
console.log(quantities);
break;
}
}
div.removeChild(this.parentNode);
}
css Code
.delete{
display: inline-block;
width: 19px;
height: 18px;
text-align: center;
background-color: #D2D2D2;
border-radius: 50%;
font-size: 12px;
line-height: 18px;
cursor: pointer;
}

I need these buttons to control which div is showing or "on top"

I have these buttons on the side of my page, and a main content area taking up the better part of the page.
What I am trying to do is get the button I click to change the main content to a div containing the corresponding information. This is very hard to find, perhaps because I am searching by the wrong terms, and I have covered a good portion of stackoverflow without much luck.
I have though about absolutely positioning the divs and using a script to change the z-index of the the divs to the highest amount using a "=+1" type situation, but I could see that getting messy.
I have considered adapting a script I have that replaces part of an image file name in order to change a main picture on a page to a larger version of the image corresponding to a thumb name, though this script targets file names so it isn't going well.
I have also tried something along the lines of:
"id of button" onclick function = "main content class" change id to "corresponding div"
only in javascript talk, and this isn't working at all so I can only assume that I am either looking at it wrong or I have some messed up in the code.
$('#tabhead1').click(function() {
document.getElementByClassName("maintab").id = "tabs1";
});
This is driving me crazy and I would really appreciate some ideas. I tried to leave it free formed so that noone gets hung up on anyone solution.
**** Just to clarify, I have 5 divs id'd at #tabhead1, #tabhead2, #tabhead3, etc. and 5 content divs classed as .maintab, and id'd as tabs1, tabs2, tabs3, etc. I need the first content div to show automatically, and for that div to change based on the button clicked. at the moment all content divs are set to display: none; except the first one.
For each button, add a data attribute related to the corresponding <div>
for example
<button id="tabhead1" data-content="tabs1" >first Tab</button>
apply a common class for the tabs, for example .tab
Then you can do the following
$('button').click(function(){
var contentId = $(this).data('content'); // get the id of corresponding tab
$('.tab').hide(); // hide all tabs
$('#'+contentId).show(); //show the corresponding tab
});
You are using getElementbyClassName which does not exists. Use:
document.getElementsByClassName("maintab")[0].id = "tabs1";
// Get all elements to match classname + get first element from array
And for the rest, I don't know why you want to add id with JS? Why not just add them to your HTML?
Try this
$('#tabhead1').click(function() {
// get element with class 'maintab' and replace its content with that of another tab
$(".maintab").html($(".tabs1").html());
});
To expand a little on the demo I posted in the comments earlier:
This uses a method very similar to #tilwin-joy, so I guess we were of like mindedness. There are a couple of small differences that I would point out:
jQuery:
$('button').on('click', function () {
var button = $(this);
var target = button.data('target');
button.prop('disabled', true).siblings().prop('disabled', false);
$(target).show('slow').siblings().hide();
});
This uses siblings to hide the other content (one less pass at the DOM).
I suggest just setting your data value with the id hash in the markup, I think it's a bit clearer to read and follow (IMHO) in both the script and markup.
This script also sets the current button to be disabled when clicked. The benefit of this is that you can use the disabled property to style up your buttons, and even if you don't style them it gives a visual cue to the user as to which tab content is currently displayed. Check out the demo to see how this can be used for styling purposes.
HTML: (I stripped some of the unneeded ids from what you described as your markup).
<div class="tabhead">
<button data-target="#tabs1" disabled="true">Content 1</button>
<button data-target="#tabs2">Content 2</button>
<button data-target="#tabs3">Content 3</button>
<button data-target="#tabs4">Content 4</button>
<button data-target="#tabs5">Content 5</button>
</div>
<div class="maintab">
<div id="tabs1">
<img src="http://placehold.it/350/e8117f/fff&text=Image+1" alt="Image 1" />
<p>This is the content of tabs1.</p>
</div>
<div id="tabs2">
<img src="http://placehold.it/350/9acd32/fff&text=Image+2" alt="Image 2" />
<p>This is the content of tabs2.</p>
</div>
<div id="tabs3">
<img src="http://placehold.it/350/9400d3/fff&text=Image+3" alt="Image 3" />
<p>This is the content of tabs3.</p>
</div>
<div id="tabs4">
<img src="http://placehold.it/350/ffd700/fff&text=Image+4" alt="Image 4" />
<p>This is the content of tabs4.</p>
</div>
<div id="tabs5">
<img src="http://placehold.it/350/1e90ff/fff&text=Image+5" alt="Image 5" />
<p>This is the content of tabs5.</p>
</div>
</div>
CSS: Not needed - just to give you an idea of how you can style the elements to look like tabs.
/*This sets all but the first tab to hidden when the page is loaded*/
.maintab>div:not(:first-child) {
display: none;
}
/*The rest is just to style the elements to look like tabs*/
body {
background-color: #eaeaea;
}
.maintab, .tabhead {
text-align: center;
margin:0 20px;
font-family: sans-serif;
}
.maintab {
border: 1px solid #1e90ff;
border-top: none;
padding-top: 20px;
background-color: #fff;
}
.tabhead {
border-bottom: 1px solid #1e90ff;
position: relative;
margin-top: 20px;
}
button {
background-color: #ccc;
padding: 10px;
border: 1px solid #999;
border-bottom: none;
-webkit-border-top-left-radius: 4px;
-webkit-border-top-right-radius: 4px;
-moz-border-radius-topleft: 4px;
-moz-border-radius-topright: 4px;
border-top-left-radius: 4px;
border-top-right-radius: 4px;
color: #999;
font-size: 14px;
cursor: pointer;
position: relative;
top: 2px;
}
button:disabled {
background-color: #fff;
border-color: #1e90ff;
color: #1e90ff;
top: 3px;
padding-top: 11px;
cursor: not-allowed;
z-index: 10;
}

Categories