Good day, Im creating buttons using DOM and toggle to change the paragraph in the HTML file when you click it in on in JavaScript however, the buttons are not appearing in the html and I've set it up so it sits on top of the paragraph. I have used CSS to style the buttons.
Here are the JC, HTML and CSS files:
HTML:
<!DOCTYPE html>
<head>
<link scr="stylesheet" type="text/css" href="A3 .css">
<script src="A3.js"></script>
</head>
<div id ="button_containter"></div>
<body id= target_p>
In considering any new subject, there is frequently a tendency, first, to overrate what we find to be already interesting
or remarkable; and, secondly, by a sort of natural reaction, to undervalue the blue state of the case, when we do
discover that our notions have surpassed those that were really tenable
</body>
</html>
JS:
let para = document.getElementById("target_p");
class ParagraphChanger {
constructor (p){
this.p=p;
var btnDiv = document.getElementById("button_containter");
let btnBold = this.createButton("toggle bold");
btnBold.addEventListener('click',() => this.makeBold());
btnDiv.appendChild(btnBold);
let widthBtn = this.createButton("toggle width");
widthBtn.addEventListener('click', () => this.changedWidth());
btnDiv.appendChild(widthBtn);
let clrBtn = this.createButton("togglt color");
clrBtn.addEventListener('click', () => this.changeColor());
clrBtn.appendChild(clrBtn);
let szBtn = this.createButton("toggle size");
szBtn.addEventListener('click', () => this.changeSize());
}
createButton (name){
const btn = document.createElement('button_container');
const buttonName = document.createTextNode(name);
buttonName.appendChild(buttonName);
return btn;
}
makeBold(){
// changing the size to bold, getting it from CSS s
this.p.classList.toggle("Toggle_bold");
}
changedWidth(){
this.p.classList.toggle('Toggle_width');
}
changeColor(){
this.p.classList.toggle('Toggle_width');
}
changeSize(){
this.p.classList.toggle('Toggle_size');
}
window.onload = () => {
new ParagraphChanger(document.getElementById('target_p;'));
}
};
CSS:
Toggle_bold {
font: bold;
}
.Toggle_width{
width: 50%;
}
.Toggle_width{
color: #ff2800;
}
.Toggle_size{
font-size: 100%;
}
#button_containter{
display: flex;
align-items: center;
justify-content: center;
text-align: center;
}
JS issues:
First, when you call document.createElement(), you are accidentally passing in the name of the container. Instead, you should pass in button, like so: const btn = document.createElement('button');
Next, you don't need to create a text node. btn.innerText = name will work just fine ;)
Finally, you accidentally stuck a semicolon in your new ParagraphChanger(document.getElementById('target_p;'));.
Also, you put the call to window.onload inside the class; move it outside!
CSS issues:
font: bold; won't work, you need to use font-weight: bold;
Also, you forgot a period in your Toggle_bold selector. It should be .Toggle_bold to select the class.
Here's a CodePen with your final, fixed code.
I hope this solves your problem!
Took a bit of editing as your code had a lot of issue. The container id had a typo, the button was created with button_container which is actually the ID etc. Below you can see how the button is created.
CreateElement:
In createElement we must specify the tag name not the ID itself to created new html element. Read more here.
document.createElement('button'); //p tag, h1,h2,h3 tags etc, divs
SetAttribute:
For the id we use setAttribute which Sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value.
btn.setAttribute("id", "button_content"); //Ids,classes and data-attribute
//id="myid", class="myclass", data-myid=1
InnerText:
Finally for the value, we use innerText to set text of button and call it onLoad.
btn.innerText ="Click me";
The complete code:
<!DOCTYPE html>
<html>
<head>
<title>Website Project</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<style>
Toggle_bold {
font: bold;
}
.Toggle_width{
width: 50%;
}
.Toggle_width{
color: #ff2800;
}
.Toggle_size{
font-size: 100%;
}
#button_containter{
display: flex;
align-items: center;
justify-content: center;
text-align: center;
}
</style>
</head>
<body>
<div id ="button_container"></div>
<script>
function createButton (name){
const btn = document.createElement('button'); //Add button with create Element
btn.setAttribute("id", "button_content"); //Add Id with setAttribute method
btn.innerText ="Click me";// Add value of the button with innerText property
let container = document.getElementById("button_container"); //Fetch container div
console.log(btn);
console.log(container);
container.appendChild(btn); //Append button to it.
}
function makeBold(){
// changing the size to bold, getting it from CSS s
this.p.classList.toggle("Toggle_bold");
}
function changedWidth(){
this.p.classList.toggle('Toggle_width');
}
function changeColor(){
this.p.classList.toggle('Toggle_width');
}
function changeSize(){
this.p.classList.toggle('Toggle_size');
}
window.onload = () => {
createButton();// call button function here to create the button
}
</script>
</body>
</html>
Finally, i believe we learn by doing and so i hope this was helpfull in clearing some of the confusions as well solving your problem :).
Related
I googled but couldn't get a satisfactory answer.
I am new to JS.
What I am doing is, creating a button with a number written on it and whenever the user clicks on the button, the number increments by one.
var newButton = document.createElement('Button');
newButton.id = "btn";
newButton.innerHTML = "0";
newButton.addEventListener("click", () => {
newButton.innerHTML = String(Number(newButton.innerHTML) + 1);
});
document.body.appendChild(newButton);
#btn {
width: 96px;
height: 48px;
font-size: 24px;
}
<!DOCTYPE html>
<html>
<head>
<!--Where the CSS is loaded in-->
<!--<link rel="stylesheet" href="css/button.css" type="text/css">-->
</head>
<body>
<!--Where the JS is loaded in-->
<!--<script src="js/button.js" type="text/javascript"></script>-->
</body>
</html>
Now, this does display a button and increment the number on it, but the css doesn't reflect in the displayed button.
Instead if my button.js is like this
var newButton = document.createElement('Button');
newButton.id = "btn";
newButton.className = "BtnClass";
newButton.innerHTML = "0";
newButton.addEventListener("click", ()=>{
newButton.innerHTML = String(Number(newButton.innerHTML) + 1);
});
document.body.appendChild(newButton);
And button.css styles it by class rather than id,
.BtnClass{ width: 96px;
height: 48px;
font-size: 24px;}
Then it properly displays the button in the way I want it to.
Why doesn't this happen when I style with the id name but works fine when I style by the class name?
Update - Works fine, it was probably some setting specific to the coding site I was using.
I have a div that displays a little popup menu when clicked. I want users to be able to click anywhere in the body of the site to close the popup, but when I add code for that, the popup cant be opened at all anymore.
So I tried adding an if-statement so that the closemenu() function will only try close the popup if its already open, but it seems like the statement is evaluating to false even if the popup is open.
Here is the HTML for showing the popup:
<div class="popcolor" onclick="showmenu()"> Click!
<span class="popupcolor" id="myPopup">Pop!</span>
</div>
Here is the css:
.popcolor .show {
visibility: visible;
-webkit-animation: fadeIn 0.5s;
animation: fadeIn 0.5s;
}
Here is the Javascript:
function showmenu() {
var popup = document.getElementById("myPopup");
popup.classList.toggle("show");
}
function closemenu() {
var popup = document.getElementById("myPopup");
if (popup.style.visibility == "visible") {
popup.classList.toggle("close");
};
}
Here is the HTML for closing the popup:
<body onclick="closemenu()">
I've been through every post I can find on this for solutions, and I'm still stuck. Any help is appreciated.
You can use the getComputedStyle() method on the window object, to calculate the style rules that result from the classes applied to your popup element.
This gives you a reliable way of determining the values of different styling rules that result from, say, the 'close' class being applied to popup
Something along the lines of this should work for you:
function closemenu() {
var popup = document.getElementById("myPopup");
// Get the computed style, that is the combination of styles
// resulting from your CSS classlist, etc
var computedStyle = window.getComputedStyle(popup, null);
// Get visibility value from computed styles
var visiblityValue = computedStyle.getPropertyValue("visibility")
if (visiblityValue == "visible") {
popup.classList.toggle("show"); // Correct this from "close" to "show"
};
}
There are also some other functional issues with your implementation which are causing problems. Consider updating your showmenu() method to:
function showmenu(event) {
// Prevent event propagation, which would cause closemenu to call
// after this method is called
event.stopPropagation()
var popup = document.getElementById("myPopup");
popup.classList.toggle("show");
}
For more information on getComputedStyle(), see the MDN documentation
Problem here is that click event triggered from div bubbles up to body which eventually closes the popup.
function showmenu(e) {
e.stopPropagation();
console.log('toggle');
document.getElementById("myPopup").classList.toggle("close");
}
function closemenu(e) {
e.stopPropagation();
console.log('hide');
document.getElementById("myPopup").classList.add("close");
}
#myPopup.close {
visibility: hidden;
}
body {
border: 1px solid #ccc;
padding: 2rem;
}
<body onclick="closemenu(event)">
<div class="popcolor" onclick="showmenu(event)"> Click!
<span class="popupcolor close" id="myPopup">Pop!</span>
</div>
</body>
P.S. Use event.stopPropagation() to cancel/consume event
Because the visibility property is being set at the class level, the style information isn't available in the style property of your element. Maybe instead of checking for a specific style, you can check to see if the 'show' class is currently assigned to your element like so:
function closemenu() {
var popup = document.getElementById("myPopup");
if (popup.classList.contains("show")) {
popup.classList.toggle("close");
};
}
Problem in your code is with the use of JavaScript functions.
Try this simple example I took from W3Schools and enhanced it for your case.
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_add_class
There seems to be some issue with W3CSchool TryIt Editor page. Here is the link to JSBin for the same code: https://jsbin.com/xefolinape/edit?html,output
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.mystyle {
width: 100%;
padding: 25px;
background-color: coral;
color: white;
font-size: 25px;
box-sizing: border-box;
}
</style>
</head>
<body>
<p>Click the "Try it" button to add the "mystyle" class to the DIV element:</p>
<button onclick="myFunction()">Try it</button>
<button onclick="myFunctionClose()">Close it</button>
<script>
function myFunction() {
var element = document.getElementById("myDIV");
element.classList.add("mystyle");
}
function myFunctionClose() {
var element = document.getElementById("myDIV");
element.classList.remove("mystyle");
}
</script>
</body>
</html>
Hope this helps!
How do you get and set CSS custom properties (those accessed with var(…) in the stylesheet) using JavaScript (plain or jQuery)?
Here is my unsuccessful try: clicking on the buttons changes the usual font-weight property, but not the custom --mycolor property:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<style>
body {
--mycolor: yellow;
background-color: var(--mycolor);
}
</style>
</head>
<body>
<p>Let's try to make this text bold and the background red.</p>
<button onclick="plain_js()">Plain JS</button>
<button onclick="jQuery_()">jQuery</button>
<script>
function plain_js() {
document.body.style['font-weight'] = 'bold';
document.body.style['--mycolor'] = 'red';
};
function jQuery_() {
$('body').css('font-weight', 'bold');
$('body').css('--mycolor', 'red');
}
</script>
</body>
</html>
You can use document.body.style.setProperty('--name', value);:
var bodyStyles = window.getComputedStyle(document.body);
var fooBar = bodyStyles.getPropertyValue('--foo-bar'); //get
document.body.style.setProperty('--foo-bar', newValue);//set
The native solution
The standard methods to get/set CSS3 variables are .setProperty() and .getPropertyValue().
If your Variables are Globals (declared in :root), you can use the following, for getting and setting their values.
// setter
document.documentElement.style.setProperty('--myVariable', 'blue');
// getter
document.documentElement.style.getPropertyValue('--myVariable');
However the getter will only return the value of a var, if has been set, using .setProperty().
If has been set through CSS declaration, will return undefined. Check it in this example:
let c = document.documentElement.style.getPropertyValue('--myVariable');
alert('The value of --myVariable is : ' + (c?c:'undefined'));
:root{ --myVariable : red; }
div{ background-color: var(--myVariable); }
<div>Red background set by --myVariable</div>
To avoid that unexpected behavior you have to make use of the getComputedStyle()method , before calling .getPropertyValue().
The getter will then, look like this:
getComputedStyle(document.documentElement,null).getPropertyValue('--myVariable');
In my opinion, accessing CSS variables should be more simple, fast, intuitive and natural...
My personal approach
I've implemented CSSGlobalVariablesa tiny (<3kb) javascript helper which automatically detects and packs into an Object all the active CSS global variables in a document, for easier access & manipulation.
// get the document CSS global vars
let cssVar = new CSSGlobalVariables();
// set a new value to --myVariable
cssVar.myVariable = 'red';
// get the value of --myVariable
console.log( cssVar.myVariable );
Any change applied to the Object properties, is translated automatically to the CSS variables.
Available in : https://github.com/colxi/css-global-variables
The following example illustrates how one may change the background using either JavaScript or jQuery, taking advantage of custom CSS properties known also as CSS variables (read more here). Bonus: the code also indicates how one may use a CSS variable to change the font color.
function plain_js() {
// need DOM to set --mycolor to a different color
d.body.style.setProperty('--mycolor', 'red');
// get the CSS variable ...
bodyStyles = window.getComputedStyle(document.body);
fontcolor = bodyStyles.getPropertyValue('--font-color'); //get
// ... reset body element to custom property's new value
d.body.style.color = fontcolor;
d.g("para").style["font-weight"] = "bold";
this.style.display="none";
};
function jQuery_() {
$("body").get(0).style.setProperty('--mycolor','#f3f');
$("body").css("color",fontcolor);
$("#para").css("fontWeight","bold");
$(this).css("display","none");
}
var bodyStyles = null;
var fontcolor = "";
var d = document;
d.g = d.getElementById;
d.g("red").addEventListener("click",plain_js);
d.g("pink").addEventListener("click",jQuery_);
:root {
--font-color:white;
--mycolor:yellow;
}
body {
background-color: var(--mycolor);
color:#090;
}
#para {
font: 90% Arial,Helvetica;
font-weight:normal;
}
#red {
background:red;
}
#pink {
background:#f3f;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<p id="para">Let's try to make the background red or pink and change the text to white and bold.</p>
<button id="red">Red</button>
<button id="pink">Pink</button>
Note that with jQuery, in order to set the custom property to a differnt value, this response actually holds the answer. It uses the body element's get() method which allows access to the underlying DOM structure and returns the body element, thereby facilitating the code setting the custom property --mycolor to a new value.
You can use getComputedStyle function to get css variables,Here is a example.
const colors = document.querySelectorAll(".color");
const result = document.getElementById("result");
colors.forEach((color) => color.addEventListener("click", changeColor));
function changeColor(event) {
const target = event.target;
// get color
const color = getComputedStyle(target).getPropertyValue("--clr");
document.body.style.backgroundColor = color;
// active color
colors.forEach((color) => color.classList.remove("active"));
target.classList.add("active");
result.textContent = getComputedStyle(target).getPropertyValue("--clr")
}
result.textContent = "#1dd1a1";
body{
background-color: #1dd1a1;
}
.colors{
position: absolute;
padding: 2rem;
display: flex;
gap: 1rem;
}
.color{
display: inline-block;
width: 2rem;
height: 2rem;
background-color: var(--clr);
border-radius: 50%;
cursor: pointer;
transition: $time-unit;
}
.color.active{
border: .2rem solid #333;
transform: scale(1.25);
}
<h1>Click to change Background</h1>
<section class="colors">
<span class="color active" style="--clr: #1dd1a1"></span>
<span class="color" style="--clr: #ff6b6b"></span>
<span class="color" style="--clr: #2e86de"></span>
<span class="color" style="--clr: #f368e0"></span>
<span class="color" style="--clr: #ff9f43"></span>
</section>
Current Color: <span id="result"></span>
$(document).ready(function() {
var btn = $('.gen');
btn.on('click', function() {
var areaTxt = $('.textarea').val();
var div = $('.result');
div.html(areaTxt);
});
});
.result {
border: 1px solid red;
width: 300px;
height: 150px;
}
.textarea {
width: 300px;
height: 150px;
}
<!DOCTYPE>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<title>Untitled Document</title>
</head>
<body>
<textarea class="textarea"></textarea>
<input type="button" class="gen" value="generate">
<div class="result"></div>
</body>
</html>
I've created a simple HTML code editor. The problem is that when I add style for all classes or divs affect also to my code editor.
I want something like the editor of w3school. Just to show the result in iframe but all code in the textarea to affect only the result area.
http://jsfiddle.net/sederther/4x6dxrs5/
Add to your styles specifically for the box of results would not solve your problem?
.result p {
font-size:8px;
font-family:Georgia;
}
.result h1{
color:red;
font-size:26px;
font-family:Georgia;
}
Like this: http://jsfiddle.net/4x6dxrs5/2/
Check fiddle Here
Just did a few tweaking. Added a dummy attribute to 'textarea' and set a value for that attribute. I then loop through the element and check for the attribute, if found I will reset all the styles applied.
$(document).ready(function() {
var btn = $('.gen');
btn.on('click', function() {
var areaTxt = $('.textarea').val();
var div = $('.result');
div.html(areaTxt);
//Code Addtion
$("textarea").each(function(){
var attr =
$(this).attr('dataref');
if (typeof attr !== typeof undefined && attr !== false && attr == 'source') {
$(this).attr('style', 'background-color: #eee !important');
}
})
});
});
In this case, I am looping all the 'textareas' and check if it has 'dataref' attribute and the value equals source. if so then reset its style. I know it would be tedious to work on all the elements in similar manner, but without using iframe this can be work around.
my 2 cents
i have a question connected with title. Currently i am trying to follow google "best practice". https://developers.google.com/apps-script/guides/html/best-practices
I have no idea why its not working.
Here is a MainPageCSS.html
<pre>
<style>
p {
color: green;
}
</style>
</pre>
Then comes server-side function:
function includeCSS() {
var content = HtmlService.createTemplateFromFile('MainPageCSS').getRawContent();
//.getContent();
return content;
}
I am using a sidebar via HtmlService, and calling google.script.run.withSuccessHandler(SuccessAddCss).includeCSS();
I tried different ways of adding css into page, but noone worked...
function SuccessAddCss(Style){
var styles = document.getElementById("allStyles").innerHTML += "p { color:red }";
var text = styles.innerHTML;
var styleNode = document.createElement('style');
var styleText = document.createTextNode('p { color:red; } ');
styleNode.appendChild(styleText);
document.getElementsByTagName('head')[0].appendChild(styleNode);
alert("ok");
};
function teso()
{
google.script.run.withSuccessHandler(SuccessAddCss).includeCSS();
alert(text);
};
In order to add somehow css from MainPageCSS to MainPage
id="allStyles" type="text/css"
<pre>
<style id="allStyles" type="text/css">
h2{
font-family: Times New Roman, Times, serif;
font-size: 14px;
text-align: center;
}
</style>
</pre>
Also sidebar is launched in SandBox.Native mode, so it allows css dynamic changes.
Thank you for help.
In my website, I use a scriptlet to include the CSS file.
HTML:
<?!= include('MainPageCSS'); ?>
<div>Some Content Here</div>
<form>A form</form>
<button>A button</button>
That's how the include function gets called from the HTML file. Just curious, could you try taking out the <pre> tags and see if that makes any difference?