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>
Related
I want to change the color of the clicked div element. If I change the color with the color is transferred to each next click div.
How to click on the div element to change the color of that div element. First click on some div and then change color?
<html>
<head>
<style>
html, body {
overflow: display;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
background-color: white;
}
#some_id1{
width: 50px;
height: 50px;
background-color: red;
}
#some_id2{
width: 50px;
height: 50px;
background-color: red;
}
#some_id3{
width: 50px;
height: 50px;
background-color: red;
}
#some_id4{
width: 50px;
height: 50px;
background-color: red;
}
</style>
</head>
<body>
<input type="color" id="divbackgroundcolor" onchange="myFunction()">
<div id="some_id1"></div>
<div id="some_id2"></div>
<div id="some_id3"></div>
<div id="some_id4"></div>
<div id="some_id5"></div>
<script>
var div = document.getElementsByTagName("div");
var divCount = div.length;
for (var i = 0; i <= divCount; i += 1) {
div[i].onclick = function(e) {
var x = document.getElementById("divbackgroundcolor").value;
document.getElementById(this.id).style.backgroundColor = x;
};
}
</script>
</body>
</html>
Ok, so first, I don't understand why are you using id on each div, while you are having the same style for each. better do it with class
Secondly, I have looked it up a little, and what I discovered people do, is just hide the color picker (input) and trigger it on click.
In your piece of code, it would look something like this:
var div = document.getElementsByTagName("div");
var divCount = div.length;
var clickedDivId
for (var i = 0; i < divCount; i += 1) {
div[i].onclick = function(e) {
clickedDivId = this.id
document.getElementById("divbackgroundcolor").click()
};
}
function colorChange(){
var x = document.getElementById("divbackgroundcolor").value;
document.getElementById(clickedDivId).style.backgroundColor = x;
}
html, body {
overflow: display;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
background-color: white;
}
#divbackgroundcolor {
position: absolute;
opacity: 0;
z-index: -1;
}
.some_style {
width: 50px;
height: 50px;
background-color: red;
}
<input type="color" id="divbackgroundcolor" onchange="colorChange()">
<div class="some_style" id="some_id1"></div>
<div class="some_style" id="some_id2"></div>
<div class="some_style" id="some_id3"></div>
<div class="some_style" id="some_id4"></div>
<div class="some_style" id="some_id5"></div>
Notice that what I did is saved the id of the div I clicked on, so I could tell on which div I have clicked.
Hope that is the answer you are looking for.
Good luck.
Your example have only to mistakes:
In HTML remove the "onclick" in your "input"
And in JS your "for" loop use "i < divCount"
Change just those lines and will work!
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.
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
I've got some kind of drop down menu dynamically appending to differents divs. Problem is, when someone click on "close", then style.display = "none" wont work. I can change background, opacity, size but i cant hide it.
Code looks like this:
<style>
html, body{
height: 98%;
}
#editorViewport{
width: 90%;
height: 100%;
min-width: 400px;
min-height: 300px;
position: relative;
margin: 0 auto;
border: 1px solid red;
}
#movingElementsContainer{
display: none;
top: 0px;
left: 0px;
}
#addStartingElementBtn{
width: 60px;
height: 60px;
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
}
#addStartingElementBtn:hover{
background-color: #c9eac6;
border: 1px solid grey;
cursor: pointer;
}
#elementsMenuContainer{
width: 150px;
border: 1px solid grey;
background-color: white;
min-height: 100px;
padding: 5px;
position: absolute;
z-index: 2;
display: none;
}
.elementOption{
width: 90%;
padding: 5px;
border: 1px solid grey;
}
.elementOption:hover{
border: 1px solid red;
cursor: pointer;
}
</style>
<body>
<div id="editorViewport">
<div id="addStartingElementBtn" data-Owner="starting" data-Side="starting" class="openElementsMenu">
Click!
</div>
</div>
<div id="movingElementsContainer">
<div id="elementsMenuContainer" data-Open="false" data-Owner="" data-Side="">
<div data-Kind="1" class="elementOption">
One
</div>
<div data-Kind="2" class="elementOption">
Two
</div>
<div data-Kind="3" class="elementOption">
Three
</div>
<div data-Kind="99" class="elementOption">
Close
</div>
</div>
</div>
</body>
<script type="text/javascript">
function prepareEventHandlers(){
var openElementsMenu = document.getElementsByClassName("openElementsMenu");
var event = window.attachEvent ? 'onclick' : 'click';
for(var i = 0; i < openElementsMenu.length; i++){
if(openElementsMenu[i].addEventListener){
openElementsMenu[i].addEventListener('click', elementsMenu, false);
}else{
openElementsMenu[i].attachEvent('onclick', elementsMenu);
}
}
var elementOption = document.getElementsByClassName("elementOption");
for(var i = 0; i < elementOption.length; i++){
if(elementOption[i].addEventListener){
elementOption[i].addEventListener('click', selectElementToCreate, false);
}else{
elementOption[i].attachEvent('onclick', selectElementToCreate);
}
}
}
window.onload = function(){
prepareEventHandlers();
}
var totalElements = 0;
var editorViewport = "editorViewport";
var selectedElementId = "";
var elementsMenu = function(){
var elementsMenu = document.getElementById("elementsMenuContainer")
this.appendChild(elementsMenu);
elementsMenu.style.display = "block";
elementsMenu.style.left = 61 + "px";
elementsMenu.style.top = "0px";
elementsMenu.setAttribute("data-Open", "true");
elementsMenu.setAttribute("data-Owner", this.getAttribute("data-Owner"));
elementsMenu.setAttribute("data-Side", this.getAttribute("data-Side"));
}
var selectElementToCreate = function(){
var dataKind = this.getAttribute('data-Kind');
var parentNode = document.getElementById(this.parentNode.id);
alert(dataKind)
if(dataKind == "99"){
parentNode.style.display = "none"
parentNode.setAttribute("data-Open", "false");
parentNode.setAttribute("data-Owner", "");
parentNode.setAttribute("data-Side", "");
}
}
</script>
Here is a JSFiddle
Many thanks for any advise!
var selectElementToCreate = function(e){
var dataKind = this.getAttribute('data-Kind');
var parentNode = document.getElementById(this.parentNode.id);
alert(dataKind)
if(dataKind == "99"){
console.log(parentNode);
parentNode.style.display = "none"
parentNode.setAttribute("data-Open", "false");
parentNode.setAttribute("data-Owner", "");
parentNode.setAttribute("data-Side", "");
alert("Wont Close :");
}
e.stopPropagation();
}
You are moving the element into the clicked element.
var elementsMenu = document.getElementById("elementsMenuContainer")
this.appendChild(elementsMenu);
At first the menu item's click handler is executed which sets the display property to none and as the click event bubbles then the event handler of the wrapper element is executed and sets the display property to block.
You should stop the propagation of the event using stopPropagation method of the event object.
var selectElementToCreate = function (event) {
event.stopPropagation();
var dataKind = this.getAttribute('data-Kind');
var parentNode = this.parentNode;
if (dataKind == "99") {
parentNode.style.display = "none";
// ...
}
}
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