How to console.log multiple objects? - javascript

I am creating a javascript exercise, my idea was to create a function that would give me an icon return, I am using FontAwesome for this. I managed to make it show the icon and the message but I wanted to add my predefined styles for titles, emphasis .. etc through a function but I still can't think of a form. I even tried using Swith but it only copies css as any string
function icones(ico_name, text,style ){ // Capture icon name, style to be used and text
switch(ico_name) { //Check argument icon
case 'user':
ico_name = '%c ' //Icon will only be displayed after CSS declaration
font = 'font-family: "Font Awesome 5 Free"; font-weight: 900; font-size: 20px; content: "\f434";'
break
}
switch(style) { // Styling text
case 'title':
text = 'color: red'
break
}
console.log(ico_name,font,text)
}
icones('user','player', 'title') //Applying values to function

I'm not sure if this is what you are looking for, but you can use document.getElementById() to get an element in the webpage and then apply CSS styles.
For instance, if the element whose font you are trying to change has its id attribute set to "changeMyFont":
<span id="changeMyFont"></span>
you can change its CSS attributes using JavaScript as such:
var elem = document.getElementById("changeMyFont");
elem.style.fontFamily = "Font Awesome 5 Free";
elem.style.fontWeight = 900;
elem.style.fontSize = "20px";
To change the text color to red for a certain element, you can follow the same procedure. To change the content within a HTML tag, use innerHTML (do not allow user input here; it is an XSS threat):
document.getElementById("elementToChange").innerHTML = "HTML here";
You can use an HTML escape in there.

Well after a few hours between trial and error I was able to accomplish my feat.
The "secret" was to put 2 styles in just one console.log, the code may seem like a confusing drift and surely to improve it.
function icones(ico_nome,texto,style ){ // Captura o nome do icone, o estilo que sera utilizado e o texto
switch(ico_nome) { // Check argument icon
case 'user':
ico_nome = '%c ' // Icon will only be displayed after CSS declaration
font_icon = 'font-family:"Font Awesome 5 Free"; font-weight: 900; font-size: 20px;' //Declara a fonte para visualização
break
}
switch(style) { // Styling text
case 'titulo': // Set styles for titles
font_icon += 'color:red;' //Set the color Red to Icon
style_text = 'color:blue; font-family: Arial;' // Set styles for texts
break
default:
font_icon += 'color: black' // Set default color
}
console.log(ico_nome + ' ' + '%c' + texto,font_icon,style_text) //Join the 2 styles and reveal the output
}
icones('user','Usuario', 'titulo') //Applying values to function
Final result
---- Console Output
Still do not know how to insert the image directly into the post sorry :)

Use Jquery function .css() For example:
$("#element").css("font-size", "20pt")

Related

EventListener Only Firing Once

still learning the basics of JS, working with EventListeners now. Trying to make a button that changes the color of text back and forth but I think I'm misunderstanding the nature of the method, or using it incorrectly. I don't believe it's a syntax issue.
I have the text and the button, both with Id's. I created variables for both elements. I add an event listener to the button, and defined the if else statement in the function. The "if" portion of the function executes without issue, but that's where it ends. Sorry in advance for the formatting I wasn't sure what made the most sense. Thanks!
Here's the HTML:
<h1 id="header"> Here's some text </h1>
<button id="button"> Change the Color </button>
CSS:
#header {
color: red;
}
And the JavaScript:
var header = document.getElementById("header");
var button = document.getElementById("button");
button.addEventListener("click", function() {
if (header.style.color = "red")
{header.style.color = "blue";}
else if (head.style.color = "blue")
{header.style.color = "red";
}
})
In JavaScript (and other languages) you need to use == to check for equality.
However, in JavaScript there is also ===. === is the strict equality operator, meaning it does not do type conversion. What does that mean? It means:
"5" == 5 // true, since "5" as a number is equal to 5, the literal number
"5" === 5 // false, since a string cannot equal a number
So in your if statements you should use == or === instead of just =.
Others have mentioned the use of = vs == vs === - which is definitely your problem, but you're also going to have other problems with comparing styles the way you are doing.
The style property is unique and cumbersome. You have the "style" property which is a property of the DOM node (just like href for anchors or type for inputs). Then you have styles which are applied from a stylesheet - either a <style> tag or external stylesheet file. Sometimes the two different styles sources are in conflict.
For style properties, you read the node.style.color property like you are doing. To get the actual color being applied to the node, you must use window.getComputedStyle(). Let me explain the difference by example:
const div = document.getElementById('foo')
div.style.color; //-> red
window.getComputedStyle(div).color; //-> rbg(0, 255, 0) - this is green!
#foo { color: green !important }
<div id="foo" style="color: red">Hello!</div>
Notice how we set red on the node itself, but green !important in the stylesheet. The !important will win, which is why the text is green. Furthermore, the browser converts the color name green to its RGB equivalent rgb(0, 255, 0). This can be tedious to reconcile. What I usually recommend is having multiple class names and switching between those on click:
var header = document.getElementById("header");
var button = document.getElementById("button");
button.addEventListener("click", function() {
if (header.classList.contains("red")) {
header.classList.remove("red")
header.classList.add("blue")
} else if (header.classList.contains("blue")) {
header.classList.remove("blue")
header.classList.add("red")
}
})
.red { color: red }
.blue { color: blue }
<h1 id="header" class="red"> Here's some text </h1>
<button id="button"> Change the Color </button>

Changing hover background color with javascript

I want to access the hover background color of a button to change the hover background color every time the button is clicked.
This is the button tag from the index.html file
<button class="btn-hero btn-hero:hover" id="btn">click me</button>
This is in the css file:
.btn-hero {
font-family: var(--ff-primary);
text-transform: uppercase;
background: transparent;
color: var(--clr-black);
}
.btn-hero:hover {
color: var(--clr-white);
background: var(--clr-black);
}
I can access the button background color like this:
btn.addEventListener("click", function () {
btn.style.backgroundColor = 'some_color'
});
That changes the button color but negates the hover property.
I tried doing this in the app.js:
let button_hover = document.querySelector(".btn-hero:hover")
But that returns a null.
Is there a way to do access the hover properties from the css file in app.js file?
Answer
In terms of javascript you can use mouseover event handler
Example
btn.addEventListener("mouseenter", function( event ) {
event.target.style.color = "purple";
}, false);
btn.addEventListener("mouseleave", function( event ) {
event.target.style.color = "";
}, false);
Reference
MDN : mouseover event
The snippets your posted contain a few errors in both the JS and the HTML:
HTML
<button class="btn-hero" id="btn">click me</button> should not contain :hover as this is a CSS pseudo selector (in this case connected to btn-hero) and should only be used in CSS (or referenced by Javascript). Remove the btn-hero:hover.
Javascript
If you want to 'catch' the element hover event you need to attach an eventListener (in case of hover either mouseover or mouseenter) to the button
While document.querySelector(".btn-hero:hover") is a proper selector, but due to the asynchrous nature of Javascript it would be purely accidental that the hover would be caught when the JS function runs. That is why the function returns NULL.
If you want to modify the CSS style of an element, digg into MDN: Window.getComputedStyle()
CSS
Seems okay to me.
Your question
Please make sure you understand that the hex value of a color is essentially not one long hexadecimal value, but a concatenation of 3 hex values resembling R,G,B made up of 2 hexadecimal digits each. Adding 100hex to any #xxxxxx (6 digit) color would get rather unexpected results. Which of the three (R,G,B) do you want to change?
So you want each button click to change the background a bit. I did not understand your hex point, but here is one of the scripts, that calculates background color from given numeric value. In this case its the attribute data-colorvalue
I modified it to fit your case and made it so it adds 10 each click. You can play around the math here, that way you get different colors:
// Grab the button:
const btn = document.querySelector('#btn')
// Detect on click event:
btn.onclick = e => {
// Get the buttons color value, parseInt makes sure its INT:
let color_value = parseInt(btn.getAttribute('data-colorvalue'))
// Make the R value based on color_value:
val_r = Math.round((255 * color_value) / 100)
// Make the G value based on color_value:
val_g = Math.round((255 * (100 - color_value)) / 100)
// Make the B value based on color_value:
val_b = Math.round(255 - (color_value * 1.5))
// Format and set as buttons background:
btn.style.backgroundColor = 'rgb(' + val_r + ', ' + val_g + ', ' + val_b + ')'
// Set the new color value plus 10.. you can play with this formula:
btn.setAttribute('data-colorvalue', color_value + 10)
}
<button id="btn" data-colorvalue="1">Click me</button>
If you want to change the hover as pseudo, then you need magic. And thats a completely standalone quesiton.
Your title says text color and question background, color. So if you want to change the text / font color you simply use btn.style.color instead of backgroundColor.
Psedo classes do not go to your html like so, ever:
EDIT
Based on the additional information provided in the comments, we worked out, that you want to change the hover-background-color each time the button is clicked.
This is a very strange situation and odd request. But one of the ways doing it is making new style element contents on each click like so:
// Grab the button:
const btn = document.querySelector('#btn')
// Make style element:
let style = document.createElement('style')
// Detect on click event:
btn.onclick = e => {
// Get the buttons color value, parseInt makes sure its INT:
let color_value = parseInt(btn.getAttribute('data-colorvalue'))
// Make the R value based on color_value:
val_r = Math.round((255 * color_value) / 100)
// Make the G value based on color_value:
val_g = Math.round((255 * (100 - color_value)) / 100)
// Make the B value based on color_value:
val_b = Math.round(255 - (color_value * 1.5))
// Set the new color value plus 10.. you can play with this formula:
btn.setAttribute('data-colorvalue', color_value + 10)
// Now starts the magic...
// Make the css contents for the style element:
let css = '#btn:hover{background-color:rgb(' + val_r + ', ' + val_g + ', ' + val_b + ')}'
// If style element exists already, then lets overwrite its contents:
if (style != undefined) style.innerHTML = css
// .. however if there is none, then we must append new:
else style.appendChild(document.createTextNode(css))
// Now we simply append the style element to the head:
document.getElementsByTagName('head')[0].appendChild(style)
}
<button id="btn" data-colorvalue="1">Click me</button>
You can use !important, but you may want to refactor your code by setting CSS variables with JavaScript or using mouseenter and mouseleave event handlers.
const btn = document.querySelector('#btn');
btn.style.backgroundColor = 'red'
:root {
--clr-black: black;
--clr-white: white;
}
.btn-hero {
font-family: var(--ff-primary);
text-transform: uppercase;
background: transparent;
color: var(--clr-black);
}
.btn-hero:hover {
color: var(--clr-white);
background: var(--clr-black) !important;
}
<button class="btn-hero" id="btn">click me</button>

Change Font Family Based On Other CSS Value

I am trying to change the font-family of a class (.button) based on the font-family value of h6. I realize this can't be done with CSS, but couldn't find a solution directly through JS. I wish it were as easy applying the styles in a stylesheet, but the h6 value is gerenated dynamically by the user. Any ideas?
Thanks!
This is the easiest way to do it, since you're using jQuery.
Just for demonstration, you can see that the button takes the font of the H6 element after you click the button.
If you want this to happen immediately, remove the click() function by deleting the first and last line of the JS code (first code block).
$('.my-button').click( function(){
var font = $('.my-title').css("font-family");
var weight = $('.my-title').css("font-weight");
$('.my-button').css('font-family', font);
$('.my-button').css('font-weight', weight);
});
.my-title {
font-family: "Lucida Handwriting";
font-weight: bold;
}
.my-button {
font-family: Verdana;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h6 class="my-title">Hello World</h6>
<button class="my-button">Some Button</button>
Have the potential font-family styles pre-set up in classes ahead of time and then use if/then logic to set the correct class on the element. The cornerstone of this is the element.classList property and its .add() method.
// Get references to the elements we need to work with
let h6 = document.querySelector("h6");
let btn = document.querySelector("button.button");
// Use if/then/else logic to set the button class
if(h6.classList.contains("foo")){
btn.classList.add("newFoo");
} else if(h6.classList.contains("bar")){
btn.classList.add("newBar");
} else if(h6.classList.contains("baz")) {
btn.classList.add("newBaz");
}
/* Example of what the pre-existing classes might be: */
.foo { font-family:"Comic Sans MS"; font-size:2em; margin:.5em; }
/* New styles that will be used to override: */
.newFoo { font-family:"Times New Roman"; }
.newBar { font-family:sans-serif; }
.newBaz { font-family:monospace; }
<h6 class="foo">foo</h6>
<button class="button">Click Me!</button>
Your question isn't clear enough for me, but I tried to answer you with a more general solution for your problem!
In the demo below, I've created an input as if the user will type a value there, and a button with button id, and its font-size will be changed according to the value provided from the user within the input field
var sizeInput = document.querySelector("#sizeInput")
var myBtn = document.querySelector("#button")
var sizeFromTheUser
sizeInput.addEventListener("change", function() {
// Update the variable's value based on the changed value from the user
sizeFromTheUser = sizeInput.value
// Change the font-size based on the given value
switch(sizeFromTheUser) {
case "h1":
myBtn.style.fontSize = "2em"
break;
case "h2":
myBtn.style.fontSize = "1.5em"
break;
case "h3":
myBtn.style.fontSize = "1.17em"
break;
case "h4":
myBtn.style.fontSize = "1em"
break;
case "h5":
myBtn.style.fontSize = "0.83em"
break;
case "h6":
myBtn.style.fontSize = "0.75em"
break;
}
})
<input type="text" id="sizeInput" />
<button id="button">This is text!</button>
You can apply the same to the font-family property with different Switch cases that meets your needs, or even using a different logic, but I just gave you a generic example that might be helpful in your situation!

How Can i change default font of Ckeditor?

I like to change default font of Ckeditor !
I cant do it and dont see anything about it in Docs .
I can only change the default lable of it !
Thanks
Per the docs these all seem to be defined in plugins/font/plugin.js.
{Object} CKEDITOR.config.font_style
The style definition to be used to apply the font in the text.
Defined in: plugins/font/plugin.js.
config.font_style =
{
element : 'span',
styles : { 'font-family' : '#(family)' },
overrides : [ { element : 'font', attributes : { 'face' : null } } ]
};
{String} CKEDITOR.config.fontSize_defaultLabel Since: 3.0
The text to be displayed in the Font Size combo is none of the available values matches the current cursor position or text selection.
Defined in: plugins/font/plugin.js.
config.fontSize_defaultLabel = '12px';
{String} CKEDITOR.config.fontSize_sizes Since: 3.0
The list of fonts size to be displayed in the Font Size combo in the toolbar. Entries are separated by semi-colons (;). Any kind of "CSS like" size can be used, like "12px", "2.3em", "130%", "larger" or "x-small". A display name may be optionally defined by prefixing the entries with the name and the slash character. For example, "Bigger Font/14px" will be displayed as "Bigger Font" in the list, but will be outputted as "14px".
Defined in: plugins/font/plugin.js.
config.fontSize_sizes = '16/16px;24/24px;48/48px;';
config.fontSize_sizes = '12px;2.3em;130%;larger;x-small';
config.fontSize_sizes = '12 Pixels/12px;Big/2.3em;30 Percent More/130%;Bigger/larger;Very Small/x-small';
I am not very savvy with Ckeditor, but I hope this helps!
In config.js:
config.contentsCss = '/ckeditor/fonts.css';
config.font_names = 'shabnam';
In fonts.css:
#font-face {
font-family: "shabnam";
src: url("/fonts/Shabnam.ttf") format('truetype');
}
Now, it may be all right.
if you want this font to be styled with body tag, you should add this in fonts.css:
body {
/* Font */
font-family: "shabnam";
}
In order to change toolbar style, what worked for me was this:
In
skins/moono-lisa/editor.css:
delete `font:normal normal normal 12px Arial,Helvetica,Tahoma,Verdana,Sans-Serif;` from
`.cke_reset_all,.cke_reset_all *,.cke_reset_all a,.cke_reset_all textarea`

How can I modify a CSS class using JavaScript?

I know how to apply css on a single tag (or changing class on it) but THIS IS NOT WHAT I AM ASKING!
I would like to modify an attribute within a CSS class without touching the element where the class is applied.
In other words if this is the css
.myclass {
font-size: 14px;
color: #aab5f0;
}
and this is the html
<span id="test" class="myclass"> foo bar </span>
to increase the font of the span tag I want to modify the content of the class and NOT doing something like
var fontsize = parseInt($('#test').css('font-size').replace(/[^-\d\.]/g, ''));
fontsize += 10;
$('#test').css('font-size', fontsize+'px');
I want that the class becomes
.myclass {
font-size: 18px;
color: #aab5f0;
}
Is there a way to change the actual class through Javascript?
My other solution would be to put the css in a container and refill the container each time, but I have the sensation that it is not a good idea...
I think ideally you should define a base font size on the html or body element. All of the other font sizes in your CSS should be relative to that "master" font size, like so:
Then, when you adjust the font-size of the body through jQuery.css(), the other elements will all automatically adjust their size relative to the parent.
$(body).css('font-size', '14px');
You don't have to use the body level, you could define base font-size a div or other container and use that as the parent instead.
Here is a contrived example of this in action:
$('#grow').click(function() {
$('body').css('font-size', '18px');
});
body {
font-size: 12px;
}
h3,
p {
font-size: 1.0em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Main Title</h3>
<p> Welcome to my website. </p>
<button id="grow" type="button">Grow</button>
My comment notwithstanding, look at this question: Setting CSS pseudo-class rules from JavaScript
Changing a class and "setting pseudo-class rules" are achieved in the same way.
#Box9's answer is probably the one you should actually use:
I threw together a small library for this since I do think there
are valid use cases for manipulating stylesheets in JS.
There is no need to change the class itself. To override the behaviour, simply add another class to the existing one or change it entirely. I'll show the first option:
.myclass {
font-size: 14px;
color: #aab5f0;
}
.myclass.override {
font-size: 12px;
}
And then all you need to do from javascript is to toggle the override class. This way it's also much better as all the presentation is done in CSS.
Since it's obvious you're using jQuery, please see the addClass and removeClass functions.
$('#test').removeClass('myClass').addClass('yourClass');
looking for same thing.
This was my solution
https://jsfiddle.net/sleekinteractive/0qgrz44x/2/
HTML
<p>The Ants in France stay mainly on the Plants</p>
CSS
p{
font-family:helvetica;
font-size:15px;
}
JAVASCRIPT (uses jQuery)
function overwrite_css(selector,properties){
// selector: String CSS Selector
// properties: Array of objects
var new_css = selector + '{';
for(i=0;i<properties.length;i++){
new_css += properties[i].prop + ':' + properties[i].value + ';';
}
new_css += '}';
$('body').append('<style>' + new_css + '</style>');
}
overwrite_css('p',Array({prop: 'font-size', value: '22px'}));
overwrite_css('p',Array({prop: 'font-size', value: '11px'}));
overwrite_css('p',Array({prop: 'font-size', value: '66px'}));
// ends on 66px after running all 3. comment out lines to see changes
Simply JQuery:
$('#test').attr('class','bigFont');
or native JS :
document.getElementById('test').className ='bigFont';
UPDATED
var size = [ 10 , 20 , 30 ] ;
var i =0;
$('#test').css('font-size',size[i]+'px');
i = (i+1)%size.length ;

Categories

Resources