I'm trying to create this piece of code in which an element is pushed into an array, displayed and get a style added which gives them a random hex color. I got the hex color and the pushing into the array partly done, but I can't seem to be able to add the style nor display the div… Here is my code so far:
JS
var colorBg = '#' + (Math.random() * 0xFFFFFF << 0).toString(16)
var elements = []
var el = '<div class="element bg"></div>'
document.getElementById("addEl").onclick = () => {
elements.push(el)
//console.log(elements)
for (i = 0; i < elements.length; i++) {
console.log(elements[i])
document.write(elements[i])
//elements[i].style.backgroundColor = colorBg
}
}
HTML
<div class="container">
<div class="element bg"></div>
</div>
<input type="button" value="Add Block" id="addEl"/>
CSS
html, body{
height:80%;
}
.container{
width:100%;
height:100%;
}
.element{
width:100px !important;
height:100px;
}
Do not use document.write(). Instead, create HTML elements with document.createElement() and then append them to other elements.
You can also just set their color and append them once when you create the element. No need to do all that for ALL the elements every time you click the button.
If you want to randomize the color of every element on every button press, you could instead select all of the elements, iterate over them, and randomize their color that way.
document.getElementById("addEl").onclick = () => {
var el = document.createElement("div");
el.className = ["element bg"];
var colorBg = '#' + (Math.random() * 0xFFFFFF << 0).toString(16)
el.style.backgroundColor = colorBg
document.getElementById("container").append(el)
}
html, body{
height:80%;
}
#container{
}
.element{
width:100px !important;
height:100px;
margin:10px;
border:1px solid black;
}
<div id="container">
</div>
<input type="button" value="Add Block" id="addEl"/>
To give structure to the code it is nice to have each operation as a separate function. Random color string generation, new DOM element construction (without displaying it), main actions. This way it is easy to read the code: can start reading at any point and understand what the lines of code are doing, not necessary having to learn the whole code logic.
What's happening here. It starts with a button click, which fires a "click" event, that has function addEl() bound to it. addEl() would acquire a new DOM element from createEl(), place it inside container element and push the element to the elements array if its required for some other functionality not covered in the original question.
function getColor() {
return '#' + (Math.random() * 0xFFFFFF << 0).toString(16);
}
function createEl(){
var el = document.createElement("div");
el.className = "element bg";
el.style.backgroundColor = getColor();
return el;
}
function addEl() {
var el = createEl();
container.appendChild(el);
elements.push(el);
}
var container = document.getElementById("container");
var elements = [];
document
.getElementById("addEl")
.addEventListener('click', addEl)
;
html, body{
height:80%;
}
#container{
width:100%;
height:100%;
}
.element{
width:100px !important;
height:100px;
float:left;
}
<div id="container"></div>
<input type="button" value="Add Block" id="addEl"/>
You would create elements using DOM methods instead of using document.write(). It's usage is discouraged. The following will do what you are after:
document.getElementById("addEl").addEventListener('click', () => {
let container = document.querySelector('.container');
let el = document.createElement("div");
el.className = 'element bg';
el.innerText = 'foo';
el.style.backgroundColor = getRandomColor();
container.appendChild(el);
});
function getRandomColor() {
return '#' + (Math.random() * 0xFFFFFF << 0).toString(16);
}
html, body{
height:80%;
}
.container{
width:100%;
height:100%;
}
.element{
width:100px !important;
height:100px;
}
<div class="container">
<div class="element bg"></div>
</div>
<input type="button" value="Add Block" id="addEl"/>
This can be simply done using jquery
$(function () {
var elements = []
var el = '<div class="element bg"></div>'
$("#addEl").click(function () {
var colorBg = '#' + (Math.random() * 0xFFFFFF << 0).toString(16)
var el = $("<div />",
{
class: "element bg",
css: {
width: "20px",
height: "10px",
backgroundColor: colorBg
}
});
elements.push(el)
$("#mycontainer").append(el);
});
})
html, body{
height:80%;
}
.container{
width:100%;
height:100%;
}
.element{
width:100px !important;
height:100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container" id="mycontainer">
<div class="element bg"></div>
</div>
<input type="button" value="Add Block" id="addEl"/>
Related
This question already has answers here:
How to add/remove a class in JavaScript?
(13 answers)
Closed 5 years ago.
How to change a class with Javascript using getElementsByClassName. I got it to work a little but it won't change the class one at the time bet only do it one time to.
I click the button to change css class it do it on all the div and I can do it more in one time.
Here is my Code
function Button_Color(Show_This) {
var x = document.getElementById("Color_box");
var i;
var Show_This;
if (Show_This == 1)
{
var d = document.getElementsByClassName("id_blue");
d[0].className = "hid";
var o = document.getElementsByClassName("id_red");
o[0].className = " uhid";
}
if (Show_This == 2) {
var d = document.getElementsByClassName("id_blue");
d[0].className = "hid";
var o = document.getElementsByClassName("id_red");
o[0].className = " uhid";
}
}
Here is a like to show you how it looks now with html css js
https://jsfiddle.net/ee51o5h5/1/
I want it to show red only when you click the little red one and blue only when you click the little blue one.
i am dyslexic and from a non-english speaking country so sorry for any miss up.
i try this :
<body>
<section class="section-button-box">
<div class="box-button box-color01" onClick="Button_Color(1);">
</div>
<div class="box-button box-color02" onClick="Button_Color(2);">
</div>
</section>
<section class="section-color-box" id="Color_box">
<div class="main-color id_blue">
<div class="box-size box-color01">
</div>
</div>
<div class="main-color id_red">
<div class="box-size box-color02">
</div>
</div>
<div class="main-color id_blue">
<div class="box-size box-color01">
</div>
</div>
<div class="main-color id_red">
<div class="box-size box-color02">
</div>
</div>
</section>
</body>
JS:
/*| Blue box |*/
function Button_Color(Show_This) {
var x = document.getElementById("Color_box");
var i;
var Show_This;
var list = document.getElementsByClassName("main-color");
for(var i = 0 ; i < list.length; i ++ ){
if (Show_This == 1)
{
console.log(list[i].classList.contains("id_blue"));
if(list[i].classList.contains("id_blue")){
list[i].classList.add("uhid");
list[i].classList.remove("hid");
}
if(list[i].classList.contains("id_red")){
list[i].classList.add("hid");
list[i].classList.remove("uhid");
}
}
if (Show_This == 2) {
console.log(list[i].classList.contains("id_blue"));
if(list[i].classList.contains("id_blue")){
list[i].classList.add("hid");
list[i].classList.remove("uhid");
}
if(list[i].classList.contains("id_red")){
list[i].classList.add("uhid");
list[i].classList.remove("hid");
}
}
}
}
and css :
/*| Button Box |*/
.section-button-box{
height:100px;
width:100%;
background-color:aqua;
}
.box-button{
height:50px;
width:50px;
float:left;
}
/*| Color Box |*/
.section-color-box{
height:300px;
background-color:#c1c1c1;
width:100%;
}
.box-size{
height:100px;
width:100px;
float:left;
}
.box-color01{
background-color:blue;
}
.box-color02{
background-color:red;
}
.hid , .hid .box-size {
height:0px;
width:0px;
}
.uhid{
height:100px;
width:100px;
}
i add something to your code . Hope to sovle your issue.
you just need to find all elements in the desired class, iterate them and change their classes to the class that makes their color:
if (Show_This == 1)
{
document.getElementsByClassName("box-color02").forEach(function(element){
element.className = "box-size box-color01";});
}
if (Show_This == 2)
{
document.getElementsByClassName("box-color01").forEach(function(element){
element.className = "box-size box-color02";});
}
I am just new in programming and that's my first attempt to learn something new. I can't get what is wrong with my code, because it doesn't want to work. All I need is to change the bg-color just by clicking on the div. It works if you remove 1st line of code until "function", but only on onload the page.
document.getElementById("trying").onclick = function(){
var someText = document.getElementById("textArea").value;
document.getElementById("randomText").innerHTML = someText;
}
document.getElementById("mainBox").onclick =
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
document.getElementById("mainBox").style.backgroundColor = getRandomColor();
.mainBox {
width: 400px;
height:350px;
background-color:pink;
margin-right:auto;
margin-left:auto;
}
#textArea {
margin-left:100px;
}
<div id="mainBox" class="mainBox">
<p id="randomText" align="center">U know who you are?</p>
<input type="text" id="textArea">
<button id="trying">Try it!</button>
</div>
The way you were setting the onClick handler was wrong.
document.getElementById("trying").onclick = function(){
var someText = document.getElementById("textArea").value;
document.getElementById("randomText").innerHTML = someText;
}
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
document.getElementById("mainBox").onclick = function() {
document.getElementById("mainBox").style.backgroundColor = getRandomColor();
}
.mainBox {
width: 400px;
height:350px;
background-color:pink;
margin-right:auto;
margin-left:auto;
}
#textArea {
margin-left:100px;
}
<div id="mainBox" class="mainBox">
<p id="randomText" align="center">U know who you are?</p>
<input type="text" id="textArea">
<button id="trying">Try it!</button>
</div>
I notice you have all your code in one place separate it. If you don't adhere to encapsulation you can get into a lot of trouble. Separate your code and things will be much easier for you. You were just missing a bracket, also try to form your answers a little bit clearer to avoid getting down voted ;). Also, we you have to fix your code so that the words don't disappear, i'll let you figure that out on your own.
Simple way to understand Encapsulation and Abstraction
http://codepen.io/psikosen/pen/RGPkAv
html
<div id="mainBox" class="mainBox">
<p id="randomText" align="center">U know who you are?</p>
<input type="text" id="textArea">
<button id="trying">Try it!</button>
</div>
css
.mainBox {
width: 400px;
height:350px;
background-color:pink;
margin-right:auto;
margin-left:auto;
}
#textArea {
margin-left:100px;
}
Js
document.getElementById("trying").onclick = function(){
var someText = document.getElementById("textArea").value;
document.getElementById("randomText").innerHTML = someText;
}
document.getElementById("mainBox").onclick = function() {
document.getElementById("mainBox").style.backgroundColor = getRandomColor();
function getRandomColor(){
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
}
I have a page with p tags and div element, the div element is set with display:none in the starting so, I just want to display the different divs as shown below inside the body tag on the click of the p tag but i got stuck in fetching the different id of the divs. Please do help me out from this situation.Below is my code. Thanks
<script>
function toggle(id)// here is the function which gets the different ids of the div
{ var element = document.getElementById(id);
for(i=1; i<3; i++)
{
if(element[i].style.display == "none")
{
element[i].style.display = "block";
}
else
{
element[i].style.display = "none"
}
}
}
</script>
<body>
<p onclick="toggle('div1')">Sentence1</p>
<p onclick="toggle('div2')">Sentence2</p>
<div id="div1" name="Name 1" style="display:none; width:400px; height:300px; border:1px solid black; background-color:yellow;" id="div1">Barun Ghatak</div>
<div id="div2" style="display:none; width:400px; height:300px; border:1px solid black; background-color:black;" id="div2">Bhoopi</div>
</body>
You only have one of each div, so you don't need the loop. Just use
function toggle(id)// here is the function which gets the different ids of the div
{
var element = document.getElementById(id);
if(element.style.display == "none")
{
element.style.display = "block";
}
else
{
element.style.display = "none"
}
}
document.getElementById returns a single object and not an array.
If you want to get both the divs, I suggest using a class to get them.
If you wanted to only show one at a time, for example if you were building a tabs, then you could use this code to hide all the other divs first, then show only the one you want to toggle. Otherwise, if you're happy to toggle them, you can use the code posted by the others.
JS Fiddle demo: http://jsfiddle.net/ecs77e9a/
HTML
<p onclick="toggle('div1');">Sentence1</p>
<p onclick="toggle('div2');">Sentence2</p>
<div id="content">
<div id="div1" name="Name 1" style="display:none; width:400px; height:300px; border:1px solid black; background-color:yellow;" id="div1">Barun Ghatak</div>
<div id="div2" style="display:none; width:400px; height:300px; border:1px solid black; background-color:black;" id="div2">Bhoopi</div>
</div>
JS
function toggle(id)
{
//Hide all other divs first
var divs = document.getElementById('content').childNodes;
for ( var i = 0; i < divs.length; i++ ) {
if ( divs[i].nodeName == "DIV" ) {
var div = document.getElementById(divs[i].id);
div.style.display = "none";
}
}
//Show the one that's being requested
var element = document.getElementById(id);
element.style.display = "block";
}
I am new to javascript and I am trying to do a featured content slider something like the top banner in this website http://www.homeplus.co.kr
As you can see, the top big banner changes automatically & also will change when user hovers over one of the list at the right.
Right now I am able to do the hovering part, but I am still stuck at the automatic changing content part.
Here's a sample jsfiddle: http://jsfiddle.net/StormSdq/5tWPy/2/
<div class="pi">a</div>
<div class="pi">b</div>
<div class="pi">c</div>
<div class="pi">d</div>
<div class="c1">I DREAM</div>
<div class="c1">OF LLAMAS</div>
<div class="c1">JUMPING AROUND</div>
<div class="c1">EATING BUSHES</div>
css:
.pi {
font-size:12px;
color:#000;
font-weight:700;
width:30px;
height:25px;
margin-right:10px;
background:transparent;
border-bottom:solid 1px black;
}
.c1 {
border:1px solid blue;
background:lightskyblue;
width:200px;
height:200px;
float:right;
margin-right:430px;
margin-top:-100px;
color:red;
font-size:25px;
text-align:center;
display:none;
}
javascript:
div = document.getElementsByClassName('c1');
div[0].style.display = 'block'
B = document.getElementsByClassName('pi');
B[0].onmouseover = function () {
blip(0);
};
B[1].onmouseover = function () {
blip(1);
};
B[2].onmouseover = function () {
blip(2);
};
B[3].onmouseover = function () {
blip(3);
};
function blip(y) {
div = document.getElementsByClassName('c1');
for (x = 0; x < (div.length); x++) {
div[x].style.display = 'none';
}
div[y].style.display = 'block';
}
Any help will be greatly appreciated
Try this:
var cur = 0; // current index
setInterval(autoAnim, 2000); // auto change every 2s
function autoAnim(){
if(cur > 3) cur = 0;
blip(cur);
cur++;
}
Here is jsfiddle
You can use the function setTimeout to call something after XX miliseconds.
var number=0;
setTimeout(automatic,5000); // every 5 seconds
function automatic(){
blip(number);
number++;
if (number > 4)
number=0;
alert("Hello");
setTimeout(automatic,5000);
}
You will probably want to make the function sleep when mouse is hover and some others condtions
I am trying to create an infinite scroll of elements, and haven't found a plugin that was sufficiently lightweight/capable enough, so I'm trying to create my own.
So far it is working swimmingly, except for a slight jerkiness in the animation when I remove the first element and append it to the end of the parent. The example I've tossed up also has an issue where the elements lose their padding, for some reason, but that is not occurring in my actual code...
Fiddle:
http://jsfiddle.net/WtFWy/
Using the sample markup:
<section id="photos" class="bg-transparent-black">
<div class="red"></div>
<div class="blue"></div>
<div class="green"></div>
</section>
#photos{
position:absolute;
bottom:1em;
width:100px;
height:225px;
padding:3px;
overflow:hidden;
white-space:nowrap;
}
#photos div{
height:100%;
width:50px;
padding:3px;
display:inline-block;
position:relative;
border:1px solid black;
}
.red{background:red;}
.blue{background:blue;}
.green{background:green;}
And JavaScript:
scrollImages = function(){
var photoArea = $('#photos');
var children = photoArea.children();
var firstChild = $(children[0])
var firstOffset=firstChild.offset();
if(document.elementLeft === false){
document.elementLeft = firstOffset.left;
}
if(document.elementWidth === false){
document.elementWidth=firstChild.outerWidth(true);
}
if(firstOffset.left < 0 && (Math.abs(firstOffset.left) > Math.abs(document.elementWidth))){
photoArea.append(firstChild);
firstChild.css('margin-left', 0 + 'px')
children = photoArea.children();
firstChild = $(children[0])
firstOffset=firstChild.offset();
document.elementLeft = firstOffset.left;
document.elementWidth=firstChild.outerWidth(true);
}else{
}
document.elementLeft -= 1;
firstChild.css('margin-left', document.elementLeft + 'px');
t = setTimeout(scrollImages, 100);
}
document.elementLeft = false;
document.elementWidth = false;
var t = setTimeout(scrollImages, 500);
$('#photos').mouseover(function(){clearTimeout(t)});
$('#photos').mouseout(function(){scrollImages()})
});
If you remove the padding: 3px from #photos the animation works properly.