How do I loop multiple scripts in javascript? - javascript

I have some code here and I want the squares to go blue, green, indigo then go back to the beginning. Each time I click the button the colour will change. The code here goes blue, green, indigo and then changes between indigo and black while I want it to go to blue again. Is there a way of restarting the entire code again?
<--code for animated squares!-->
<!DOCTYPE html>
<html>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: Black;
}
div#animate {
width: 50px;
height: 50px;
position: absolute;
left: 175px;
top: 0px;
background-color: Blue;
}
</style>
<style>
#containertwo {
width: 400px;
height: 400px;
position: relative;
background: Black;
}
div#animatetwo {
width: 50px;
height: 50px;
position: absolute;
left: 175px;
top: 175px;
background-color: Black;
}
</style>
<body>
<style>
#containerthree {
width: 400px;
height: 400px;
position: relative;
background: Black;
}
div#animatethree {
width: 50px;
height: 50px;
position: absolute;
left: 175px;
top: 350px;
background-color: Black;
}
</style>
<body>
<p>
<button onClick="button_click();button_clicktwo();button_clickthree()">Change Colour</button>
</p>
<div id ="container">
<div id ="animate"></div>
<div id ="animatetwo"></div>
<div id ="animatethree"></div>
</div>
<div id="box" onClick="button_click(j)();"></div>
<script>
var colors = ["Black","Black","Blue"];
function button_click() {
var box = document.getElementById("animate");
var background_color = box.style.backgroundColor;
var i = colors.indexOf(background_color);
if (i === colors.length-1) {
i = -1;
}
animate.style.backgroundColor = colors[i+1];
}
</script>
<div id="box" onClick="button_clicktwo();"></div>
<script>
var colorstwo = ["Green","Black","Black",];
function button_clicktwo() {
var box = document.getElementById("animatetwo");
var background_color = box.style.backgroundColor;
var i = colorstwo.indexOf(background_color);
if (i === colorstwo.length-1) {
i = -1;
}
animatetwo.style.backgroundColor = colorstwo[i+1];
}
</script>
<div id="box" onClick="button_clickthree();"></div>
<script>
var colorsthree = ["Black","Indigo","Black"];
function button_clickthree() {
var box = document.getElementById("animatethree");
var background_color = box.style.backgroundColor;
var i = colorsthree.indexOf(background_color);
if (i === colorstwo.length-1) {
i = -1;
}
animatethree.style.backgroundColor = colorsthree[i+1];
}
</script>

There's quite a bit of invalid and repetitive code, so for simplicity, I just reworked the entire thing. I'll note some of the problems below.
Since there were so many changes made to the HTML, CSS and JS, I won't list them all, but will leave it to you to observe the differences.
// Gather the colors and elements, and set a shared `i` to `0`
var colors = ["Blue", "Green", "Indigo"];
var elems = document.querySelectorAll(".animate");
var i = 0;
// Have a single function that makes the current element black and the next
// one a different color
function button_click() {
elems[i].style.backgroundColor = "Black";
if (++i === colors.length) {
i = 0
}
elems[i].style.backgroundColor = colors[i];
}
#container {
width: 400px;
height: 400px;
position: relative;
background: Black;
}
.animate {
width: 50px;
height: 50px;
left: 175px;
position: absolute;
}
.animate:nth-child(1) {
top: 0px;
background-color: Blue;
}
.animate:nth-child(2) {
top: 175px;
}
.animate:nth-child(3) {
top: 350px;
}
<p>
<button onClick="button_click();">Change Colour</button>
</p>
<div id="container">
<div class="animate"></div>
<div class="animate"></div>
<div class="animate"></div>
</div>
Note that there are other ways to do this too, like having each color set in the CSS, and then setting the visibility to hidden or visible with JavaScript.
Some of the general problems were:
the same ID attribute used more than once
an extra <body> tag
lots of repeating CSS, JS and HTML that was able to be greatly reduced

Related

Changing position of absolute element without container overflow

Maybe an obvious question but how do I make an element with a absolute position not overflow its container when moving it's position right? I know I could change it to relative position or move it 99% but for my project that won't due. I tried using margins, padding, object-fit, all with no success. Thanks for any help
var green = document.getElementById('green');
function myFunct() {
green.style.right = '100%';
}
h1 {
position: relative;
width: 80%;
height: 100px;
margin: auto;
background-color: red;
}
#green {
position: absolute;
right: 0px;
height: 100px;
background-color: green;
width: 20px;
}
<h1>
<div id = 'green'></div>
</h1>
<button onclick="myFunct()">FindHighScore</button>
Use CSS calc()
var green = document.getElementById("green");
function myFunct() {
green.style.right = "calc(100% - 20px)";
}
Or, apply left: 0 and right: auto (reset)
var green = document.getElementById("green");
function myFunct() {
green.style.left = "0";
green.style.right = "auto";
}
A <div> should not be in a <h1> tag by the way.
You can set overflow to hidden at parent container.
<h1> permitted content is Phrasing content
var green = document.getElementById('green');
function myFunct() {
green.style.right = '100%';
}
div:not(#green) {
position: relative;
width: 80%;
height: 100px;
margin: auto;
background-color: red;
overflow: hidden;
}
#green {
position: absolute;
right: 0px;
height: 100px;
background-color: green;
width: 20px;
}
<div>
<div id='green'></div>
</div>
<button onclick="myFunct()">FindHighScore</button>

I am not able to add and remove the classes

My Code:
window.addEventListener('scroll', scrollWhere);
function scrollWhere(e) {
var windowScroll = $(window).scrollTop();
var idScroll = $('.me').offset().top;
var height = $("#half-who").height();
if (windowScroll > idScroll) {
$('.me').addClass('me-fixed');
} else {
$('.me').removeClass('me-fixed');
}
}
I want to add a class when the scroll is past a certain point and remove it when is smaller than that certain point.
Get your idScroll value outside scrollWhere function as because it re-initiate calculation again and again and returns different values each time as because it has a fixed position. check below snippet for reference.
window.addEventListener('scroll', scrollWhere);
var idScroll = $('.me').offset().top;
function scrollWhere(e) {
var windowScroll = $(window).scrollTop();
//var height = $("#half-who").height();
if (windowScroll > idScroll) {
$('.me').addClass('me-fixed');
} else {
$('.me').removeClass('me-fixed');
}
}
.container {
height: 300vh;
width: 100%;
background-color: grey;
padding: 0;
margin: 0;
}
.content {
height: 100px;
width: 100%;
background-color: cyan;
}
.me {
height: 50px;
width: 100%;
background-color: red;
}
.me-fixed {
position: fixed;
top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="content"></div>
<div class="me"></div>
</div>
Here's a simple example to add a class when scroll passing a certain point. Hope you can get an idea. >>> JSFiddle
$(window).scroll(function(){
var winH = $(window).scrollTop();
var ruler = $('.ruler').position().top;
if(ruler < winH){
$('.nav').addClass('me-fixed');
}
else{
$('.nav').removeClass('me-fixed');
}
});
body{
height: 1500px;
}
.nav{
height: 50px;
background: #a1bfbe;
color: #000;
width: 100%;
position: relative;
top: 250px;
text-align: center;
}
.nav.me-fixed{
background: #c2debf;
}
p{
font-size: 20px;
display: none;
}
.me-fixed p{
display: block;
}
.ruler{
position: fixed;
top: 150px;
border-bottom: 1px solid red;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nav">
<p>
Fixed
</p>
</div>
<div class="ruler">
</div>
Also if you can provide the html and css structure, it will be easy to identify the issue.

onClick javascript function shows only first child of wrapper

I am learning javascript these days and I have a little problem with my code.
I have three elements on page wrapper1, wrapper2 and wrapper3 and every of these has its triggerand redbox element.
My goal is when the trigger is hit, it will show the redbox element corresponding to number.
Examples:
clicking trigger1 inside wrapper1 element shows up redbox1 element,
trigger2 inside wrapper2 element shows up redbox2 element etc.
The problem is, when I click on trigger3 for example it always shows redbox1 element. (as example shows).
What I am doing wrong? I am just a begginer.
function showTheRedBox() {
var theRedBox = document.getElementsByClassName('redbox');
theRedBox[0].style.display = 'block';
}
body {background: #222;}
.wrapper {
background: yellow;
width: 100px;
height: 100px;
}
.trigger {
background: blue;
width: 50px;
height: 50px;
position: absolute;
margin-top: 50px;
margin-left: 50px;
}
.redbox {
background: red;
width: 200px;
height: 100px;
margin-left: 100px;
position: absolute;
display: none;
}
<div class="wrapper">
<div class="trigger" onclick="showTheRedBox();">trigger1</div>
<div class="redbox">hurrah1</div>
wrapper1</div>
<div class="wrapper">
<div class="trigger" onclick="showTheRedBox();">trigger2</div>
<div class="redbox">hurrah2</div>
wrapper2</div>
<div class="wrapper">
<div class="trigger" onclick="showTheRedBox();">trigger3</div>
<div class="redbox">hurrah3</div>
wrapper3</div>
You can use a for loop and a closure to access the .wrapper information for each onclick event. This method will work whether there are the same amount of children or not, and will always show the correct child.
Also, it is best to not use inline JavaScript attributes (e.g. onclick="showTheRedBox();") you should always assign your event handlers in your script for readability and maintainability.
var wrappers = document.querySelectorAll('.wrapper'), i;
var redboxes = document.querySelectorAll('.redbox');
for(i = wrappers.length - 1; i >= 0; --i) {
(function(wrapper){
wrapper.querySelector('.trigger').onclick = function() {
hideAll();
wrapper.querySelector('.redbox').style.display = 'block';
}
})(wrappers[i]);
}
function hideAll() {
for(i = redboxes.length - 1; i >= 0; --i) {
redboxes[i].style.display = 'none';
}
}
var wrappers = document.querySelectorAll('.wrapper'), i;
var redboxes = document.querySelectorAll('.redbox');
for(i = wrappers.length - 1; i >= 0; --i) {
(function(wrapper){
wrapper.querySelector('.trigger').onclick = function() {
hideAll();
wrapper.querySelector('.redbox').style.display = 'block';
}
})(wrappers[i]);
}
function hideAll() {
for(i = redboxes.length - 1; i >= 0; --i) {
redboxes[i].style.display = 'none';
}
}
body {background: #222;}
.wrapper {
background: yellow;
width: 100px;
height: 100px;
}
.trigger {
background: blue;
width: 50px;
height: 50px;
position: absolute;
margin-top: 50px;
margin-left: 50px;
}
.redbox {
background: red;
width: 200px;
height: 100px;
margin-left: 100px;
position: absolute;
display: none;
}
<div class="wrapper">
<div class="trigger">trigger1</div>
<div class="redbox">hurrah1</div>
wrapper1</div>
<div class="wrapper">
<div class="trigger">trigger2</div>
<div class="redbox">hurrah2</div>
wrapper2</div>
<div class="wrapper">
<div class="trigger">trigger3</div>
<div class="redbox">hurrah3</div>
wrapper3</div>
This method will also work, but it will use more memory as it queries the DOM once more than the above solution.
var wrappers = document.querySelectorAll('.wrapper'), i;
var redboxes = document.querySelectorAll('.redbox');
for(i = wrappers.length - 1; i >= 0; --i) {
wrappers[i].querySelector('.trigger').onclick = function() {
hideAll();
this.parentNode.querySelector('.redbox').style.display = 'block';
}
}
function hideAll() {
for(i = redboxes.length - 1; i >= 0; --i) {
redboxes[i].style.display = 'none';
}
}
var wrappers = document.querySelectorAll('.wrapper'), i;
var redboxes = document.querySelectorAll('.redbox');
for(i = wrappers.length - 1; i >= 0; --i) {
wrappers[i].querySelector('.trigger').onclick = function() {
hideAll();
this.parentNode.querySelector('.redbox').style.display = 'block';
}
}
function hideAll() {
for(i = redboxes.length - 1; i >= 0; --i) {
redboxes[i].style.display = 'none';
}
}
body {background: #222;}
.wrapper {
background: yellow;
width: 100px;
height: 100px;
}
.trigger {
background: blue;
width: 50px;
height: 50px;
position: absolute;
margin-top: 50px;
margin-left: 50px;
}
.redbox {
background: red;
width: 200px;
height: 100px;
margin-left: 100px;
position: absolute;
display: none;
}
<div class="wrapper">
<div class="trigger">trigger1</div>
<div class="redbox">hurrah1</div>
wrapper1</div>
<div class="wrapper">
<div class="trigger">trigger2</div>
<div class="redbox">hurrah2</div>
wrapper2</div>
<div class="wrapper">
<div class="trigger">trigger3</div>
<div class="redbox">hurrah3</div>
wrapper3</div>
The problem you have was that the method "getElementsByClassName", returns you an Array that contains all the elements of that class. So, when you where doing this:
theRedBox[0].style.display = 'block'
You were changing the display style of the First element of the Array, in this case "wrapper1".
Here's a modify version that functions whit the others wrappers:
<!DOCTYPE html>
<html lang = 'es'>
<head>
<title> MY TEST </title>
<style>
body {
background: #222;
}
.wrapper {
background: yellow;
width: 100px;
height: 100px;
}
.trigger {
background: blue;
width: 50px;
height: 50px;
position: absolute;
margin-top: 50px;
margin-left: 50px;
}
.redbox {
background: red;
width: 200px;
height: 100px;
margin-left: 100px;
position: absolute;
display: none;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="trigger" onclick="showTheRedBox(0)">trigger1</div> <!-- When the onClick event is trigered the function "showTheRedBox receives a parameter , that parameter is the position of the element in the Array "theRedBox"-->
<div class="redbox">hurrah1</div>
wrapper1
</div>
<div class="wrapper">
<div class="trigger" onclick="showTheRedBox(1)">trigger2</div>
<div class="redbox">hurrah2</div>
wrapper2
</div>
<div class="wrapper">
<div class="trigger" onclick="showTheRedBox(2)">trigger3</div>
<div class="redbox">hurrah3</div>
wrapper3</div>
<script>
function showTheRedBox(wrapperNumber) {
var theRedBox = document.getElementsByClassName('redbox');
theRedBox[wrapperNumber].style.display = 'block';
}
</script>
</body>
</html>

multiple pop up div's in the same page

In one of my projects, I have requirement of multiple pop up div's on the same page. That means when user clicks on a link, some content should open in a pop up. There will be many such links with their own pop ups. With little knowledge of javascript, I have tried to write a javascript for it but it works only for one pop up. When I click on second, third... links, only first pop up opens rather than opening second, third... pop ups. Here is my code. Please tell the modifications to it.
<!DOCTYPE html>
<html >
<head>
<script>
window.document.onkeydown = function (e)
{
if (!e)
{
e = event;
}
if (e.keyCode == 27)
{
lightbox_close();
}
}
function lightbox_open()
{
window.scrollTo(0,0);
document.getElementById('light').style.display='block';
document.getElementById('fade').style.display='block';
}
function lightbox_close()
{
document.getElementById('light').style.display='none';
document.getElementById('fade').style.display='none';
}
</script>
<style>
#fade
{
display: none;
position: fixed;
top: 0%;
left: 0%;
width: 100%;
height: 100%;
background-color: #000;
z-index:1001;
-moz-opacity: 0.7;
opacity:.70;
filter: alpha(opacity=70);
}
#light
{
display: none;
position: absolute;
top: 50%;
left: 50%;
width: 300px;
height: 200px;
margin-left: -150px;
margin-top: -100px;
padding: 10px;
border: 2px solid #FFF;
background: #CCC;
z-index:1002;
overflow:visible;
}
</style>
</head>
<body>
Open 1
<div id="light">div 1</div>
<div id="fade" onClick="lightbox_close();"></div>
Open 2
<div id="light">div 2</div>
<div id="fade" onClick="lightbox_close();"></div>
Open 3
<div id="light">div 3</div>
<div id="fade" onClick="lightbox_close();"></div>
</body>
</html>
Here's a way to achieve what you want. I'm sure it can be improved, but it's up to you then.
First, IDs should be unique across the page. If you want to group elements, give them a shared class instead.
With the changes, your HTML would look like this:
Open 1
<div class="light">div 1</div>
<div class="fade" onClick="lightbox_close()"></div>
Open 2
<div class="light">div 2</div>
<div class="fade" onClick="lightbox_close()"></div>
Open 3
<div class="light">div 3</div>
<div class="fade" onClick="lightbox_close()"></div>
Your CSS:
html, body {
width: 100%;
height: 100%;
}
.fade {
display: none;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: #000;
z-index:1001;
-moz-opacity: 0.7;
opacity:.70;
filter: alpha(opacity=70);
}
.light {
display: none;
position: absolute;
top: 50%;
left: 50%;
width: 300px;
height: 200px;
margin-left: -150px;
margin-top: -100px;
padding: 10px;
border: 2px solid #FFF;
background: #CCC;
z-index:1002;
overflow:visible;
}
And your Javascript:
window.document.onkeydown = function (e) {
if (!e) {
e = event;
}
if (e.keyCode == 27) {
lightbox_close();
}
}
// Note that the function is receiving the clicked element reference.
function lightbox_open(el) {
window.scrollTo(0,0);
// All the anchors that have a class lightbox.
var anchors = document.querySelectorAll('a.lightbox');
// All the elements with class light.
var light = document.querySelectorAll('.light');
// All the elements with class fade.
var fade = document.querySelectorAll('.fade');
// Iterate over the anchors elements.
for (var i = 0; i < anchors.length; i++) {
// If the anchor matches the clicked one.
if (anchors[i] == el) {
// Look for the light and fade with the same index
// and display them.
light[i].style.display = 'block';
fade[i].style.display = 'block';
}
}
}
function lightbox_close() {
// All the elements with class light or fade.
var els = document.querySelectorAll('.light, .fade');
// Loop through the list.
for (var i = 0; i < els.length; i++) {
// Hide them.
els[i].style.display = 'none';
}
}
Demo

Creating a color mixer showing the result of two combined colors

I am working on a color mixer where there are 6 colors. When you click on 2 of them it shows the color that it would be if you took mixed two colors of paint and put them together.
I am wondering how to make it so that when you click two things it shows an output.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Color Mixer</title>
</head>
<body>
<div id="greendiv"></div>
<div id="bluediv"></div>
<div id="yellowdiv"></div>
<div id="reddiv"></div>
<div id="purplediv"></div>
<div id="orangediv"></div>
<p id="separator">------------------------------------------
</body>
</html>
and the CSS
#greendiv {
background-color:green;
width: 100px;
height: 200px;
margin-left: 360px;
}
#bluediv {
background-color:blue;
width: 100px;
height: 200px;
margin-left: 120px;
margin-top: -200px;
}
#yellowdiv {
background-color:yellow;
width: 100px;
height: 200px;
margin-left: 240px;
margin-top: -200px;
}
#reddiv {
background-color: #E42217;
height: 200px;
width: 100px;
margin-top: -200px
}
#purplediv {
background-color: purple;
height: 200px;
width: 100px;
margin-left: 480px;
margin-top: -200px;
}
#orangediv {
background-color: orange;
height: 200px;
width: 100px;
margin-left: 600px;
margin-top: -200px;
}
#separator {
font-size: 50px;
color: #565051;
margin-top: -15px
}
#reddiv:hover {
background-color: #C11B17
}
I'm using JQuery XColor to do the color mixing..
See this fiddle: choose 2 items and hit "Get Mix" button
http://jsfiddle.net/jFIT/X4Qgf/6/
function getMix() {
var colors = $('.selected');
var col1 = rgb2hex($(colors[0]).css('background-color'));
var col2 = rgb2hex($(colors[1]).css('background-color'));
console.log(colors);
var additiveColor = ($.xcolor.average(col1, col2).getHex());
console.log(col1 + ' AND ' + col2);
console.log(' = ' + additiveColor);
$('#result').css('background-color', additiveColor);
}
for this line:
var additiveColor = ($.xcolor.average(col1, col2).getHex());
you can use a number of different color calculations by changing .average( to whatever you want documented here: http://www.xarg.org/project/jquery-color-plugin-xcolor/ (i.e. additive, subtractive.. etc)
Is this what you're after??
Try this: First add 3 more entries to your CSS
#color1div {
background-color: black;
height: 100px;
width: 100px;
}
#color2div {
background-color: black;
height: 100px;
width: 100px;
margin-left: 120px;
}
#resultdiv {
background-color: black;
height: 100px;
width: 100px;
margin-left: 240px;
}
Then, modify your html page like this:
<html>
<head>
<meta charset="utf-8">
<title>Color Mixer</title>
<script type="text/javascript">
var nextColor = 'color1div';
function selectColor(colorName)
{
//select color
document.getElementById(nextColor).style.backgroundColor=colorName;
//toggle color 1 and color 2
if(nextColor == 'color1div')
nextColor = 'color2div';
else
nextColor = 'color1div';
//mix the colors
var color1 = document.getElementById('color1div').style.backgroundColor;
var color2 = document.getElementById('color2div').style.backgroundColor;
//insert your color mixing formula here and set result
//example:
//var result = mix(color1, color2);
//document.getElementById('resultdiv').style.backgroundColor = result;
}
</script>
</head>
<body>
<div id="greendiv" onclick="javascript:selectColor('green')"></div>
<div id="bluediv" onclick="javascript:selectColor('blue')"></div>
<div id="yellowdiv" onclick="javascript:selectColor('yellow')"></div>
<div id="reddiv" onclick="javascript:selectColor('red')"></div>
<div id="purplediv" onclick="javascript:selectColor('purple')"></div>
<div id="orangediv" onclick="javascript:selectColor('orange')"></div>
<p id="separator">------------------------------------------
<div id="color1div"/>
<div id="color2div"/>
<div id="resultdiv"/>
</body>
</html>
When you click the color divs, it calls the javscript function to save the selected color in a variable. Now, you can just insert your color mixing formula and set the resulting color on the resultdiv.

Categories