try to setTimeout to show and hide the balls - javascript

I tried to write a program to practice my js skills. There are 3 balls and they are hidden at first. I want the ball_1 shows up first, and after 1 sec, ball_1 disappears. Next, ball_2 shows up and after 1 sec it disappears; same logic goes with ball_3. When I run my code, the first two balls does not hide. I am not sure what is going wrong. The code below are the html, css, and js code that i wrote. Hope someone could help me out. Thank you in advance.
$(document).ready(function() {
var notes = ['ball_1', 'ball_2', 'ball_3'];
for (i = notes.length; i > 0; i--) {
var note = notes.shift();
$('#' + note).addClass('shown');
setTimeout(function() {
$('#' + note).removeClass('shown');
}, 1000);
}
});
#ball_1 {
width: 10px;
height: 10px;
background: #000000;
border: 2px solid #ccc;
border-radius: 50%;
}
#ball_2 {
width: 10px;
height: 10px;
background: #0000FF;
border: 2px solid #ccc;
border-radius: 50%;
}
#ball_3 {
width: 10px;
height: 10px;
background: #7FFF00;
border: 2px solid #ccc;
border-radius: 50%;
}
#ball_1,
#ball_2,
#ball_3 {
width: 10px;
height: 10px;
border: 2px solid #ccc;
border-radius: 50%;
}
.not_shown {
display: none;
}
.shown {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div id="ball">
<div id="ball_1" class="not_shown"></div>
<div id="ball_2" class="not_shown"></div>
<div id="ball_3" class="not_shown"></div>
</div>

In general never modify an array when iterating using a for loop. The shift method will remove the first item from the array thus modifying it's length. Instead do this:
$(document).ready(function() {
var notes = ['ball_1','ball_2','ball_3'];
var i; // You were declaring "i" in global namespace before. Don't do that.
for(i = 0; i < notes.length; i++){
var note = notes[i];
$('#' + note).addClass('shown');
setTimeout(function() {
$('#' + note).removeClass('shown');
},1000);
}
});
Also you will see from my note that you were defining "i" in the global namespace. It is never good to do that so always make sure to define your variables at the beginning of the function block if using "var".
EDIT: missed a semicolon
EDIT2: completely missed that i needed to change up the loop condition.

You are looking for an asnychronous play of events - first ball_1 shows up for 1 sec and after that ball_2 shows up for 1 sec and so forth.
Something like this won't work:
for( var i = 0; i < notes.length; i++){
$('#' + notes[i]).addClass('shown');
setTimeout(function() {
$('#' + notes[i]).removeClass('shown');
},1000);
}
because the timeouts will be registered one after the other in quick succession and all the balls will show up and hide in little over one second.
So you can create a callback and set the timeout for the next ball only after the previous ball has been shown fully for 1 sec - see demo below:
$(document).ready(function() {
var notes = ['ball_1', 'ball_2', 'ball_3'];
hideBall(notes,0);
});
function hideBall(notes,i) {
$('#' + notes[i]).addClass('shown');
hide(function() {
if(++i < notes.length) {
hideBall(notes,i);
}
}, notes[i]);
}
function hide(callback, note) {
setTimeout(function() {
$('#' + note).removeClass('shown');
callback();
}, 1000);
}
#ball_1 {
width: 10px;
height: 10px;
background: #000000;
border: 2px solid #ccc;
border-radius: 50%;
}
#ball_2 {
width: 10px;
height: 10px;
background: #0000FF;
border: 2px solid #ccc;
border-radius: 50%;
}
#ball_3 {
width: 10px;
height: 10px;
background: #7FFF00;
border: 2px solid #ccc;
border-radius: 50%;
}
#ball_1,
#ball_2,
#ball_3 {
width: 10px;
height: 10px;
border: 2px solid #ccc;
border-radius: 50%;
}
.not_shown {
display: none;
}
.shown {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div id="ball">
<div id="ball_1" class="not_shown"></div>
<div id="ball_2" class="not_shown"></div>
<div id="ball_3" class="not_shown"></div>
</div>

Hope this is what you need
$(document).ready(function() {
var notes = ['ball_1','ball_2','ball_3'];
for(i = notes.length; i > 0; i--){
var note = notes[i];
$('#' + note).addClass('shown');
hideBall(note, i)
}
});
function hideBall(note) {
setTimeout(function() {
$('#' + note).removeClass('shown');
},1000 * i);
}
#ball_1{
width: 10px;
height: 10px;
background: #000000;
border: 2px solid #ccc;
border-radius: 50%;
}
#ball_2{
width: 10px;
height: 10px;
background: #0000FF;
border: 2px solid #ccc;
border-radius: 50%;
}
#ball_3{
width: 10px;
height: 10px;
background: #7FFF00;
border: 2px solid #ccc;
border-radius: 50%;
}
#ball_1, #ball_2, #ball_3 {
width: 10px;
height: 10px;
border: 2px solid #ccc;
border-radius: 50%;
}
.not_shown {
display: none;
}
.shown {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "ball">
<div id = "ball_1" class = "not_shown"></div>
<div id = "ball_2" class = "not_shown"></div>
<div id = "ball_3" class = "not_shown"></div>
</div>

What you are trying won't work as it will run the for loop all in one go, setting up 3x timeouts.
try something like this
jQuery(document).ready(function($) {
function myBallLoop(){
// increment as needed
if(typeof note == 'undefined') {
var note = 1;
} else if (note == 3){
break; // end loop
} else {
note ++;
}
// show current ball qickly
$('#ball_' + note).show('fast', function(){
// call back after show event
// hide current ball after 1 sec
r = setTimeout(function(){$('#ball_' + note).hide()}, 1000);
// self call function after 2 seconts
t = setTimeout(function(){myBallLoop();, 2000}
});
}
// loop start
myBallLoop();
});

Take advantage of what jquery gives you.
Iterate using $.each is also the same as ES5's forEach. Using delay method to delay a function of adding classes is similar to setTimeout.
$(document).ready(() => {
var notes = ['ball_1','ball_2','ball_3'];
let showBalls = (i, item) => {
$('#' + item).delay(i * 1000).queue(() => {
$('#' + item).addClass('shown');
$('#' + notes[i - 1]).removeClass('shown').clearQueue();
});
}
$.each(notes, (i, item) => {
showBalls(i, item);
});
});
#ball_1{
width: 10px;
height: 10px;
background: #000000;
border: 2px solid #ccc;
border-radius: 50%;
}
#ball_2{
width: 10px;
height: 10px;
background: #0000FF;
border: 2px solid #ccc;
border-radius: 50%;
}
#ball_3{
width: 10px;
height: 10px;
background: #7FFF00;
border: 2px solid #ccc;
border-radius: 50%;
}
#ball_1, #ball_2, #ball_3 {
width: 10px;
height: 10px;
border: 2px solid #ccc;
border-radius: 50%;
}
.not_shown {
display: none;
}
.shown {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "ball">
<div id = "ball_1" class = "not_shown"></div>
<div id = "ball_2" class = "not_shown"></div>
<div id = "ball_3" class = "not_shown"></div>
</div>

Related

Is there a way to make this Javascript list ouput result to show images instead of numbers?

I am struggling on how to make the result output into images like: image 1, image 2 so on... Is there way to store all those images in the javascript and then show them on the result?
Here's the script of what i am talking about, please bear with me, i am learning and i am not an expert.
function proRangeSlider(sliderid, outputid, colorclass) {
var x = document.getElementById(sliderid).value;
document.getElementById(outputid).innerHTML = x;
document.getElementById(sliderid).setAttribute('class', colorclass);
updateTotal();
}
var total = 0;
function updateTotal() {
var list= document.getElementsByClassName("range");
[].forEach.call(list, function(el) {
console.log(el.value);
total += parseInt(el.value);
});
document.getElementById("n_total").innerHTML = total;
}
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(function() {
$('form').submit('click', function() {
$(this).hide();
$('html, body').animate({
scrollTop: $("#anchor").offset().top
}, 500);
$("#result").empty().append(
"<ul>" + Object.entries($('form').serializeObject()).map(e => `<li>${e[0]}: ${e[1]}`).join("") + "</ul>");
$(".hidden-block").show();
return false;
});
});
$(document).ready(function(){
$("#reset").click(function(){
location.reload(true);
});
});
Here's my project in case you would like to view the source: https://jsfiddle.net/archer201977/h9f6r21u/6/
I'm not sure what you mean by 'image' here, but maybe you want to display the slider within div#result?
Your code has some issues. To educate and entertain 😊 I've created a minimal reproducable example, presuming that by 'image' you mean the actual sliders. It
does not use jQuery
does not use inline event handling
does use event delegation
uses data attributes to be able to pass some state values etc.
document.addEventListener(`change`, handle);
updateTotal();
function handle(evt) {
if (evt.target.dataset.inputstate) {
return displayResult(evt.target);
}
}
function displayResult(origin) {
proRangeSlider(origin, ...origin.dataset.inputstate.split(`,`));
let totalValues = [];
document.querySelectorAll(`[data-inputstate]`).forEach(range => {
const rangeClone = createClone(range);
totalValues.push(`<li><div>${rangeClone}</div><div>${
range.dataset.name}: ${range.value}</div></li>`);
});
totalValues.push(`<li><div><b>Total: ${
document.querySelector(`#n_total`).textContent}</b></div></li>`);
document.querySelector(`#result`).innerHTML = `<ul>${totalValues.join(``)}</ul>`;
}
function createClone(fromRange) {
const clone = fromRange.cloneNode();
clone.setAttribute(`value`, fromRange.value);
clone.id = ``;
clone.removeAttribute(`data-inputstate`);
return clone.outerHTML;
}
function proRangeSlider(origin, outputId, colorclass) {
origin.closest(`div`).querySelector(`#${outputId}`).textContent = origin.value;
origin.setAttribute('class', colorclass);
updateTotal();
}
function updateTotal() {
let total = 0;
[...document.querySelectorAll(`[data-inputstate]`)]
.forEach(elem => total += +elem.value);
document.getElementById("n_total").textContent = total;
}
body,
html {
margin: 10px;
}
#proRangeSlider {
border: 1px solid #CCC;
padding: 0;
}
div {
background: #f1f1f1;
border-bottom: 1px dotted #666;
padding: 2px 0px;
}
div:last-child {
border: none;
}
input {
-webkit-appearance: none;
width: 160px;
height: 15px;
background: linear-gradient(to right, #16a085 0%, #16a085 100%);
background-size: 150px 10px;
background-position: center;
background-repeat: no-repeat;
overflow: hidden;
outline: none;
vertical-align: middle;
}
input::-webkit-slider-thumb {
-webkit-appearance: none;
width: 15px;
height: 15px;
border-radius: 50%;
background: #27ae60;
position: relative;
z-index: 3;
}
#total {
padding-left: 7px;
}
.blue::-webkit-slider-thumb {
background: #2980b9;
}
.orange::-webkit-slider-thumb {
background: #d35400;
}
#result {
margin-bottom: 0;
border: none;
padding: 5px;
background-color: transparent;
}
#result ul {
margin-left: -1.5rem;
}
#result ul li div {
display: inline-block;
vertical-align: middle;
background-color: transparent;
border: none;
padding: 0 3px;
}
#result ul li div input[type=range] {
height: auto;
margin-left: -0.4rem;
}
#result ul li {
text-align: left;
}
<div id="proRangeSlider">
<div id="total">TOTAL: <span id="n_total"></span></div>
<div>
<input type="range" data-name="Cost per day" class="range orange" value="20" data-inputstate="output1,orange">
<output id="output1">20</output>
</div>
<div>
<input type="range" data-name="Number of days" value="50" class="blue range" data-inputstate="output2,blue">
<output id="output2">50</output>
</div>
</div>
<div id="result"></div>
But ... you meant to create an image from some number, ok. This snippet may help. It uses an image sprite for the numbers.
const createNumber = nr => {
const numbers = `zero,one,two,three,four,five,six,seven,eight,nine`
.split(`,`);
return [...`${nr}`]
.map(n => `<div class="number ${numbers[n]}"></div>`)
.join(``);
}
const example = nr => document.body.insertAdjacentHTML(
`beforeend`,
`<div class="example">${nr} => ${createNumber(nr)}</p>`);
example(1234567890);
example(233);
example(732);
example(1854);
example(42);
.example {
height: 32px;
}
.example .number {
vertical-align: middle;
}
.number {
background-image: url('//sdn.nicon.nl/tests/numbers.png');
background-repeat: no-repeat;
width: 14px;
height: 16px;
display: inline-block;
border: 1px solid #aaa;
padding: 1px;
margin: 0 1px
}
.number.zero {
background-position: 3px 1px;
}
.number.one {
background-position: -25px 1px;
}
.number.two {
background-position: -51px 1px
}
.number.three {
background-position: -77px 1px
}
.number.four {
background-position: -103px 1px
}
.number.five {
background-position: -129px 1px
}
.number.six {
background-position: -155px 1px
}
.number.seven {
background-position: -183px 1px
}
.number.eight {
background-position: -209px 1px
}
.number.nine {
background-position: -235px 1px
}

Can't overwrite CSS property with jQuery, what's wrong with my code?

I'm working on the jQuery project in The Odin Project curriculum. I've managed to create a grid inside a container that changes the color of it's boxes but I want to be able to increase the amount of boxes without popping out of the container. I think I can manage if I overwrite the css properties of the boxes with jQuery but can't figure out why it's not working.
Here's my code:
$(document).ready(function grid(boxes)
{
//Declare how many boxes in the grid.
var boxes = prompt("Choose gridsize");
//Resize boxes assigning css.
var rcsize = Math.floor(400/boxes - 3);
$('.row').css('width: ' + rcsize + 'px');
$('.row').css('height: ' + rcsize + 'px');
//Create grid.
var $row = $('<div class="row"></div>');
var $col = $('<div class="col"></div>');
for (var i = 0; i < boxes; i++) {
$row.append($col.clone());
}
for (var i = 0; i < boxes; i++) {
$("#outerbox").append($row.clone());
}
$('.col').on('hover', function() {
$(this).addClass('colon');
});
//Add functionality to navbar buttons.
$("#g").click(function() {
prompt("Choose gridsize");
});
$("#r").click(function() {
alert("sup");
});
$("#c").click(function() {
prompt("Choose color: black, red or blue");
});
});
Here's my CSS:
.body {
width: 100%;
height: 100%;
background-color: #a79696;
position: absolute;
margin: 0 0 0 0;
overflow-x: hidden;
}
.titlelogo {
background-color: #e38f52;
height: 25px;
width: 100%;
padding: 30px 0 30px 0;
}
#logo {
margin: 0 0 0 0;
width: 30%;
font-size: 20px;
}
#navbar0 {
margin-top: 0;
padding: 0;
background-color: #483f47;
}
.navbar1 {
display: inline;
text-decoration-color: white;
}
button {
margin-left: 45px;
margin-right: 45px;
background-color: #ffffff80;
}
#outerbox {
width: 400px;
height: 400px;
margin: 50px;
border-radius: 10px;
background-color: #e38f52;
padding: 12px 0px 0px 12px;
}
.row {
display: inline-block;
float: left;
padding: 1px;
}
.col {
height: 22px;
width: 22px;
margin: 0px;
outline: 1px solid;
outline-color: #000;
float: left;
background: #e38f52;
display: inline-block;
padding: 1px;
}
.colon {
background: #000;
}
The hover is not working on jsfiddle but it works on my index file for some reason. Thank you in advance.
jsfiddle
use css function as below
$('.row').css('width' , rcsize + 'px');
$('.row').css('height' , rcsize + 'px');
For reference check this link http://api.jquery.com/css/
you have typo in class. right here
//create grid
var $row = $('<div clas="row"></div>');
it should be
//create grid
var $row = $('<div class="row"></div>');

JQuery Traversing through DOM on click

I am having problem of traversing through each HTML element one by one.There are two buttons #up and #down.On click of #up the id #myID should move to the next element upwards and vice versa for #down.The problem is I am able to move through the siblings but not through the child elements.
For example if I click on #down the id #myID should have moved to p tag which is the child of that div on next click to span which is child of p then on next click to div.But in my code it is directly jumping to div ignoring the children.
JSFIDDLE
Here is the code:
$("#up").click(function() {
$("#startHere").find("#myID").next().attr('id', 'myID');
$('#startHere').find("#myID").removeAttr('id');
});
$("#down").click(function() {
$("#startHere").find("#myID").prev().attr('id', 'myID');
$('#startHere').find("#myID").next().removeAttr('id');
})
#myID {
border: 2px solid yellow;
}
#startHere {
height: 100%;
width: 50%;
}
div {
height: 100px;
width: 100px;
border: 2px solid;
margin: 10px;
}
p {
height: 50px;
width: 50px;
border: 2px solid blue;
margin: 10px;
}
h1 {
height: 40px;
width: 40px;
border: 2px solid red;
margin: 10px;
}
span {
display: block;
height: 25px;
width: 25px;
border: 2px solid green;
margin: 10px;
}
button {
height: 25px;
width: 100px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="up">GO DOWN</button>
<button id="down">GO UP</button>
<div id="startHere">
<div id="myID">
<p><span></span></p>
</div>
<div><span></span></div>
<div>
<h1></h1>
</div>
<p></p>
<h1></h1>
<p><span></span></p>
</div>
I think you can just find all the elements first, jQuery returns them in DOM order, which is what you want. No need to search for the next/prev element on-the-fly.
var allElements = $("#startHere").find('*');
var currentIndex = allElements.index('#myID');
function move(delta) {
// Find the new index
var index = currentIndex + delta;
// Clamp to 0…lengh of list
// Here we could also make it wrap instead
index = Math.max(Math.min(index, allElements.length - 1), 0);
// Remove the ID from the old element
allElements.eq(currentIndex).removeAttr('id');
// Add the ID to the new element
allElements.eq(index).attr('id', 'myID');
// Update the index
currentIndex = index;
}
$("#up").click(function() {
move(1);
});
$("#down").click(function() {
move(-1);
})
var allElements = $("#startHere").find('*');
var currentIndex = allElements.index('#myID');
function move(delta) {
// Find the new index
var index = currentIndex + delta;
// Clamp to 0…lengh of list
// Here we could also make it wrap instead
index = Math.max(Math.min(index, allElements.length - 1), 0);
// Remove the ID from the old element
allElements.eq(currentIndex).removeAttr('id');
// Add the ID to the new element
allElements.eq(index).attr('id', 'myID');
// Update the index
currentIndex = index;
}
$("#up").click(function() {
move(-1);
});
$("#down").click(function() {
move(1);
})
#myID {
border: 2px solid yellow;
}
#startHere {
height: 100%;
width: 50%;
}
div {
height: 100px;
width: 100px;
border: 2px solid;
margin: 10px;
}
p {
height: 50px;
width: 50px;
border: 2px solid blue;
margin: 10px;
}
h1 {
height: 40px;
width: 40px;
border: 2px solid red;
margin: 10px;
}
span {
display: block;
height: 25px;
width: 25px;
border: 2px solid green;
margin: 10px;
}
button {
height: 25px;
width: 100px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="down">GO DOWN</button>
<button id="up">GO UP</button>
<div id="startHere">
<div id="myID">
<p><span></span></p>
</div>
<div><span></span></div>
<div>
<h1></h1>
</div>
<p></p>
<h1></h1>
<p><span></span></p>
</div>
If you do need the elements on-the-fly (because they might have changed), you can still use the same tactic (and simply build up the allElements list in the move function and get the index using allElements.index('#myID')) but it might be more performant to update the list only when you know it changed (after an Ajax request, after modification on event handlers, etc.).
Edit:
The code for searching the next/prev element on-the-fly is a bit more work because it has to recurse when traversing up but makes it possible to have a different set of rules for up vs. down movement.
var boundary = $("#startHere");
function findNext(node, anchor) {
if(!anchor && node.children(':first-child').length) {
return node.children(':first-child');
}
if(node.next().length) {
return node.next();
}
if(!boundary.find(node.parent()).length) {
// Out of boundary. Stick to the last node
return anchor||node;
}
return findNext(node.parent(), anchor||node);
}
function findPrev(node, anchor) {
if(!anchor && node.children(':last-child').length) {
return node.children(':last-child');
}
if(node.prev().length) {
return node.prev();
}
if(!boundary.find(node.parent()).length) {
// Out of boundary. Stick to the last node
return anchor||node;
}
return findPrev(node.parent(), anchor||node);
}
function move(finder) {
// Find the current item
var current = boundary.find('#myID');
// Find the next item
var next = finder(current);
// Remove the ID from the old element
current.removeAttr('id');
// Add the ID to the new element
next.attr('id', 'myID');
}
$("#up").click(function() {
move(findPrev);
});
$("#down").click(function() {
move(findNext);
})
var boundary = $("#startHere");
function findNext(node, anchor) {
if(!anchor && node.children(':first-child').length) {
return node.children(':first-child');
}
if(node.next().length) {
return node.next();
}
if(!boundary.find(node.parent()).length) {
// Out of boundary. Stick to the last node
return anchor||node;
}
return findNext(node.parent(), anchor||node);
}
function findPrev(node, anchor) {
if(!anchor && node.children(':last-child').length) {
return node.children(':last-child');
}
if(node.prev().length) {
return node.prev();
}
if(!boundary.find(node.parent()).length) {
// Out of boundary. Stick to the last node
return anchor||node;
}
return findPrev(node.parent(), anchor||node);
}
function move(finder) {
// Find the current item
var current = boundary.find('#myID');
// Find the next item
var next = finder(current);
// Remove the ID from the old element
current.removeAttr('id');
// Add the ID to the new element
next.attr('id', 'myID');
}
$("#up").click(function() {
move(findPrev);
});
$("#down").click(function() {
move(findNext);
})
#myID {
border: 2px solid yellow;
}
#startHere {
height: 100%;
width: 50%;
}
div {
height: 100px;
width: 100px;
border: 2px solid;
margin: 10px;
}
p {
height: 50px;
width: 50px;
border: 2px solid blue;
margin: 10px;
}
h1 {
height: 40px;
width: 40px;
border: 2px solid red;
margin: 10px;
}
span {
display: block;
height: 25px;
width: 25px;
border: 2px solid green;
margin: 10px;
}
button {
height: 25px;
width: 100px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="down">GO DOWN</button>
<button id="up">GO UP</button>
<div id="startHere">
<div id="myID">
<p><span></span></p>
</div>
<div><span></span></div>
<div>
<h1></h1>
</div>
<p></p>
<h1></h1>
<p><span></span></p>
</div>
This is really bad UI. To select some nodes in some states, you first have to navigate “UP” and then “DOWN” again. But it seems to do what you ask for.

Trouble applying CSS changes to dynamically created via JS/JQuery

I've been trying to alter the size of my ".square" divs that are created using JS/JQuery. I've successfully changed the size of the container div, but using the exact same code does not work for the dynamically created .square divs, despite being able to apply events the .square divs in other ways.
I've been trying to understand the problem for the last two days, and have been writing and rewriting solutions, but I think my current skills are overlooking a very simple answer.
The aim was to have the .square divs' size be determined by how many squares will be in the container. The more squares, the smaller the .square div css.
Thanks for any help anyone can give.
$(document).ready(function() {
var create = function(king) {
return $("#container").prepend("<div class='square' id=king></div>");
}
var sLoad = function() {
for (i = 0; i < 16; i++) {
$("#16").click(function() {
$("#container").prepend("<div class='square'></div>");
});
};
};
sLoad();
$("#clear").on("click", function() {
$(".square").remove();
num = prompt("How many squares would you like?");
// var containerSize = function(){
// var siz = 112 * num;
// $("#container").css({"height": siz+15+"px" , "width": siz+"px"});
// }
// containerSize()
$(".square").css({
"height": "50px",
"width": "50px"
});
var make = function(num) {
return num * num;
};
//var squareSize = function(){
// var sqr = 600 / make(num);
// $(".square").css({"height":sqr+"px" , "width":sqr+"px"});
//};
//squareSize();
for (i = 0; i < make(num); i++) {
$("#container").prepend("<div class='square'></div>");
};
});
// $(".button").click(function(){
//
//making the square dis and reappear
$("#container").on("mouseenter", function() {
$(".square").mouseenter(function() {
$(this).fadeTo("fast", 0);
}),
$(".square").mouseleave(function() {
$(this).fadeTo("fast", 1);
});
});
});
#menuContainer {
height: 45px;
width: 50%;
margin: auto;
}
#container {
width: 600px;
height: 600px;
border: 1px blue dotted;
border-radius: 2%;
margin: auto;
padding: 0px;
}
#controlDiv {
height: 30px;
width: 30px;
border: 1px dashed red;
margin: auto;
margin-top: 50%;
background-color: black;
}
.square {
width: 100px;
height: 100px;
background-color: grey;
border: 1px black dashed;
border-radius: 3%;
margin: 5px 5px 5px 5px;
display: inline-block;
}
.button {
height: 27px;
width: 70px;
background-color: gold;
border: solid 1px yellow;
text-decoration-color: blue;
border-radius: 5%;
text-align: center;
padding-top: 7px;
/*margin: auto;*/
margin-bottom: 4px;
display: inline-block;
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div id="menuContainer">
<div class="button" id="16">Click</div>
<div class="button" id="clear">Clear</div>
</div>
<div id="container">
<!-- <div id="controlDiv"></div> -->
</div>
<!--<div class="square"></div>-->
</body>
</html>
This fiddle should work : https://jsfiddle.net/x0x9rv30/2/
You applied the CSS on removed elements, you need to create the elements first, then you can apply CSS on it.
I just swapped two code blocks :
Before
$(".square").remove();
$(".square").css({"height":"50px" , "width": "50px"});
for (i = 0; i < make(num); i++){
$("#container").prepend("<div class='square'></div>");
};
After
$(".square").remove();
for (i = 0; i < make(num); i++){
$("#container").prepend("<div class='square'></div>");
};
$(".square").css({"height":"50px" , "width": "50px"});

How to hide css while clicking another

I want to hide black arrow while clicking green arrow.. without using jquery
My fiddle:
http://jsfiddle.net/t5Nf8/195/
html:
<div class="arrow-down"></div>
<div class="arrow-up"></div>
css:
.arrow-down {
position: absolute;
/*display: none;*/
left: 1.5px;
top: 6px;
z-index: 1;
width: 0;
height: 0;
border-left: 8px solid transparent;
border-right: 8px solid transparent;
border-top: 8px solid #0ef2c4;
cursor: pointer;
}
.arrow-up {
border-color: transparent transparent black;
border-style: dashed dashed solid;
border-width: 0px 8.5px 8.5px;
position: absolute;
left: 1.5px;
top: 14px;
z-index: 1;
height: 0px;
width: 0px;
}
js:
$('.arrow-up').click(function {
$('.arrow-down').hide();
});
Please anyone help
$('.arrow-down').click(function(){
$('.arrow-up').toggle();
});
$('.arrow-up').click(function(){
$('.arrow-down').toggle();
});
You had a syntax error in your Code after function you should have
() which you missed in your Code
I Have used toggle so that it shows and hides but you can use hide alone if you want.
DEMO
According to #JoeFitter's answer, you can toggle the "upArrow" to show and hide by clicking the "downArrow" using JavaScript
var downArrow = document.getElementsByClassName('arrow-down')[0];
var upArrow = document.getElementsByClassName('arrow-up')[0];
downArrow.addEventListener('click', function() {
if(upArrow.style.display == 'none'){
upArrow.style.display = 'block';
}
else{
upArrow.style.display = 'none';
}
});
Live Demo
var downArrow = document.getElementsByClassName('arrow-down')[0];
var upArrow = document.getElementsByClassName('arrow-up')[0];
downArrow.addEventListener('click', function() {
upArrow.style.display = upArrow.style.display !== 'none' ? 'none' : 'block';
});
http://jsfiddle.net/t5Nf8/197/
Use getComputedStyle(el).getPropertyValue("display"); to get the value of dispaly, after, you just do a test to show or hide your arrow!
Note: it's a pure Javascript, no library:
var display = getComputedStyle(up).getPropertyValue("display");
if ( display !== "block" ) {
up.style.display = 'block';
} else {
up.style.display = 'none';
}
Want to watch it in action? See demo: http://jsfiddle.net/g4g9doj0/
I don't think it is a simple task JUST using CSS, using Jquery should look like:
I don't know but I see useless CSS instructions, I think it could be reduce to:
.arrow-down {
border-color: transparent transparent black;
border-style: dashed dashed solid;
border-width: 0px 8.5px 8.5px;
height: 0px;
width: 0px;
}
.arrow-up{
width: 0;
height: 0;
border-left: 8px solid transparent;
border-right: 8px solid transparent;
border-top: 8px solid #0ef2c4;
cursor: pointer;
}
Jquery would look like:
$(document).ready(function(){
$(".arrow-up").click(function(){
$(".arrow-down").hide();
});
});
http://jsfiddle.net/t5Nf8/209/

Categories