Centering three buttons in three divs on the same line - javascript

I have three buttons, inside three divs, and I need to center them on the same line.
They were created with the createElement() method. Button and Div.
This is the only way I know for creating buttons within functions or script tags or if-else statements. Or at least the only way that works for me. ^^;
I bet a visual would help at this point.
function threeGameButtons()
{
buttonDiv = createElement("div");
buttonDiv = setAttribute("center");
//This ^ has been to center the divs, and has done so by putting them on
//top of each other. I believe I understand why though.
gameButton = document.createElement("BUTTON");
gameText = document.createTextNode("text");
gameButton = appendChild(gameText);
buttonDiv.id = "buttonID";
gameButton.onclick = myFunction;
//calls a function for the game
buttonDiv.appendChild(gameButton);
document.body.appendChild(buttonDiv);
//two more buttons
}
So the three buttons made like this are called in a function earlier in the game. (I don't think I mentioned, but it's probably obvious now: this is for a game).
I'd love to just make a container div and center that or something but I'm completely unaware of how to do so when the divs are created like this in a function.
And I've tried some CSS to center the divs and buttons. Oh boy have I tried. But my efforts have been fruitless. I could give you everything, but I'd have to think back to all of the CSS methods I've tried.
One I've tried though:
#buttonID2 (Second and center button)
{
margin:0 auto;
}
#buttonID (First and left button)
{
display:inline-block;
position:absolute;
left:200px;
}
#buttonID3 (Third and right Button)
{
display:inline-block;
position:absolute;
right:200px;
}
When I try this, the third button goes to the second line, but goes to the right.
And I've tried adding inline-block to margin:0 auto; and it stops the second button from centering.
The other two still go left and right of the center though.
My intention isn't really to have them go that far to the left and right, but for right now, I just don't want them overlapping the middle button.
A note; All of this happens on the page that the function calling them happens. I'm not sure if that makes a difference or not. I thought I'd throw that in though, in case it does.

So you want to add three buttons inside a DIV tag, inline. If I understand your question correctly I think this is what you are looking for:
function threeGamesButton() {
var x =document.getElementById("box");
var btnSet = document.createElement("div");
btnSet.setAttribute("style","border: 1px solid black; width:800; height:300;" )
var firstButton = document.createElement("button");
firstButton.setAttribute("style","border: 1px solid black; width:200; height:250;" );
firstButton.setAttribute("onClick","myFunction1()" );
firstButton.innerText ="Button 1";
var secondButton = document.createElement("button");
secondButton.setAttribute("style", "border: 1px solid black; width:200; height:250;");
secondButton.setAttribute("onClick","myFunction2()" );
secondButton.innerText ="Button 2";
var thirdButton = document.createElement("button");
thirdButton.setAttribute("style", "border: 1px solid black; width:200; height:250;")
secondButton.setAttribute("onClick","myFunction3()" );
thirdButton.innerText ="Button 1";
btnSet.appendChild(firstButton);
btnSet.appendChild(secondButton);
btnSet.appendChild(thirdButton);
x.appendChild(btnSet);
}
In you html page include div which has id called box. And call the function from any where..Rather than setting a attribute for (styles), you can use
firstButton.className = "firstButton"
and then add css section for that name. But If the total width of the inside buttons are larger than the div tag where you insert all these buttons, then the last button will pass to the second raw automatically...

So I figured this out on my own, for anyone that needs it.
I have it here in JSFiddle.
But the part of the code for the buttons goes like this (ignore the odd function names) :
function continueIntro()
{
document.body.innerHTML = '';
var continueParagraph = document.createElement("p");
continueParagraph.innerHTML = "<center>These are the buttons I finally got <br>" +
"to center on the same line: </center>";
document.body.appendChild(continueParagraph);
getGoldButtons();
}
function getGoldButtons()
{
buttonDiv2 = document.createElement("div");
buttonDiv2.setAttribute("align","center");
gameButton2=document.createElement("BUTTON");
gameText2=document.createTextNode("First Option");
gameButton2.appendChild(gameText2);
buttonDiv2.id = "buttonDiv2";
gameButton2.onclick = caveGetGold;
buttonDiv2.appendChild(gameButton2);
gameButton3=document.createElement("BUTTON");
gameText3=document.createTextNode("Second Option");
gameButton3.appendChild(gameText3);
gameButton3.onclick = forestGetGold;
buttonDiv2.appendChild(gameButton3);
gameButton4=document.createElement("BUTTON");
gameText4=document.createTextNode("Third Option");
gameButton4.appendChild(gameText4);
gameButton4.onclick = tunnelGetGold;
buttonDiv2.appendChild(gameButton4);
document.body.appendChild(buttonDiv2);
}

Related

why document.execCommand('copy') doesnt copy here?

There is a list that when i search colors it opens, i want to copy the color name when i click on the list item, the color name is in a input[type=hidden] but i cant copy the value of the input. execCommand('copy') works fine with input[type=hidden].
link to codepen but you will not get the list because i used ajax for getting colors.
sorry if code is messy, i'm learning!
codepen
function copy(event) {
var alertColorBox = document.querySelector('.alertCopy .color');
alertColorBox.style.backgroundColor = event.target.style.backgroundColor;
var alert = document.querySelector('.alertCopy');
alert.classList.remove('alertAnimation');
var alert_span = document.querySelector('.alertCopy span');
// my question code part
var input = event.target.querySelector('input');
input.select();
document.execCommand('copy');
// my question code part
alert_span.innerHTML = input.value;
alert.classList.add('alertAnimation');
setTimeout(removeAlert, 5000);
}
I was with the same problem some time ago. Your code probably will work on Firefox, but on Chromium not.
What I have to do is remove the type="hidden" of the inputs, the I gave then a position="absolute" and "top: -1000px";
This isn't the best way to do that, but works. The inputs will not be visible anymore (on the screen), but the browser will copy the content.
I made this class to simplify:
.inputToHide {
opacity: 0;
padding: 0;
margin: 0;
position: absolute;
top: -1000px;
}
Ps.: Try to indent your code to be easier to understand
==========================================================
EDIT
If you can control your HTML, set a data-color in your div with contain the name of the color, then in the function you just need to create a input, append in the body then copy the content, something like this:
var colorInput = document.createElement('input');
colorInput = colorName.getAttribute('data-color');
document.body.appendChild(colorInput);
colorInput.select();
document.execCommand("copy");
document.body.removeChild(colorInput);
This is a better option after all

How would I make specific boxes changes color upon clicking on them?

I'd like to change color of more than one box to purple upon clicking on it. With my current code below, only one box gets colored purple when clicking on it.
I've tried so many different ways to make it work in terms of upon you clicking on any number of boxes, the box should turn purple, but all my attempts have failed.
What am I doing wrong?
function createBoxesDynamically() {
var tileLength = Math.floor(Math.random() * 11);
console.log("tileLength " + tileLength);
var box = new Array(tileLength);
console.log("box" + box);
for (var i = 0; i < box.length; i++) {
box[i] = "box";
}
for (var j = 0; j < box.length; j++) {
var div = document.createElement("div");
div.id = "box";
document.body.appendChild(div);
}
var boxes = document.querySelector("[id^=box]");
boxes.addEventListener("click", function () {
boxes.style.backgroundColor = "purple";
});
}
createBoxesDynamically();
#box {
border: 1px solid;
width: 50px;
height: 50px;
background-color: green;
}
You can't have multiple elements with identical id values, that's why no matter which box you click, the first one is always affected, your .querySelector() call stops looking after finding the first match.
Instead, move the code that sets up the event handler inside the loop where the box is being created and just use this in the click callback to have the callback act upon the box that was clicked. No id necessary. And, because you won't be using ids, you don't need your array or the first loop.
In general, stay away from coding solutions that rely on ids. Yes, they seem precise and easy to use at first, but what you'll find (and you already are) is that they create very brittle solutions that don't scale very well. There are many other ways of referencing and styling elements besides an id.
You should also try to avoid inline styling of elements (setting up styles directly on the style property) as this usually leads to duplication of code and therefore makes the code more difficult to read and maintain. Use CSS classes for as much as you can.
function createBoxesDynamically() {
var tileLength = Math.floor(Math.random() * 11);
console.log("tileLength " + tileLength);
for (var j = 0; j < tileLength; j++) {
var div = document.createElement("div");
div.classList.add("box"); // Add the CSS class to the element
div.addEventListener("click", function () {
this.classList.add("clickColor");;
});
document.body.appendChild(div);
}
}
createBoxesDynamically();
/* Use Classes instead of IDs */
.box {
border: 1px solid;
width: 50px;
height: 50px;
background-color: green;
}
.clickColor { background-color: #800080; }

How to edit text style with Javascript

I'm trying to make a button create new entries in a list that display similar to this:
"#1 new Click Me"
Except I want to make "Click Me" to show up as yellow text in a black box, and then I want to make the black box disappear and the text turn brown on mouseover. I've been able to make the list appear, but don't know how to edit the style of the text to make it appear the way I want to. The most code I think I need to give for this is this:
var li = document.createElement("li");
var liBody = document.createTextNode("#"+numOfNewCMs+
" new " + newClickMe);
li.appendChild(liBody);
And then I insert li into the list.
I figure I should make newClickMe a variable and edit that and then put it next to the rest of the text in the liBody variable, and I figure the HTML span element is the best way to do that, except I don't even know quite what the span element really does. How do I go about editing the style of that particular string? I can't get around to figuring out how (if I even can) make the text turn brown on mouseover until I do so.
Never met CreateTextNode, but i guessliBody.style.fontSize="12px"should help. And other properties such as 'fontWeight,color,fontStyle...'
HTML elements have a style property that can be used to apply CSS styles to them.
For example:
var newClickMe = document.createElement("span");
newClickMe.style.backgroundColor = "#000000";
newClickMe.style.color = "#FFFF00";
newClickMe.innerText = "Click Me";
var li = document.createElement("li");
var liText = document.createTextNode("#"+numOfNewCMs+
" new ");
li.appendChild(liText);
li.appendChild(newClickMe);
Will make the list item have a black background with yellow text.
For more details on the style property, MDN has a great section on it: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style
And here is a reference page to translate CSS properties into their JavaScript equivalent: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Properties_Reference
I'm assuming you want the styles to change on mouseOver. I just changed the styles using css' :hover. Is this what you had in mind?
var numOfNewCMs=1;
function generateLi(){
var li = document.createElement("li");
var liBody = document.createTextNode("#"+numOfNewCMs+
" new ");
var sp = document.createElement("span");
var spBody = document.createTextNode("Click Me");
sp.setAttribute("id", "sp"+numOfNewCMs);
sp.setAttribute("onmouseover", "highlight("+numOfNewCMs+")");
sp.setAttribute("onmouseout", "highlight2("+numOfNewCMs+")");
sp.style.backgroundColor='black';
sp.style.color='yellow';
sp.appendChild(spBody);
li.appendChild(liBody);
li.appendChild(sp);
lis.appendChild(li);
numOfNewCMs++;
}
function highlight(id){
var element= document.getElementById('sp'+id);
element.style.backgroundColor='white';
element.style.color='brown';
}
function highlight2(id){
var element= document.getElementById('sp'+id);
element.style.backgroundColor='black';
element.style.color='yellow';
}
li{
margin-bottom:20px;
}
li > span{
padding:5px;
margin-bottom:10px;
}
li:hover > span{
color:brown;
background-color:white;
}
<button onclick="generateLi()">Click me</button>
<div id="lis" style="margin-top:20px;"></div>

Adding and deleting a paragraph, displaying text briefly

After clicking on a specific place in an image map, the function add() should be run, a paragraph should be created, one should see "not available yet" in red for five seconds, and the paragraph should be deleted again.
function add() {
var x = document.createElement("P");
var t = document.createTextNode("This is a paragraph.");
x.appendChild(t);
document.body.appendChild(x);
setTimeout ( "del()", 5000 );
}
function del() {
removeChild() }
So there are a couple of things which are not correct.
1: how do you change the text to red? And to another font?
2: the del()function should remove the paragraph, but I don't know what to place there. Just removeChild(P) ? Wait... P isn't even a Child...
Could anyone help me with getting the desired result? (I mean, this: one should see 'not available yet' in red for five seconds, afterwards the paragraph should disappear.
to change the text to red using JavaScript:
para.style.fontFamily = 'Arial'
para.style.color = 'red'
to change the text to red using CSS:
CSS:
.mypara {
color: red;
font-family: Arial;
}
JS:
para.className = 'mypara'
to remove the paragraph:
var para = document.createElement("P");
function add() {
var t = document.createTextNode("This is a paragraph.");
para.appendChild(t);
document.body.appendChild(para);
setTimeout (del, 5000);
}
function del() {
para.parentNode.removeChild(para);
// or if you just need to empty the paragraph
// para.innerHTML = '';
}
To make that text red: There are two ways. Either you write:
x.style.color = '#ff0000';
Or you give it a class:
x.className = 'red_text'
... and define the style for that class in a stylesheet.
To remove the paragraph, just do the reverse of what you did to add it:
document.body.removeChild(x)
Take a look to this example.
1: how do you change the text to red? And to another font?
I suggest to use CSS for everything regarding style and simply assign the right class to the element. You can specify whatever you need. For example also use CSS for a fade in effect.
2: the del()function should remove the paragraph, but I don't know what to place there. Just removeChild(P) ?
I suggest to use a closure and pass parent and child in order to use parent.removeChild(child);. If you do not need nothing else you even could avoid to define another function.

How to position a div next to element with absolute position?

I am trying to create a div that can be attached to an element whenever user hover to the link
I have many links and my codes look like the following.
for loops to create many links
codes....
link.href='#';
link.innerHTML = 'test'
link.onmouseover = OnHover;
codes....
function OnHover(){
var position;
var div = document.createElement('div');
div.className='testdiv';
div.innerHTML = 'test';
position=$(div).position();
div.style.top = position['top'] + 15 + 'px';
$(this).prepend(div);
}
link element1
link element2
----
| | //add new div when hover link element2
----
link element2
link element3
my css
.testdiv{
position:absolute;
}
I want to add a new div everytime the user hover to my link and position on the left top of the element.
My code would position all the div on top instead of every element.
Are there anyway to do this? Thanks so much!
Without seeing your other JavaScript/markup I can make the following observations:
You need to set position:absolute on your new div before top will do anything.
You need to make sure link is non-position:static.
Non-dynamic styles like the above should be in your CSS, not JS.
Positioning absolutely means you shouldn't need to use $(div).position()
You're using a mix of jQuery and pure JavaScript which looks a little odd :)
JS
function OnHover() {
var position;
var div = $('<div></div>');
div.addClass('testdiv');
div.html('test');
div.css('top', 15);
$(this).prepend(div);
}
CSS
.testdiv {
position:absolute;
}
a.testanchor {
position:relative;
}

Categories

Resources