How do I get my function to find my input arguments? - javascript

I am creating a function that would format my input text using predefined styles.
const icons = {
user: {'icon_cod': '%c  %c', 'font_icon': 'font-family:"Font Awesome 5 Free"; font-weight: 900;'} // declare my icon
}
const txt_styles = {
texto: {'style': 'color:red; font-family: "Open Sans"; font-weight: 700; font-size: 15px;', // Format my text and icon
'icon_style': 'color:blue;'}
}
function icon_construct(icon_chosen,text,style) {
txt_formatted = ''
if (icon_chosen in icons && style in txt_styles) { // Check the input
txt_formatted = icons.icon_chosen['icon_cod'] + text, icons.icon_chosen['font_icon'] + txt_styles.style['icon_style'], txt_styles.style['style']
} return txt_formatted // Returns formatted text
}
console.log(icon_construct('user','Hello World','body'));
However the exit is returns this error to me:
The expected output would be this
To exemplify how formatting happens
//Run in the browser console
console.log ('%c Red %c Blue','color: red; ','color: blue; ')
The styles follow the order in which the elements were declared
Function does not find the value of the argument

Try this (Note that snippet cannot print design to console, take a look at the devtools to see the result):
const
icons = {
user: {
iconCode: '%c  %c',
fontIcon: 'font-family: "Font Awesome 5 Free"; font-weight: 900;'
}
},
textStyles = {
text: {
style: 'color: red; font-family: "Open Sans"; font-weight: 700; font-size: 15px;',
iconStyle: 'color: blue;'
}
},
iconConstruct = (iconChosen, text, style) =>
iconChosen in icons && style in textStyles ? [
icons[iconChosen].iconCode + text,
icons[iconChosen].fontIcon + textStyles[style].iconStyle,
textStyles[style].style
] : [];
console.log(...iconConstruct('user', 'Hello World', 'text'));

There is no prop named icon_chosen. You need the square bracket syntax here: txt_formatted = icons.icon_chosen.

It is easy to understand like this, assume you have an object as given:
obj = { 1:{'color':'black','height':'20px'}
2:{'color':'white','height':'60px'}
}
So if you want access the color property it can be done by
obj[1].color
in your case:
icons[icon_chosen].icon_cod

there is no prop icon_chosen for icon
here icon_chosen contain value user
so by using icon[icon_chosen] you will have user object value.
try below function
function icon_construct(icon_chosen,text,style) {
if ( icons.hasOwnProperty(icon_chosen) && txt_styles.hasOwnProperty(style)) { // Check the input
console.log(icons[icon_chosen]['icon_cod'] + text, icons[icon_chosen]['font_icon'] + txt_styles[style]['icon_style'], txt_styles[style]['style'])
}
}
working example (user icon missing - i guess for css is missing in my local )

Related

How to condense 3 IF loops with the toggle() method in Vanilla Javascript?

I have created this lightbulb exercise that toggles the SRC of the lightbulb, the background color, as well as the color of the text. As an extra challenge, I'm trying to see if I can condense my code using the toggle() method as I have 3 separate functions. Does anyone know if this is possible and how I could accomplish this?
<h1 class="title-text" id="title-text">Click the lightbulb to turn it on or off!</h1>
<img id="lightbulb" onclick="toggleLight();toggleColor();toggleText()" src="/personal-projects/pic_bulbon1.gif">
<script>
let lightbulb = document.getElementById("lightbulb");
let titleText = document.getElementById("title-text");
function toggleLight() {
if (lightbulb.src.match("bulbon1")) {
lightbulb.src = "/personal-projects/pic_bulboff1.gif"
} else {
lightbulb.src = "/personal-projects/pic_bulbon1.gif"
}
}
function toggleColor() {
if (lightbulb.src.match("bulboff1")) {
document.body.style.background = "black";
} else {
document.body.style.background = "#FEDD00";
}
}
function toggleText() {
if (lightbulb.src.match("bulboff1")) {
titleText.style.color = "white";
} else {
titleText.style.color = "black";
}
}
</script>
</body>
</html>
The If loops work fine. I just want to know how I could use toggle if its possible. All the tutorials I find for this type of thing involve jquery.
Using toggle method
You want to first create a class for toggling in your css. Each element you want to toggle should have a default state and a toggled state. Toggling will add/remove a single class.
See snippet below
Snippet
const LightBulb = document.getElementById("lightbulb");
const toggleLight = () => {
LightBulb.classList.toggle("lightBulbOn");
document.body.classList.toggle("bodyLightOn");
};
body {
background-color: black;
}
body,
body .title-text {
color: white;
}
body.bodyLightOn {
background-color: #fedd00;
}
body.bodyLightOn .title-text {
color: black;
}
#lightbulb::before {
content: url("https://upload.wikimedia.org/wikipedia/commons/thumb/b/b4/Gluehlampe_01_KMJ.png/340px-Gluehlampe_01_KMJ.png");
}
.lightBulbOn::before {
content: url("https://cdn.mos.cms.futurecdn.net/HaPnm6P7TZhPQGGUxtDjAg-320-80.jpg") !important;
}
<h1 class="title-text" id="title-text">Click the lightbulb to turn it on or off!</h1>
<div id="lightbulb" class="" onclick="toggleLight();">
</div>
Codepen

Implement live markdown rendering using slate.js

I'm writing a markdown text editor using slate.js. I'm trying to implement the following live-rendering effect (from Typora):
As you can see,
When I'm typing, the text is turning to bold automatically.
When I hit the space key, the four asterisks disappeared, only the text itself is visible.
When I focus the cursor back to the text, the asterisks shows up again (so I can modify them).
I've already implemented the first item thanks to the example of MarkdownPreview, here is the code of it (take from the slate repository):
import Prism from 'prismjs'
import React, { useCallback, useMemo } from 'react'
import { Slate, Editable, withReact } from 'slate-react'
import { Text, createEditor, Descendant } from 'slate'
import { withHistory } from 'slate-history'
import { css } from '#emotion/css'
// eslint-disable-next-line
;Prism.languages.markdown=Prism.languages.extend("markup",{}),Prism.languages.insertBefore("markdown","prolog",{blockquote:{pattern:/^>(?:[\t ]*>)*/m,alias:"punctuation"},code:[{pattern:/^(?: {4}|\t).+/m,alias:"keyword"},{pattern:/``.+?``|`[^`\n]+`/,alias:"keyword"}],title:[{pattern:/\w+.*(?:\r?\n|\r)(?:==+|--+)/,alias:"important",inside:{punctuation:/==+$|--+$/}},{pattern:/(^\s*)#+.+/m,lookbehind:!0,alias:"important",inside:{punctuation:/^#+|#+$/}}],hr:{pattern:/(^\s*)([*-])([\t ]*\2){2,}(?=\s*$)/m,lookbehind:!0,alias:"punctuation"},list:{pattern:/(^\s*)(?:[*+-]|\d+\.)(?=[\t ].)/m,lookbehind:!0,alias:"punctuation"},"url-reference":{pattern:/!?\[[^\]]+\]:[\t ]+(?:\S+|<(?:\\.|[^>\\])+>)(?:[\t ]+(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\)))?/,inside:{variable:{pattern:/^(!?\[)[^\]]+/,lookbehind:!0},string:/(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\))$/,punctuation:/^[\[\]!:]|[<>]/},alias:"url"},bold:{pattern:/(^|[^\\])(\*\*|__)(?:(?:\r?\n|\r)(?!\r?\n|\r)|.)+?\2/,lookbehind:!0,inside:{punctuation:/^\*\*|^__|\*\*$|__$/}},italic:{pattern:/(^|[^\\])([*_])(?:(?:\r?\n|\r)(?!\r?\n|\r)|.)+?\2/,lookbehind:!0,inside:{punctuation:/^[*_]|[*_]$/}},url:{pattern:/!?\[[^\]]+\](?:\([^\s)]+(?:[\t ]+"(?:\\.|[^"\\])*")?\)| ?\[[^\]\n]*\])/,inside:{variable:{pattern:/(!?\[)[^\]]+(?=\]$)/,lookbehind:!0},string:{pattern:/"(?:\\.|[^"\\])*"(?=\)$)/}}}}),Prism.languages.markdown.bold.inside.url=Prism.util.clone(Prism.languages.markdown.url),Prism.languages.markdown.italic.inside.url=Prism.util.clone(Prism.languages.markdown.url),Prism.languages.markdown.bold.inside.italic=Prism.util.clone(Prism.languages.markdown.italic),Prism.languages.markdown.italic.inside.bold=Prism.util.clone(Prism.languages.markdown.bold); // prettier-ignore
const MarkdownPreviewExample = () => {
const renderLeaf = useCallback(props => <Leaf {...props} />, [])
const editor = useMemo(() => withHistory(withReact(createEditor())), [])
const decorate = useCallback(([node, path]) => {
const ranges = []
if (!Text.isText(node)) {
return ranges
}
const getLength = token => {
if (typeof token === 'string') {
return token.length
} else if (typeof token.content === 'string') {
return token.content.length
} else {
return token.content.reduce((l, t) => l + getLength(t), 0)
}
}
const tokens = Prism.tokenize(node.text, Prism.languages.markdown)
let start = 0
for (const token of tokens) {
const length = getLength(token)
const end = start + length
if (typeof token !== 'string') {
ranges.push({
[token.type]: true,
anchor: { path, offset: start },
focus: { path, offset: end },
})
}
start = end
}
return ranges
}, [])
return (
<Slate editor={editor} value={initialValue}>
<Editable
decorate={decorate}
renderLeaf={renderLeaf}
placeholder="Write some markdown..."
/>
</Slate>
)
}
const Leaf = ({ attributes, children, leaf }) => {
return (
<span
{...attributes}
className={css`
font-weight: ${leaf.bold && 'bold'};
font-style: ${leaf.italic && 'italic'};
text-decoration: ${leaf.underlined && 'underline'};
${leaf.title &&
css`
display: inline-block;
font-weight: bold;
font-size: 20px;
margin: 20px 0 10px 0;
`}
${leaf.list &&
css`
padding-left: 10px;
font-size: 20px;
line-height: 10px;
`}
${leaf.hr &&
css`
display: block;
text-align: center;
border-bottom: 2px solid #ddd;
`}
${leaf.blockquote &&
css`
display: inline-block;
border-left: 2px solid #ddd;
padding-left: 10px;
color: #aaa;
font-style: italic;
`}
${leaf.code &&
css`
font-family: monospace;
background-color: #eee;
padding: 3px;
`}
`}
>
{children}
</span>
)
}
const initialValue: Descendant[] = [
{
type: 'paragraph',
children: [
{
text:
'Slate is flexible enough to add **decorations** that can format text based on its content. For example, this editor has **Markdown** preview decorations on it, to make it _dead_ simple to make an editor with built-in Markdown previewing.',
},
],
},
{
type: 'paragraph',
children: [{ text: '## Try it out!' }],
},
{
type: 'paragraph',
children: [{ text: 'Try it out for yourself!' }],
},
]
export default MarkdownPreviewExample
My question is, how can I implement the second and third items? I've been thinking about it for a long time, but didn't find any good way to achieve them.
The good news:
The original text is saved unharmed (somewhere in your application)
Slate.js is rendering a new element for each style. thanks to the live demonstration link you've posted it is clear that the DOM is saving the state of your markdown (which suggest that we can add manipulations on-top of slate if required)
The bad news:
Implementing an editor is a headache. Using an existing one is not always as intuitive and easy as we expected. That's why I love the Monaco editor project so much (a free editable editor that gives me the experience of VS code for free? yes please!)
What we can do?
the easy way:
Use Monaco editor in our project. From my experience - it is better in terms of coding and formatting technical texts (and maybe this is the engine behind VS code)
The not-so-easy way:
We can make a simpler implementation - a panel with the raw text and another panel for preview (by the way - this is exactly what happens when you edit markdown files in VS code anyways). That way we can always render the view to reflect our most recent changes. For starters - you can use this project to do it and add tweaks to it so suit your demands
The hard way:
Using slate.js commands (read this doc for the general concept + useful examples). This approach will let slate handle the load but requires you to deep-dive into that project as well. Note that you can register custom commands and queries to suit your need without breaking your work pipeline (read this)
The insane way:
Try to override slate by using custom events on-top of rendered elements. This can be tricky but achievable if you love to play with projects internals and inject values on the fly. Not very recommended though
My Recommendation
Create a custom command that will apply the markdown style you want (for instance: bold)
Use slate handler for tracking the space key hit and use your command
function onKeyDown(event, editor, next) {
if (event.key == 'Enter') {
// TODO: add markdown style
editor.applyMarkdownBold() // applyMarkdownBold is a made-up name for your custom command
} else {
return next()
}
}
I know - this example will apply bold style to all text but - if you combine it with a range selection you will get the style you need for the relevant area in you editor (again - docs for the rescue)
From this point - applying a specific selection via key press or adding the markdown characters by clicking it (using an event + query + command) is only a matter of time

Approaches for Styling Individual Letters in a Web Component

Let's say I want to create a custom element which bolds every other character. For example, <staggered-bold>Hello</staggered-bold> would become "Hello, where the H, l, and o are all bolded.
There's no nth-letter CSS selector, so as far as I know the only way to achieve this effect is to wrap each individual character with a span programmatically. To do that, I have an implementation that clones the text content into the Shadow Dom, so that the child content as specified by the user is not changed.
Unfortunately, by doing so, something like <staggered-bold><span class="red">red</span></staggered-bold> no longer works, because by cloning the content into the Shadow Dom, the class CSS declarations for the wrapped span no longer apply.
Here's a proof-of-concept implementation, showcasing that the red and blue text are in fact not red and blue:
customElements.define('staggered-bold', class extends HTMLElement {
constructor() {
super()
this
.attachShadow({ mode: 'open' })
.appendChild(document.getElementById('staggered-bold').content.cloneNode(true))
}
connectedCallback() {
// this is a shadow dom element
const text = this.shadowRoot.getElementById('text')
this.shadowRoot.querySelector('slot').assignedNodes().forEach(node => {
const content = node.textContent.split('').map((char) => {
return `<span class="char">${char}</span>`
}).join('')
const newNode = node.nodeType === Node.TEXT_NODE ? document.createElement('span') : node.cloneNode(true)
newNode.innerHTML = content
text.appendChild(newNode)
})
}
})
.red { color: red; }
.blue { color: blue; }
<p><staggered-bold>Some text</staggered-bold></p>
<p><staggered-bold><span class="red">Red</span> <span class="blue">Blue</span></staggered-bold></p>
<template id="staggered-bold">
<style>
.hide { display: none; }
.char:nth-child(odd) {
font-weight: bold;
}
</style>
<span class="hide"><slot></slot></span>
<span id="text"></span>
</template>
My question is this: what is a good approach to styling each character in a custom element while preserving characteristics provided in the light dom?
One approach I've considered is to manipulate the light dom directly, but I have been avoiding that since I think of the light dom as being in full control of the usage-site (ie. things get complicated very quickly if external JS is manipulating the child of staggered-bold). I'm open to being convinced otherwise, especially there's no real alternative.
I've also considered cloning the content into a named slot so that the original text is preserved, and yet the content continues to live in the light dom. However, I feel like this is still kind of icky for the same reason as the previous paragraph.
You can't have the cake and eat it
Global CSS does NOT style shadowDOM (unless you use CSS properties)
Easier to not use shadowDOM at all.
With an extra safeguard: store the state so the element is properly redrawn on DOM moves.
Note: The setTimeout is always required,
because the connectedCallback fires early on the opening tag;
there is no parsed (innerHTML) DOM yet at that time.
So you have to wait for that DOM to be there.
If you do need a TEMPLATE and shadowDOM, dump the whole .innerHTML to the shadowRoot; but Global CSS still won't style it. Or <slot> it.
Do read: ::slotted CSS selector for nested children in shadowDOM slot
If you go with <slot> consider the slotchange Event
but be aware for an endless loop; changing lightDOM will trigger the slotchange Event again
<staggered-bold>Some text</staggered-bold>
<staggered-bold><span class="red">Red</span> <span class="blue">Blue</span></staggered-bold>
<style>
staggered-bold { display: block; font: 21px Arial }
staggered-bold .char:nth-child(even) { color: blue }
staggered-bold .char:nth-child(odd) { color: red; font-weight: bold }
</style>
<script>
customElements.define('staggered-bold', class extends HTMLElement {
connectedCallback() {
setTimeout(() => { // make sure innerHTML is all parsed
if (this.saved) this.innerHTML = this.saved;
else this.saved = this.innerHTML;
this.stagger();
})
}
stagger(node=this) {
if (node.children.length) {
[...node.children].forEach( n => this.stagger(n) )
} else {
node.innerHTML = node.textContent
.split('')
.map(ch => `<span class="char">${ch}</span>`)
.join('');
}
}
})
document.body.append(document.querySelector("staggered-bold"));//move in DOM
</script>
In the end I attempted a strategy I'm calling the mirror node. The idea is the custom element actually creates an adjacent node within which the split characters are placed.
The original node remains exactly as specified by the user, but is hidden from view
The mirror node actually displays the staggered bold text
The below implementation is incomplete, but gets the idea across:
class StaggeredBoldMirror extends HTMLElement {
constructor() {
super()
}
}
customElements.define('staggered-bold', class extends HTMLElement {
constructor() {
super()
this
.attachShadow({ mode: 'open' })
.appendChild(document.getElementById('staggered-bold').content.cloneNode(true))
}
connectedCallback() {
setTimeout(() => {
const mirror = new StaggeredBoldMirror()
mirror.innerHTML = this.divideIntoCharacters()
this.parentNode.insertBefore(mirror, this)
})
}
divideIntoCharacters = (node = this) => {
return [...node.childNodes].map(n => {
if (n.nodeType === Node.TEXT_NODE) {
return n.textContent
.split('')
.map(ch => `<span class="char">${ch}</span>`)
.join('')
} else {
const nn = n.cloneNode(false)
nn.innerHTML = this.divideIntoCharacters(n)
return nn.outerHTML
}
}).join('')
}
})
customElements.define('staggered-bold-mirror', StaggeredBoldMirror)
.red {
color: red;
}
.blue {
color: blue;
}
staggered-bold-mirror .char:nth-child(odd) {
font-weight: bold;
}
<p><staggered-bold>Some text</staggered-bold></p>
<p><staggered-bold><span class="red">Red</span> <span class="blue">Blue</span></staggered-bold></p>
<template id="staggered-bold">
<style>
.hide { display: none; }
</style>
<span class="hide"><slot></slot></span>
</template>
The vanilla component can be outfitted with a slotchange listener in order to rebuild its mirror whenever its inner content changes. The disconnectedCallback method can also ensure that when one node is removed, the other is too.
Of course, there are downsides to this approach, such has potentially having to also mirror events and the fact that it still manipulates the light dom.
Depending on the use case, either this or Danny's answer works.

Disable visual effects of a CSS class

On a site a CSS class is periodically added to an element by JavaScript.
I'd like not to show the visible effect of that class. In other words what I need is an effect similar to switching the class off in the development console of the browser. Let the class exist but without any consequences.
I understand that I can catch events and remove the class when it appears.
But maybe there is just a more simple way in my case?
In other words: there is a CSS class, I would like it to be present but without any visual effects. If it is impossible, that will also be an answer.
You could use something like this. Access the document's stylesheets and apply some sort of regex matching to figure out which rules are associated with the class in question. Then simply unset the styling on the rules. Note that just because the class name is found in the stylesheet rule doesn't mean it is the element being affected by the styles...but this should get you going in the right direction.
function removeClassStyling(clazz) {
var classRegex = new RegExp('\\.'+clazz.toLowerCase()+'\\b','i')
for (var s=0; s<document.styleSheets.length; ++s) {
var sheet = document.styleSheets[s];
for(var r=0; r<sheet.cssRules.length; ++r) {
var rule = sheet.cssRules[r];
if(rule.selectorText && rule.selectorText.match(classRegex)) {
var properties = Object.keys(rule.style);
for(var p=0; p<properties.length; ++p){
if(rule.style[properties[p]]) rule.style[properties[p]] = "";
}
console.log('removed styling for "'+clazz+'"');
}
}
}
}
setTimeout(function(){ removeClassStyling('unwanted-class') }, 1500)
.unwanted-class {
border: 1px solid red;
}
<div class="unwanted-class"> Test </div>
This should do the trick in most circumstances. I imagine there are circumstances that would evade this, but I can't think of them.
Basically you need to iterate document.styleSheets collection, then iterate each rule contained within and compare the CSSStyleRule.selectorText for each rule against a regular expression.
Regular expressions can be faulty, so I've included a check against an element with the supplied class name using the Element#matches() method. That method can also provide false positives in the case where the element matches some other part of the selector, so the two together should reasonably prevent any false positives.
Once you have a list of all the CSS rules that apply to a given class, you can simply delete them all. This can be done in the same step as finding them, but I've done it separately in for example's sake.
function findClassRules(name) {
const element = document.createElement('div')
element.classList.add(name)
const regex = new RegExp(`\\\.${ name }([^\w]|$)`, 'i')
const test = {
rule: rule => {
if('cssRules' in rule) {
return test.sheet(rule)
} else if('selectorText' in rule) {
const selector = rule.selectorText
return selector.match(regex) && element.matches(selector) && rule
}
},
sheet: sheet => {
const rules = Array.from(sheet.cssRules, test.rule).filter(Boolean)
return rules.length && { sheet, rules }
}
}
return Array.from(document.styleSheets, test.sheet).filter(Boolean)
}
function processSheet({ sheet, rules }) {
rules.forEach(rule => {
if('rules' in rule) {
processSheet(rule)
} else {
sheet.deleteRule(rule)
console.log(`Removed: ${ rule.cssText }`)
}
})
}
document.getElementById('clean').addEventListener('click', event => {
findClassRules('test').forEach(processSheet)
}, false)
.test { padding: 5px }
.test2 { padding: 10px }
#media screen {
.test { margin: 15px }
}
<p class="test">Hello world!</p>
<button id="clean">Remove CSS</button>
<style type="text/css">
.test { color: red }
</style>
<style type="text/css">
.test { border: 1px solid red }
</style>
How about you comment the class in your css file

get selectors by property js

I have a css file, where I place all my styles by page.
How I can get the selectors' class/id by searching for a property in css.
For example, I want to change the text color by all pages. I need to get an array with all the selectors that have a property of "color".
How I can do this?
so fun, i have answered a similar question (but for another problem). :)
=> see = https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables
let myGroup = document.querySelector('#my-Group');
let myGroupCSS = getComputedStyle(myGroup);
Bt_change_Color.onclick = function () {
let current_Color = myGroupCSS.getPropertyValue('--color_for_group');
console.log('first color', current_Color); // #305395
myGroup.style.setProperty('--color_for_group', '#95305a');
}
#my-Group {
--color_for_group: #305395;
}
h2 {
color: var(--color_for_group);
}
h4{
color: var(--color_for_group);
}
p {
color: var(--color_for_group);
}
<div id="my-Group">
<h2>title</h2>
<h4>sub tilte</h4>
<p>paragraph</p>
</div>
<button id="Bt_change_Color"> Change Color </button>

Categories

Resources