In my HTML i have put a script and a div. Now i want to make 3 buttons next to each other in the while block in the middle of the page. I want to make the 3 buttons without changing the html and thus make it dynamic inside the javascript.
So far i have put a var in the javascript but i do not know what to do now..
I earlier made a html page with a button element inside it and then change all of it using the html but i cant figure out how to do this if there isn't a button element inside the html page.
HTML:
<body>
<div id="container"></div>
<script src="button.js"></script>
</body>
CSS:
html{
background-color: grey;
}
#container{
top: 10px;
padding: 82px;
margin: auto;
width: 450px;
background-color: white;
position: relative;
}
JS:
var buttons = document.getElementsById("container");
button.onclick = onbuttonclicked;
function onbuttonclicked(){
if (onbuttonclicked) {
button1.style.backgroundColor = "red";
button1.disabled=true;
} else {
button1.style.backgroundColor = "green";
button1.disabled=false;
}
}
so like here each button has its own text and color
Create the buttons and append them as children of your buttons container. Here I am creating one button. You can do the same for other buttons:
var buttons = document.getElementById("container");
var button1 = document.createElement("button");
button1.onclick = onbuttonclicked;
buttons.appendChild(button1);
function onbuttonclicked() {
if (onbuttonclicked) {
button1.style.backgroundColor = "red";
button1.disabled = true;
} else {
button1.style.backgroundColor = "green";
button1.disabled = false;
}
}
Note that onbuttonclicked will always evaluate to true because you are checking whether the function is defined or not. Also, if you want to change the background and disabled attribute of the clicked button, rather than button1 explicitly, you should use this instead of button1.
var container = document.querySelector("#container");
var arr = ['success','danger','warning'];
for (var i = 0; i < 3; i++) {
var button = document.createElement("button");
button.setAttribute("attribute", arr[i]);
button.innerHTML = arr[i];
button.className += arr[i];
container.appendChild(button);
console.log(button)
}
html{
background-color: grey;
}
#container{
top: 10px;
padding: 82px;
margin: auto;
width: 450px;
background-color: white;
position: relative;
}
btn {
border: none;
background-color: inherit;
padding: 14px 28px;
font-size: 16px;
cursor: pointer;
display: inline-block;
}
.success {
color: black;
background:green;
}
.success:hover {
background-color: #4CAF50;
color: white;
}
.warning {
background: yellow;
color:black;
}
.warning:hover {
background: #ff9800;
color: white;
}
.danger {
background: red;
color:black;
}
.danger:hover {
background: #f44336;
color: white;
}
<body>
<div id="container"></div>
<script src="button.js"></script>
</body>
I think like this?
So for this you are trying to manipulate the DOM using JavaScript, take your div#container and you are trying to append three button elements. The process for doing this (or really any HTML Element with JS DOM manipulation is fairly similar, you create the element, add the attributes you want, and then "append" it to the main element where you want it inserted)
Check out my example below to add 3 buttons to your <div id="container">:
var container = document.querySelector("#container"); //or use document.getElementById("container"), makes no difference
for (var i = 0; i < 3; i++) {
var button = document.createElement("button"); //works with any HTML5 element
button.setAttribute("attribute", "value"); //Use this to add attributes such as id, class, styles, or even event listeners like onclick
button.innerHTML = "Button Text"; //Make sure to add button text if you don't want an empty button!!
container.appendChild(button);
}
Since you said you want the buttons next to each other (I'm assuming this means side-by-side) then you can add a style to your CSS
button {
display: inline;
}
but of course that would depend on your usage, meaning if you wanted all buttons to be inline. If you wanted just those three then you can use the .setAttribute("class", "classname"); to add a class and then define that class to have the same style.
You can also make your container a CSS flexbox and have each of the buttons aligned horizontally
#container {
display: flexbox;
flex-direction: row; /*Use row for horizontal, column for vertical*/
}
and you wouldn't need to style your buttons. But the choice is yours.
Edit: to make 2 buttons, one green and one red,
//Make a green text button1
var button1 = document.createElement("button"); //works with any HTML5 element
button1.style.color = "green";
button1.innerHTML = "Button1 Text"; //Make sure to add button text if you don't want an empty button!!
container.appendChild(button1);
//Make a red text button2
var button2 = document.createElement("button"); //works with any HTML5 element
button2.style.color = "red";
button2.innerHTML = "Button2 Text"; //Make sure to add button text if you don't want an empty button!!
container.appendChild(button2);
If you wanted to change the background colors as well you could add button.style.backgroundColor = "pink" or whatever color you'd like
Check out: JavaScript DOM Methods, this was a REAL help to me when I was learning what you're trying to do right now!
To give the buttons a function use the onclick value of the button, so in the above script we can add something like this:
button1.onclick = button1AfterClicked;
//Or
button1.setAttribute("onclick", "button1AfterClicked");
And since JavaScript is pretty lenient we can define our button1AfterClicked() anywhere
function button1AfterClicked() {
button1.style.color = "some color";
//And so forth...
}
For these kinds of questions I highly suggest looking up the answer on google because I know W3Schools does a splendid job on explaining the basics and more: OnClick Event JavaScript
You Can do it with jquery check is this right ?
$("#container").html('<button class="green-button">Button1</button><button class="red-button">Button2</button><button class="yellow-button">Button3</button>');
$( ".red-button" ).click(function() {
$(".red-button").css("background-color", "red");
});
$( ".green-button" ).click(function() {
$(".green-button").css("background-color", "green");
});
$( ".yellow-button" ).click(function() {
$(".yellow-button").css("background-color", "yellow");
});
<div id="container"></div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
Following is what might help you,you can set margin and padding to your needs:
var button = document.createElement("button");
button.innerHTML = "Do Something";
var body = document.getElementsByTagName("body")[0];
body.appendChild(button);
button.addEventListener ("click", function() {
alert("did something");
});
The code provided is all you needed for your current project
You can add the style of the button in CSS
// container of buttons
const containerBtn = document.querySelector('.container');
let createBtns = (classParam, text) => {
let btn = document.createElement('button');
btn.classList.add(classParam);
btn.innerText = text;
containerBtn.append(btn);
return btn;
};
// 1. add the button **class**
// 2. add the button text
let btn1 = createBtns('btn-1', 'test');
// add event listener to btn1
btn1.addEventListener('click', () => {
console.log(1);
});
This is an example where three buttons are created and styled with CSS. They use the nth-of-type() and attribute selectors to style the buttons based on their position and disabled state.
Do note that when disabling the buttons they won't listen to the click event anymore.
const container = document.getElementById('container');
for (let i = 0; i < 3; i++) {
const button = document.createElement('button');
button.textContent = `Button ${i + 1}`;
container.append(button);
}
container.addEventListener('click', event => {
const { target } = event;
if (!target.tagName.toLowerCase() === 'button') {
return;
}
if (!target.disabled) {
target.disabled = true;
} else {
target.disabled = false;
}
});
#container {
display: flex;
}
#container button {
padding: 15px;
color: white;
}
#container button:first-of-type {
background-color: red;
}
#container button:nth-of-type(2) {
background-color: blue;
}
#container button:last-of-type {
background-color: goldenrod;
}
#container button[disabled] {
background-color: black;
}
<div id="container"></div>
Related
I do not know how to ask this question correctly and I do not know how to find solutions in google because it leads me to how to add entire background color to a textbox which I am not looking for. I am trying to achieve such results like image below:
I want to add background to each text(of course characters) inside a input tag except spaces. User will start typing stuff inside input tag and will apply background color but spaced text won't color.
I do not have any code because I do not know how to do it using css or JS if neccesary. I just have a
<input type="text">
I think it might use only JS but I do not know how to(of course I know JS). How do I achieve that?
You can use div with contentEditable and use little js to append text as span
<div contentEditable></div>
CSS
span {
background-color: red;
margin-right: 2px;
}
div {
border: 1px solid black;
}
var el = document.querySelector("div");
el.addEventListener("blur", () => {
var content = el.textContent;
var contents = content.split(" ");
el.innerHTML = "";
contents.forEach((item) => {
el.innerHTML += `<span>${item}</span>`;
});
});
Something like this
Another method is to overlap the input box with a "mirroring" element. The overlap must be precise, both in layout and text characteristics. Here is a minimal example:
var input = document.getElementById("input"),
mirror = document.getElementById("input-mirror");
input.addEventListener("keyup", function() {
var words = input.value.split(" ").map(function(a) {
var span = document.createElement("span");
span.textContent = a;
return span;
});
mirror.innerHTML = "";
for (let i = 0; i < words.length; i++) {
mirror.append(words[i], " ");
}
});
.container {
display: grid;
}
#input,
#input-mirror {
font: inherit;
box-sizing: border-box;
margin: 0;
border: 1px solid;
padding: 0;
grid-row: 1;
grid-column: 1;
}
#input {
background: transparent;
}
#input-mirror > span {
background: #0f0;
}
<div class="container">
<span id="input-mirror"></span>
<input id="input" type="text" />
</div>
I'm trying to create customizable checkboxes using buttons. I'm able to differentiate which button class has been selected, but I've been unable to track the button class post form submission. Ideally, instead of reseting the buttons to a default value when the page is loaded or submitted, I can keep whatever input was initially provided. I've tried using the isset() php function, but I don't think it's a valid solution in this circumstance. Are there any alternatives? Find my code below:
<form id="my-form" method="post">
<html>
<body >
<style>
.button {
color: white;
padding: 10px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 12px;
margin: 4px 2px;
cursor: pointer;
}
.button1 {
border-radius: 100%;
background-color: green;
border: none;
}
.button2 {
border-radius: 100%;
background-color: red;
border: none;
}
</style>
<div id="test1"></div>
<div id="test2"></div>
<!-- invalid code?
<?php
echo isset($_POST["t1test"]);
echo isset($_POST["t2test"]);
echo $_POST["t1test"];
echo $_POST["t2test"];
?>
-->
<script type="text/javascript">
function makeButton(div, val) {
var element = document.getElementById(val);
var button = document.createElement("button");
var span = document.createElement("span");
// change to account for submitted settings
if (element == null) {
button.setAttribute("class", "button button1"); }
else {
var cL1 = element.classList.contains("button1");
var cL2 = element.classList.contains("button2");
element.parentNode.removeChild(element);
if (cL2 == true) { button.setAttribute("class", "button button1"); }
if (cL1 == true) { button.setAttribute("class", "button button2"); }
}
button.setAttribute("type", "button");
button.setAttribute("id", val);
button.setAttribute("name", val);
var testDiv = document.getElementById(div);
testDiv.appendChild(button);
button.addEventListener ("click", function() { makeButton(div, val); })
}
window.onload = function() {
makeButton("test1", "t1test");
makeButton("test2", "t2test"); }
</script>
</body>
</html>
<button id="submit">Submit</button>
</form>
How about removing the form tags and adding a "click" event listener to the submit button? The code shown below inserted appended to the end of the file:
<script>
document.getElementById("submit").addEventListener("click", function(){
var elements = ["t1test", "t2test"];
for(var i = 0; i < elements.length; i++) {
var element = document.getElementById(elements[i]);
console.log(element.classList.contains("button1"));
console.log(element.classList.contains("button2"));
}
});
</script>
This way the page will not be reloaded when the button is pressed thus retaining button selection.
I am trying to create a toggle function with JavaScript (not jQuery).
I have created an ID named box, and a class within the ID named box-open.
The width of the ID box is 100px.
The width of box-open is set to 1000px.
When I try to use my code I get this error, that displays “Cannot set property 'display' of undefined”.
I have tried writing the code a couple of different ways, but I always seem to get the same error in the console.
function toggle(open) {
box = document.getElementById('box').style.display = 'block';
if (open == true) {
box.style.display = 'none';
boxOpen = document.getElementsByClassName('box-open').style.display = 'block';
} else {
box.style.display = 'block';
boxOpen.style.display = 'none';
}
}
#box {
width: 100px;
height: 100px;
background: gold;
text-align: center;
display: block;
}
.box-open {
width: 50px;
height: 50px;
background: green;
display: none;
}
<div id="box" class="box-close"></div>
<button type="button" onClick="toggle()">click me</button>
This is a link to my codepen, where you can find the code
http://codepen.io/2bu/pen/YNYjjR
I am not sure but this line:
box = document.getElementById('box').style.display = 'block'
should be maybe
box = document.getElementById('box');
Your function is not very flexible because it can only toggle a specific box with ID "box". Instead you could pass in a selector for the element you want to toggle:
<div id="box" class="box-close"></div>
<button type="button" onClick="toggle('#box')">click me</button>
And then in your Javascript:
function toggle(selector) {
var box = document.querySelector(selector);
var isOpen = box.style.display === "block";
box.style.display = isOpen ? "none" : "block";
}
This way you can use the same toggle function to toggle any box you like.
Here is a simple jQuery implementation. Just change the .box-toggled class to be whatever you actually want. It also uses eventListener to keep your HTML cleaner.
https://jsfiddle.net/segbxnh3/3/
var box = document.querySelector('#box');
var toggleButton = document.querySelector('button');
toggleButton.addEventListener('click', function() {
$(box).toggleClass('box-toggled');
});
UPDATE:
Here is a vanilla JS implementation.
https://jsfiddle.net/segbxnh3/5/
var box = document.querySelector('#box');
var toggleButton = document.querySelector('button');
toggleButton.addEventListener('click', function() {
if (box.classList.contains('box-toggled')) {
box.classList.remove('box-toggled');
} else {
box.classList.add('box-toggled');
}
});
You can use like this.
function toggle(open, element){
box = document.getElementById('box');
boxOpen = document.getElementById('box-open');
if ( open == true) {
box.style.display = 'none';
boxOpen.style.display = 'block';
element.setAttribute('onclick', "toggle(false, this);");
}else{
box.style.display = 'block';
boxOpen.style.display = 'none';
element.setAttribute('onclick', "toggle(true, this);");
}
}
*{
margin:0px;
padding:0px;
font-family: 'Montserrat', sans-serif;
}
#box{
width:100px;
height: 100px;
background: gold;
text-align: center;
display:block;
}
#box-open{
width:50px;
height: 50px;
background: green;
display: none;
}
<div id="box"></div>
<div id="box-open"></div>
<button type="button" onClick="toggle(true, this);" >click me </button>
Also, check this solution
Is it possible to somehow set my custom html object to event.dataTransfer.setDragImage(myCustomHtml,0,0) ?
I tried like this
var x=$doc.getElementById("row_selected_notification");
event.dataTransfer.setDragImage(x, 100, 100);
but it didn't work.
As I'm doing this through Java, I'm using native methods so jQuery is not an option for me.
You can either create a custom element on drag or use an existing element.
If you are crating an element you have to make sure it is not visible after adding it to the DOM. I've just added a negative top value to the create element to hide it, but i am sure that there are other ways to fix this as well.
Here is an example with one existing element and one that will be created.
var foo = document.getElementsByClassName("drag-me").item(0),
bar = document.getElementsByClassName("drag-me").item(1);
// Drag foo and create custom element.
foo.addEventListener("dragstart", function(e) {
var elem = document.createElement("div");
elem.id = "drag-ghost";
elem.textNode = "Dragging";
elem.style.position = "absolute";
elem.style.top = "-1000px";
document.body.appendChild(elem);
e.dataTransfer.setDragImage(elem, 0, 0);
}, false);
// Drag bar and use foo as ghost image
bar.addEventListener("dragstart", function(e) {
e.dataTransfer.setDragImage(foo, 0, 0);
}, false);
// Let's remove the created ghost elem on dragend
document.addEventListener("dragend", function(e) {
var ghost = document.getElementById("drag-ghost");
if (ghost.parentNode) {
ghost.parentNode.removeChild(ghost);
}
}, false);
.drag-me {
width: 100px;
padding: 30px 0;
text-align: center;
color: white;
display: inline-block;
}
.drag-me:nth-child(1) {
background-color: green;
}
.drag-me:nth-child(2) {
background-color: red;
}
#drag-ghost {
width: 200px;
height: 200px;
background-color: yellow;
}
<div class="drag-me" draggable="true">Drag Me Foo</div>
<div class="drag-me" draggable="true">Drag Me Bar</div>
I'm trying to learn the vanilla JS way of toggling a button color with addEventListener. I'm having some trouble understanding how to switch the button back to the original color. Here is my code:
HTML
<h1>Hello</h1>
<section id="container"></section>
CSS
h1 {
font-family: sans;
}
#container {
padding: 2em;
background-color: tomato;
}
#container2 {
padding: 2em;
background-color: blue;
}
JS
var el = document.getElementById('container');
el.addEventListener('click', function() {
this.style.backgroundColor = 'blue';
});
jsbin
You can restore the declared CSS style by clearing the background color, like this:
this.style.backgroundColor = '';
Fiddle at http://jsfiddle.net/xza5bt0q/
Click the box to toggle the color.
You could check if a color is set and remove it otherwise:
el.addEventListener('click', function() {
if (this.style.backgroundColor == 'blue') {
this.style.backgroundColor = null;
} else {
this.style.backgroundColor = 'blue';
}
});
Try like the given code snippet here
HTML
<div id="toggleArea" class='active'> Toggle area see in class name </div>
<button id="btnToggle"> Toggle Button </button>
JavaScript
const toggleArea = document.getElementById('toggleArea')
const btnToggle = document.getElementById('btnToggle')
btnToggle.addEventListener('click', function() {
if (toggleArea.classList.contains('active')) {
toggleArea.classList.remove("active");
toggleArea.classList.add("disable");
} else {
toggleArea.classList.remove("disable");
toggleArea.classList.add("active");
}
toggleArea.innerHTML = toggleArea.classList[0]
})
I would recommend toggling a CSS class when clicking. Then you can use the class to control color and other properties.
CSS
.container-active {
background-color: blue;
}
JS
var ACTIVE_CLASS = 'container-active'; // define a css class 'constant'
var el = document.getElementById('container');
el.addEventListener('click', function () {
var classes,
idx;
// simplest case: class name is empty
if (this.className === '') {
this.className = ACTIVE_CLASS;
return;
}
// next: class name matches active
if (this.className === ACTIVE_CLASS) {
this.className = '';
return;
}
// otherwise, if more complex, parse and modify classes
classes = this.className.split(' ');
idx = classes.indexOf(activeClass);
if (idx === -1) {
classes.push(activeClass);
} else {
classes.splice(idx, 1);
}
this.className = classes.join(' ');
});
Try the following codes: HTML, CSS, and Javascript.
In this code, the default color of the button is set to be blue. Once you click the button, it changes the background-color to red. If you click it again, the background-color changes to the default i.e. blue.
HTML
<button id="button" class="blueColor" onclick="toggle()">GET STARTED</button>
CSS
#button{
color: white;
width: 175px;
height: 50px;
border-radius: 5px;
font-family: arial;
font-weight: bold;
word-spacing: 3px;
border: none;
outline: none;
}
.blueColor{
background: blue;
}
.redColor{
background: red;
}
Javascript
<script>
function toggle(){
var colorofbutton = document.querySelector("#button");
if(document.getElementsByClassName("blueColor")[0])
{
colorofbutton.classList.remove('blueColor');
colorofbutton.classList.add('redColor');
}
else
{
colorofbutton.classList.remove('redColor');
colorofbutton.classList.add('blueColor');
}
}
</script>