JQuery Remove not removing specified div - javascript

I have a small page on which you can add squares of different colors to a div with a button. After adding them, you can remove them by double clicking any of the squares created.
My code works well, when adding elements. However when I want to remove a square, I just get to remove one and after that I can´t make the element disappear on HTML even though the counter does decrease. I´m a doing something wrong with the remove() function? Right now I´m just focusing on the blue (Azul) color.
Here´s my code
https://jsfiddle.net/kdwyw0mc/
var azules = 0;
var rojos = 0;
var amarillos = 0;
var verdes = 0;
function eliminar(cuadro){
azules = parseInt(jQuery('#num-azules').text());
verdes = parseInt(jQuery('#num-verdes').text());
rojos = parseInt(jQuery('#num-rojos').text());
amarillos = parseInt(jQuery('#num-amarillos').text());
if(cuadro[0].classList[1]=='blue'){
azules = azules -1;
}
else if(cuadro[0].classList[1]=='red'){
rojos--;
}
else if(cuadro[0].classList[1]=='yellos'){
amarillos--;
}
else if(cuadro[0].classList[1]=='green'){
verdes--;
}
cuadro.remove();
jQuery('#num-azules').text(azules);
jQuery('#num-verdes').text(verdes);
jQuery('#num-rojos').text(rojos);
jQuery('#num-amarillos').text(amarillos);
}
function agregar(){
jQuery('span#num-azules').val(azules);
var numCuadros = jQuery("#numero").val();
var color = $('#color option:selected').text();
for( i = 0; i< numCuadros; i++){
if(color=='Azul'){
/*jQuery(".square").append(function(){
return jQuery('<div class="square blue"> </div>').ondblclick(eliminar);
})*/
var newSquare = jQuery('<div class="square blue"> </div>')
var a = jQuery(".squares").append(newSquare);
newSquare.dblclick(function(){eliminar(newSquare);})
azules += 1;
}
else if(color=='Rojo'){
jQuery(".squares").append('<div class="square red"> </div>')
rojos+= 1;
}
else if(color=='Amarillo'){
jQuery(".squares").append('<div class="square yellow"> </div>')
amarillos+= 1;
}
else if(color=='Verde'){
jQuery(".squares").append('<div class="square green"> </div>')
verdes+= 1;
}
}
jQuery('#num-azules').text(azules);
jQuery('#num-verdes').text(verdes);
jQuery('#num-rojos').text(rojos);
jQuery('#num-amarillos').text(amarillos);
}
/*
* jQuery("#agregar").click(function(){
agregar();
});
VS
jQuery("#agregar").click(agregar());
* */
jQuery('#num-azules').text(azules);
jQuery('#num-verdes').text(verdes);
jQuery('#num-rojos').text(rojos);
jQuery('#num-amarillos').text(amarillos);
jQuery("#agregar").click(function(){
agregar();
});
HTML:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="styles/reset.css"/>
<link rel="stylesheet" href="styles/main.css"/>
</head>
<body>
<div class="main-content">
<div class="toolbar">
Numero Cuadrados: <input id="numero"type="text"/>
<select id="color" name="color">
<option value="azul">Azul</option>
<option value="rojo">Rojo</option>
<option value="amarillo">Amarillo</option>
<option value="verde">Verde</option>
</select>
<button id="agregar">Agregar</button>
</div>
<div class="squares">
</div>
<div class="numeros">
<p>Azules: <span id="num-azules">0</span> </p>
<p>Rojos: <span id="num-rojos">0</span></p>
<p>Verde: <span id="num-verdes">0</span></p>
<p>Amarillo: <span id="num-amarillos">0</span></p>
</div>
</div>
<script src="scripts/jquery-1.11.3.min.js"></script>
<script src="scripts/main.js"></script>
</body>
</html>

This is an inefficient way of registering / listening to events, it is better to delegate the event handling to a wrapper (parent) container:
$("#container").on("dblclick", ".square", function(){
$(this).remove();
)};
on works for dynamically created elements; since the container was already in the DOM, it can continue listening to events coming from any other, newly created child element that has class .square.
http://api.jquery.com/on/
Edit:
One way of solving the counter problem would be to do something like this:
var StateObj = function(){
this.counter = 0;
this.arrSquares = [];
this.increaseCounter = function(){
this.counter += 1;
},
this.decreaseCounter = function(){
this.counter -= 1;
},
this.addSquare = function(id, color){
this.arrSquares.push({id: id, color: color});
},
this.getSquareById = function(id){
return square = $.grep(this.arrSquares, function(){ return id == id; });
}
}
var stateObj = newStateObj();
$("#container").on("dblclick", ".square", function(e){
$(this).remove();
var id = $(e.currentTarget).attr("id");
stateObj.increaseCounter();
console.log(stateObj.counter);
)};

Related

change properties of two divs with one onclick and querySelectorAll()

I have multiple elements that are seperatet in two divs. The first div contains a Text and the second div a color.
When I click on one element the text and color should change and if I click it again it should change back.
The problem is that no matter which one I click, its always the last one which changes.
The HTML part:
<style>
.colorGreen {
background-color: green;
}
.colorRed {
background-color: red;
}
</style>
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
The JavaScript part:
<script type='text/javascript'>
var box1Temp = document.querySelectorAll(".box1");
var box2Temp = document.querySelectorAll(".box2");
for (var i = 0; i < box1Temp.length; i++) {
var box1 = box1Temp[i];
var box2 = box2Temp[i];
box2.onclick = box1.onclick = function() {
if (box1.classList.contains("colorGreen")) {
box1.classList.add("colorRed");
box1.classList.remove("colorGreen");
box2.innerHTML = "Text2";
} else {
box1.classList.add("colorGreen");
box1.classList.remove("colorRed");
box2.innerHTML = "Text1";
}
}
}
</script>
It works, when I use only one div.
Then I can use 'this', instead of the 'box1' variable, to addres the right element.
But if I replace 'box1' with 'this' its still the text div that changes.
(I know it's obvious that this is happening, but I'm lost)
With a few small tweaks, this can be written a lot more cleanly:
// Capture click event for parent container, .toggle-set
for (const ele of document.querySelectorAll(".toggle-set")) {
ele.addEventListener("click", function() {
// Grab text and color elements
const textToggle = ele.querySelector(".toggle-text");
const colorToggle = ele.querySelector(".toggle-color");
// Toggle text
// NOTE: This could use further refinement with regex or something similar to strip whitespace before comparison
textToggle.textContent = textToggle.textContent == "Text1" ? "Text2" : "Text1";
// Toggle css classes
colorToggle.classList.toggle("colorGreen");
colorToggle.classList.toggle("colorRed");
});
}
.colorGreen { background-color: green; }
.colorRed { background-color: red; }
<div class="toggle-set">
<div class="toggle-text">Text1</div>
<div class="toggle-color colorGreen">
O
</div>
</div>
<div class="toggle-set">
<div class="toggle-text">Text1</div>
<div class="toggle-color colorGreen">
O
</div>
</div>
Your code is so confused
You were right for the this option.
you can do with simple onclick function :
function change(el){
box1 = el.querySelector('.box1');
box2 = el.querySelector('.box2');
if (box1.classList.contains("colorGreen")) {
box1.classList.add("colorRed");
box1.classList.remove("colorGreen");
box2.innerHTML = "Text2";
} else {
box1.classList.add("colorGreen");
box1.classList.remove("colorRed");
box2.innerHTML = "Text1";
}
}
<style>
.colorGreen {
background-color: green;
}
.colorRed {
background-color: red;
}
</style>
<div onclick="change(this)">
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
</div>
<div onclick="change(this)">
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
</div>
<div onclick="change(this)">
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
</div>
I think following code snippet would help you to get your desired result
let box1 = document.querySelectorAll(".box1");
let box2 = document.querySelectorAll(".box2");
box1.forEach((b1,i) => {
b1.addEventListener("click",(ev) => {
ev.target.classList.toggle("colorGreen");
ev.target.classList.toggle("colorRed");
console.log(box2[i]);
if(ev.target.classList.contains("colorGreen")){
box2[i].textContent = "Text1";
}else{
box2[i].textContent = "Text2"
}
})
})

Cycle through divs up and down with Jquery

I need to cycle up and down through two sets of divs simultaneously. This code works well for cycling up the list (button1) but when I tried to create a down button (button2) it messes up the div order and doesn't cycle correctly. How can I alter this code to make it successfully cycle up and down through the list in the correct order?
$(document).ready(function() {
var divs = $('div[id^="num-"]').hide(),
i = 0;
function cycleone() {
divs.hide().eq(i).show();
i = ++i % divs.length;
};
cycleone()
$('#button1').click(function() {
cycleone()
})
});
$(document).ready(function() {
var divsv = $('div[id^="numv-"]').hide(),
iv = 0;
function cycletwo() {
divsv.hide().eq(iv).show();
iv = ++iv % divsv.length;
};
cycletwo()
$('#button1').click(function() {
cycletwo()
})
});
$(document).ready(function() {
var divs = $('div[id^="num-"]').hide(),
i = 0;
function cycleonedown() {
divs.hide().eq(i).show();
i = --i % divs.length;
};
cycleonedown()
$('#button2').click(function() {
cycleonedown()
})
});
$(document).ready(function() {
var divsv = $('div[id^="numv-"]').hide(),
iv = 0;
function cycletwodown() {
divsv.hide().eq(iv).show();
iv = --iv % divsv.length;
};
cycletwodown()
$('#button2').click(function() {
cycletwodown()
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="num-1">1</div>
<div id="num-2">2</div>
<div id="num-3">3</div>
<div id="num-4">4</div>
<div id="num-5">5</div>
<div id="num-6">6</div>
<div id="num-7">7</div>
<div id="numv-1">A</div>
<div id="numv-2">B</div>
<div id="numv-3">C</div>
<div id="numv-4">D</div>
<div id="numv-5">E</div>
<div id="numv-6">F</div>
<div id="numv-7">G</div>
<button id="button1">Up</button>
<button id="button2">Down</button>
As i can see you are using jquery, try the snippet below
$(document).ready(function(){
var lettersArray=[];
var step=1;
var lastStep=parseInt($(document).find('.num').length);
if($(document).find('.numv').length){
$(document).find('.numv').each(function(){
var letter=$(this).html();
lettersArray.push(letter);
});
}
showCycle=function(step){
var stepLetter=lettersArray[step-1];
$('#number').html(step);
$('#letter').html(stepLetter);
}
$(document).on('click','#button1',function(){
step=step+1;
step=step > lastStep ? 1 : step;
showCycle(step);
});
$(document).on('click','#button2',function(){
step=step-1;
step=step < 1 ? lastStep : step;
showCycle(step);
});
});
.num, .numv{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<div id="num-1"class="num">1</div>
<div id="num-2"class="num">2</div>
<div id="num-3"class="num">3</div>
<div id="num-4"class="num">4</div>
<div id="num-5"class="num">5</div>
<div id="num-6"class="num">6</div>
<div id="num-7"class="num">7</div>
<div id="numv-1"class="numv">A</div>
<div id="numv-2"class="numv">B</div>
<div id="numv-3"class="numv">C</div>
<div id="numv-4"class="numv">D</div>
<div id="numv-5"class="numv">E</div>
<div id="numv-6"class="numv">F</div>
<div id="numv-7"class="numv">G</div>
<div id="number">1</div>
<div id="letter">A</div>
<button id="button1">Up</button>
<button id="button2">Down</button>

How to get all HTML elements 500px below viewport using Javascript

I am trying to get all the HTML elements(div with particular id) which are there 500px below viewport on the page. I want to have this on scroll event.
var windowHeight = window.outerHeight;
var gridTop = windowHeight + 500;
var elements = document.getElementsByClassName('test');
window.addEventListener('scroll', function () {
for (let i = 0; i < elements.length; i++) {
var thisTop = elements[i].offsetTop - document.body.scrollTop;
if (thisTop >= gridTop) {
console.log('hi');
}
}
});
I need help on finding elements 500px below viewport.
EDIT:
I want to do it with pure JavaScript and I am using above code. But every time I am getting thisTop as 0. Please let me know the approach to do this.
Check following solution, here I put parent div which is scrollable.
Note- I have put offset of 50px, in order to support the example.
var parent = document.documentElement
var elements = document.getElementsByClassName('test');
var gridTop = parent.clientHeight + 50;
window.addEventListener('scroll', function() {
var printStr = "";
for (let i = 0; i < elements.length; i++) {
var thisTop = elements[i].offsetTop - parent.scrollTop;
if (thisTop >= gridTop) {
printStr += " "+elements[i].id
}
}
console.clear();
console.log('selected ', printStr);
});
.container div {
width: 40px;
height: 70px;
margin: 5px;
background-color: red;
text-align: center;
}
<div class="container">
<div class="test" id="1">1</div>
<div class="test" id="2">2</div>
<div class="test" id="3">3</div>
<div class="test" id="4">4</div>
<div class="test" id="5">5</div>
<div class="test" id="6">6</div>
<div class="test" id="7">7</div>
<div class="test" id="8">8</div>
<div class="test" id="9">9</div>
<div class="test" id="10">10</div>
<div class="test" id="11">11</div>
<div class="test" id="12">12</div>
</div>
You should not set multiple elements to have the same ID.
It will have a conflict in your js.
If you want to identify a set of DIVs, you should use CLASS instead.
Here, what I did was to find all elements classed as some-class-name iterated through the list,
Then get their width, both style.width and offsetWidth
<div id="the_900px_div" class="some-class-name" style="width:900px;border:1px solid blue;"></div>
<div id="the_200px_div" class="some-class-name" style="width:200px;border:1px solid blue;"></div>
<div id="the_100px_div" class="some-class-name" style="width:100px;border:1px solid red;"></div>
<script type="text/javascript">
function autorun()
{
var elements = document.getElementsByClassName('some-class-name');
var elementsLength = elements.length;
console.log(elements);
for (var i = 0; i < elementsLength; i++){
var sw = elements[i].style.width.replace('px','');
var ow = elements[i].offsetWidth;
var id = elements[i].id;
console.log(sw > 500)
console.log(id + ' style.width is ' + sw + 'px')
console.log(ow > 500)
console.log(id + ' offsetWidth is ' + ow + 'px')
}
}
if (document.addEventListener) document.addEventListener("DOMContentLoaded", autorun, false);
else if (document.attachEvent) document.attachEvent("onreadystatechange", autorun);
else window.onload = autorun;
</script>

managing several show/hide divs

I have some scripts here that show and hide divs when click. Now what I need is to just only display one div at a time. I have a code that controls them all but its not working I don't know about much of javascript.
This is the first example of show/hide function that can be done simultaneously without hiding the other divs.
FIDDLE HERE
HTML:
<a href="javascript:ReverseDisplay('uniquename')">
Click to show/hide.
</a>
<div id="uniquename" style="display:none;">
<p>Content goes here.</p>
</div>
<a href="javascript:ReverseDisplay('uniquename1')">
Click to show/hide.
</a>
<div id="uniquename1" style="display:none;">
<p>Content goes here.</p>
</div>
SCRIPT:
function HideContent(d) {
document.getElementById(d).style.display = "none";
}
function ShowContent(d) {
document.getElementById(d).style.display = "block";
}
function ReverseDisplay(d) {
if (document.getElementById(d).style.display == "none") {
document.getElementById(d).style.display = "block";
} else {
document.getElementById(d).style.display = "none";
}
}
function HideAllShowOne(d) {
// Between the quotation marks, list the id values of each div.
var IDvaluesOfEachDiv = "idone idtwo uniquename1 uniquename";
//-------------------------------------------------------------
IDvaluesOfEachDiv = IDvaluesOfEachDiv.replace(/[,\s"']/g," ");
IDvaluesOfEachDiv = IDvaluesOfEachDiv.replace(/^\s*/,"");
IDvaluesOfEachDiv = IDvaluesOfEachDiv.replace(/\s*$/,"");
IDvaluesOfEachDiv = IDvaluesOfEachDiv.replace(/ +/g," ");
var IDlist = IDvaluesOfEachDiv.split(" ");
for(var i=0; i<IDlist.length; i++) { HideContent(IDlist[i]); }
ShowContent(d);
}
The other fiddle I created would do what I need but the script seems not to be working. Fiddle here
Found the solution on my code thanks to #Abhas Tandon
Fiddle here the extra id's inside the IDvaluesOfEachDiv seems to be making some error with the codes.
If you are happy with IE10+ support then
function ReverseDisplay(d) {
var els = document.querySelectorAll('.toggle.active:not(#' + d + ')');
for (var i = 0; i < els.length; i++) {
els[i].classList.remove('active');
}
document.getElementById(d).classList.toggle('active')
}
.toggle {
display: none;
}
.toggle.active {
display: block;
}
<a href="javascript:ReverseDisplay('uniquename')">
Click to show/hide.
</a>
<div id="uniquename" class="toggle">
<p>Content goes here.</p>
</div>
<a href="javascript:ReverseDisplay('uniquename1')">
Click to show/hide.
</a>
<div id="uniquename1" class="toggle">
<p>Content goes here.</p>
</div>
I would suggest to use jQuery which is far easier.
Include thiswithin
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
HTML
<div id="id_one">Item 1</div>
<div id="content_one">
content goes here
</div>
<div id="id_two">Item 1</div>
<div id="content_two">
content goes here
</div>
Script:
$(function()
{
$("#content_one").hide();
$("#content_two").hide();
});
$("#id_one").on("click",function()
{
$("#content_one").slideDown("fast");
});
$("#id_two").on("click",function()
{
$("#content_two").slideDown("fast");
});
If you have a "Button" for every DIV inside your HTML - you can go by element index
var btn = document.querySelectorAll(".btn");
var div = document.querySelectorAll(".ele");
function toggleDivs() {
for(var i=0; i<btn.length; i++) {
var us = i===[].slice.call(btn).indexOf(this);
btn[i].tog = us ? this.tog^=1 : 0;
div[i].style.display = ["none","block"][us?[this.tog]:0];
}
}
for(var i=0; i<btn.length; i++) btn[i].addEventListener("click", toggleDivs);
.btn{/* Anchors Buttons */ display:block; cursor:pointer; color:#00f;}
.ele{/* Hidden Divs */ display:none;}
<a class="btn"> 1Click to show/hide.</a>
<div class="ele"><p>1Content goes here.</p></div>
<hr>
<a class="btn">2Click to show/hide.</a>
<div class="ele"><p>2Content goes here.</p></div>
<hr>

How to invoke JavaScript on hover over an element class or id?

I have 1,000 links on one page. Each link has a title/note/tool-tip. All the titles say the same thing so rather than typing it up on each line is there a way that I can have javscript do this for me?
Example Before:
<div class="links">
Tooltips
Tooltips
Tooltips
Tooltips
</div>
Example of what I would like:
<div class="links">
<a href="#" >Tooltips</a>
<a href="#" >Tooltips</a>
<a href="#" >Tooltips</a>
<a href="#" >Tooltips</a>
</div>
and have java script display a note when mouseover of "div .links a"
Thanks in advance.
jsFiddle Demo
var set = document.querySelectorAll(".links a");
var tip = document.createElement("div");
tip.className = "hover";
var msg = document.createElement("div");
tip.appendChild(msg);
msg.innerHTML = "Generic Hover Message";
for( var i = 0, n = set.length; i < n; i++ ){
set[i].onmouseover = function(){
this.parentNode.insertBefore(tip,this);
};
set[i].onmouseout = function(){
tip.parentNode.removeChild(tip);
};
}
Set up events for the target elements
Use a combination of document.querySelectorAllMDN and iterate through the set assigning the onmouseover eventMDN and onmousout eventMDN to each element.
var set = document.querySelectorAll(".links a");
for( var i = 0, n = set.length; i < n; i++ ){
set[i].onmouseover = function(){
Create an element using document.createElementMDN for the tooltip
var tip = document.createElement("div");
tip.className = "hover";
var msg = document.createElement("div");
tip.appendChild(msg);
msg.innerHTML = "Generic Hover Message";
Create styling to position the tooltip
.hover{
position: absolute;
display:inline-block;
width:100%;
}
.hover > div{
top: 1.2em;
position:absolute;
z-index: 1;
}
Use insertBeforeMDN to place the element
this.parentNode.insertBefore(tip,this);
Like this?
<div class="links" title="This is a title">
<a href="#" >Tooltips</a>
...
Here is an example using Travis' proposed solution with a querySelector and onmouseover.
<html>
<head>
<title>Link over</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<style>
.links{
}
</style>
<script>
// I show a tooltip
function showTip() {
console.log("I'm a tooltip");
}
// I set up the listeners
window.onload = function() {
var links = document.querySelector("div.links");
for (var i = 0; i < links.children.length; i++) {
links.children[i].onmouseover = showTip;
}
};
</script>
</head>
<body>
<div class="links">
Tooltips
Tooltips
Tooltips
Tooltips
</div>
</body>
</html>

Categories

Resources