How to show/hide a border using javascript - javascript

I have 10 square boxes with different colors. I'm trying to show a border for the square that the user clicks on, and hide the border of the previous square. So far I have this, but I somehow get Cannot read property 'style' of null. My idea is to hide the current box border, then show a border for the new box that the user clicks.
Here is the jsFiddle of what I want. However, it doesn't seem to work. I can only use Javascript and can't use JQuery
https://jsfiddle.net/5op0d7zs/7/
var currentBoxNum = 1;
function changeColor(background, boxNum) {
document.getElementById("box" + currentBoxNum).style.borderStyle = "none";
currentBoxNum = boxNum;
document.getElementById("box" + currentBoxNum).style.borderStyle = "solid";
}
box1.onclick = function() { changeColor("#e6e2cf",1); }
box2.onclick = function() { changeColor("#dbcaac",2); }
box3.onclick = function() { changeColor("#c9cbb3",3); }
box4.onclick = function() { changeColor("#bbc9ca",4); }
box5.onclick = function() { changeColor("#a6a5b5",5); }
box6.onclick = function() { changeColor("#b5a6ab",6); }
box7.onclick = function() { changeColor("#eccfcf",7); }
box8.onclick = function() { changeColor("#eceeeb",8); }
box9.onclick = function() { changeColor("#bab9b5",9); }
<div class="colors">
<div id="box1">1</div>
<div id="box2">2</div>
<div id="box3">3</div>
<div id="box4">4</div>
<div id="box5">5</div>
<div id="box6">6</div>
<div id="box7">7</div>
<div id="box8">8</div>
<div id="box9">9</div>
</div>

You don't need to call the changeColor twice. Second thing You can do what you want in less code.
See this working example here.
You can check the updated fiddle here
var currentBoxNum = 1;
function changeColor(background, boxNum) {
document.getElementById("box" + currentBoxNum).style.borderStyle = "none";
currentBoxNum = boxNum;
document.getElementById("box" + currentBoxNum).style.borderStyle = "solid";
document.getElementById("box" + currentBoxNum).style.borderColor = "black";
}
document.getElementById("box1").addEventListener("click", function(){ changeColor("#e6e2cf", 1); });
document.getElementById("box2").addEventListener("click", function(){ changeColor("#dbcaac", 2); });
document.getElementById("box3").addEventListener("click", function(){ changeColor("#c9cbb3", 3); });
document.getElementById("box4").addEventListener("click", function(){ changeColor("#bbc9ca", 4); });
document.getElementById("box5").addEventListener("click", function(){ changeColor("#a6a5b5", 5); });
document.getElementById("box6").addEventListener("click", function(){ changeColor("#b5a6ab", 6); });
document.getElementById("box7").addEventListener("click", function(){ changeColor("#eccfcf", 7); });
document.getElementById("box8").addEventListener("click", function(){ changeColor("#eceeeb", 8); });
document.getElementById("box9").addEventListener("click", function(){ changeColor("#bab9b5", 9); });
#box1 {
background-color: #e6e2cf;
border: 2px solid black;
}
#box2 {
background-color: #dbcaac;
}
#box3 {
background-color: #c9cbb3;
}
#box4 {
background-color: #bbc9ca;
}
#box5 {
background-color: #a6a5b5;
}
#box6 {
background-color: #b5a6ab;
}
#box7 {
background-color: #eccfcf;
}
#box8 {
background-color: #eceeeb;
}
#box9 {
background-color: #bab9b5;
}
.pad {
margin: 10px;
}
.colors {
display: flex;
flex-wrap: wrap;
}
.colors>div {
width: 50px;
margin: 10px;
height: 50px;
}
<!-- This is a static file -->
<!-- served from your routes in server.js -->
<!DOCTYPE html>
<html>
<head>
<title>Show me!</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="./reset.css">
<link rel="stylesheet" href="./style.css">
<link href="https://fonts.googleapis.com/css?family=Dancing+Script|Homemade+Apple|Indie+Flower|Long+Cang&display=swap" rel="stylesheet">
</head>
<body>
<main>
<div class="pad">
<h2 class="choose_pad">Choose your color</h2>
<div class="colors">
<div id="box1">1</div>
<div id="box2">2</div>
<div id="box3">3</div>
<div id="box4">4</div>
<div id="box5">5</div>
<div id="box6">6</div>
<div id="box7">7</div>
<div id="box8">8</div>
<div id="box9">9</div>
</div>
</div>
</main>
<footer>
<p class="msg">
Made on Glitch!
</p>
<!-- adds the glitch button at the bottom -->
<div class="glitchButton"></div>
<script src="https://button.glitch.me/button.js"></script>
<script src="./script.js"></script>
</footer>
</body>
</html>

You're calling
document.getElementById("cb").style.backgroundColor = background;
There is no element with an id of "cb".
Update your code to properly reference the id of the element you wish to change the background color for.

Missing line: document.getElementById("box" + currentBoxNum).style. borderColor = background;
var currentBoxNum = 1;
function changeColor(background, boxNum) {
document.getElementById("box" + currentBoxNum).style.borderStyle = "none";
currentBoxNum = boxNum;
document.getElementById("box" + currentBoxNum).style.borderStyle = "solid";
document.getElementById("box" + currentBoxNum).style. borderColor = background;
}
box1.onclick = function() { changeColor("#e6e2cf",1); }
box2.onclick = function() { changeColor("#dbcaac",2); }
box3.onclick = function() { changeColor("#c9cbb3",3); }
box4.onclick = function() { changeColor("#bbc9ca",4); }
box5.onclick = function() { changeColor("#a6a5b5",5); }
box6.onclick = function() { changeColor("#b5a6ab",6); }
box7.onclick = function() { changeColor("#eccfcf",7); }
box8.onclick = function() { changeColor("#eceeeb",8); }
box9.onclick = function() { changeColor("#bab9b5",9); }
<div class="colors">
<div id="box1">1</div>
<div id="box2">2</div>
<div id="box3">3</div>
<div id="box4">4</div>
<div id="box5">5</div>
<div id="box6">6</div>
<div id="box7">7</div>
<div id="box8">8</div>
<div id="box9">9</div>
</div>

You can change you changeColor method as below
function changeColor(background, boxNum) {
$('.colors div').css('border', 'none'); // This will remove borders from all boxes
document.getElementById("box" + boxNum).style.borderStyle = "solid";
document.getElementById("box" + boxNum).style.borderColor = background;
}
Since this method is using jQuery, please include the jQuery in your html as below,
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
Also, this is just adding the border color not background color. If you want to add the background color as well you can add the following statement in changeColor function
document.getElementById("box" + boxNum).style.backgroundColor = background;

Related

Button requiring 2 clicks to work. - Vanilla JavaScript

My code is in this jsfiddle snippet below. Whenever I press the remove button, it requires 2 clicks to remove the boxes that were originally generated with html. If I have added them, then those boxes work properly with one click. The problem lies with these boxes that are made through the markup.
Link to the code : this
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.box-container {
display: flex;
}
.box-item {
display: inline-block;
height: 30px;
width: 30px;
background: orangered;
margin: 0 10px;
}
.activated {
background: dodgerblue;
}
</style>
</head>
<body>
<div id="box-container">
<span class="1 box-item"></span>
<span class="2 box-item"></span>
<span class="3 box-item"></span>
</div>
<button id="add">Add</button>
<button id="remove">Remove</button>
<script src="main.js"></script>
</body>
</html>
JS CODE
const boxContainer = document.getElementById("box-container");
const boxItems = document.getElementsByClassName("box-item");
const addBtn = document.getElementById("add");
const removeBtn = document.getElementById("remove");
function Box(element) {
this.__el = element;
this.activated = true;
}
Box.prototype.init = function() {
this.activateBox();
this.__el.addEventListener("click", this.toggleActivation.bind(this));
};
Box.prototype.logger = function() {
console.log(this);
};
Box.prototype.activateBox = function() {
if (this.activated) {
this.__el.classList.add("activated");
}
};
Box.prototype.deactivateBox = function() {
if (!this.activated) {
this.__el.classList.remove("activated");
}
};
Box.prototype.toggleActivation = function() {
this.__el.classList.toggle("activated");
return (this.activated = !this.activated);
};
let box = [];
for (let i = 0; i < boxItems.length; i++) {
box[i] = new Box(boxItems[i]);
box[i].init();
}
const addBox = function() {
const node = document.createElement("span");
node.classList.add("box-item", "activated");
boxContainer.appendChild(node);
};
function removeBox() {
boxContainer.removeChild(boxContainer.lastChild);
}
addBtn.addEventListener("click", addBox);
removeBtn.addEventListener("click", removeBox);
PS: I have checked other 2 questions that have the same title, but they don't solve my issue.
The problem is that your HTML includes text nodes between the .box-items:
<div id="box-container">
<span class="1 box-item"></span>
<span class="2 box-item"></span>
<span class="3 box-item"></span>
</div>
So, when you call
boxContainer.removeChild(boxContainer.lastChild);
If a parent's last child node is a text node, that text node will be selected when you use lastChild. That's not what you want - you don't want to select the text nodes. You only want to remove the <span> elements, so you might remove the last item in the .children instead:
const { children } = boxContainer;
boxContainer.removeChild(children[children.length - 1]);
Or, more elegantly, select the lastElementChild property, thanks to Andre's comment:
boxContainer.removeChild(boxContainer.lastElementChild);
(quite confusingly, the final index of children is not the same thing as the node returned by lastChild)
const boxContainer = document.getElementById("box-container");
const boxItems = document.getElementsByClassName("box-item");
const addBtn = document.getElementById("add");
const removeBtn = document.getElementById("remove");
function Box(element) {
this.__el = element;
this.activated = true;
}
Box.prototype.init = function() {
this.activateBox();
this.__el.addEventListener("click", this.toggleActivation.bind(this));
};
Box.prototype.logger = function() {
console.log(this);
};
Box.prototype.activateBox = function() {
if (this.activated) {
this.__el.classList.add("activated");
}
};
Box.prototype.deactivateBox = function() {
if (!this.activated) {
this.__el.classList.remove("activated");
}
};
Box.prototype.toggleActivation = function() {
this.__el.classList.toggle("activated");
return (this.activated = !this.activated);
};
let box = [];
for (let i = 0; i < boxItems.length; i++) {
box[i] = new Box(boxItems[i]);
box[i].init();
}
const addBox = function() {
const node = document.createElement("span");
node.classList.add("box-item", "activated");
boxContainer.appendChild(node);
};
function removeBox() {
boxContainer.removeChild(boxContainer.lastElementChild);
}
addBtn.addEventListener("click", addBox);
removeBtn.addEventListener("click", removeBox);
.box-container {
display: flex;
}
.box-item {
display: inline-block;
height: 30px;
width: 30px;
background: orangered;
margin: 0 10px;
}
.activated {
background: dodgerblue;
}
<div id="box-container">
<span class="1 box-item"></span>
<span class="2 box-item"></span>
<span class="3 box-item"></span>
</div>
<button id="add">Add</button>
<button id="remove">Remove</button>
Or, you can just change the HTML such that there are no text nodes:
<div id="box-container"><span class="1 box-item"></span><span class="2 box-item"></span><span class="3 box-item"></span></div>
const boxContainer = document.getElementById("box-container");
const boxItems = document.getElementsByClassName("box-item");
const addBtn = document.getElementById("add");
const removeBtn = document.getElementById("remove");
function Box(element) {
this.__el = element;
this.activated = true;
}
Box.prototype.init = function() {
this.activateBox();
this.__el.addEventListener("click", this.toggleActivation.bind(this));
};
Box.prototype.logger = function() {
console.log(this);
};
Box.prototype.activateBox = function() {
if (this.activated) {
this.__el.classList.add("activated");
}
};
Box.prototype.deactivateBox = function() {
if (!this.activated) {
this.__el.classList.remove("activated");
}
};
Box.prototype.toggleActivation = function() {
this.__el.classList.toggle("activated");
return (this.activated = !this.activated);
};
let box = [];
for (let i = 0; i < boxItems.length; i++) {
box[i] = new Box(boxItems[i]);
box[i].init();
}
const addBox = function() {
const node = document.createElement("span");
node.classList.add("box-item", "activated");
boxContainer.appendChild(node);
};
function removeBox() {
boxContainer.removeChild(boxContainer.lastChild);
}
addBtn.addEventListener("click", addBox);
removeBtn.addEventListener("click", removeBox);
.box-container {
display: flex;
}
.box-item {
display: inline-block;
height: 30px;
width: 30px;
background: orangered;
margin: 0 10px;
}
.activated {
background: dodgerblue;
}
<div id="box-container"><span class="1 box-item"></span><span class="2 box-item"></span><span class="3 box-item"></span></div>
<button id="add">Add</button>
<button id="remove">Remove</button>

Create multiple divs with different content

The problem is when duplicate multiple div but with different data-type, it still running a same content, i want correct all div will have the different content following the different data-type.
Is there a way to do this?
$(function() {
// document
'use strict';
var cp = $('div.box');
// unique id
var idCp = 0;
for (var i = 0; i < cp.length; i++) {
idCp++;
cp[i].id = "cp_" + idCp;
}
// diffrent type
if (cp.data('type') == "c1") {
cp.addClass('red').css({
"background: 'red',
"padding": "20px",
"display": "table"
});
$('.box').append('<div class="cp-title">' + 'c1-title' + '</div>');
} else if (cp.data('type') == "c2") {
cp.addClass('green').css({
"background": 'green',
"padding": "20px",
"display": "table"
});
$('.box').append('<div class="cp-title">' + 'c2-title' + '</div>');
} else {
return false;
}
}); //end
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<! it should be like this>
<div class="box" data-type="c1" id="cp_1">
<div class="cp-title">c1 title</div>
</div>
<div class="box" data-type="c2" id="cp_2">
<div class="cp-title">c2 title</div>
</div>
<! currently wrong output>
<div class="box" data-type="c1" id="cp_1">
<div class="cp-title">c1 title</div>
</div>
<div class="box" data-type="c2" id="cp_2">
<div class="cp-title">c1 title</div>
</div>
The problem in your code is that you are not looping inside the div's. You have to use the .each() function while looping inside all the elements
$(function() {
var cp = $('div.box');
cp.each(function() {
var _cp = $(this);
var text = _cp.attr("data-type") + "-title"; //Generate the text dynamically
var cls = _cp.attr("data-class"); //Get the class dynamically
_cp.addClass(cls).append('<div class="cp-title">' + text + '</div>'); //Add the class and append the text to the parent div
});
}); //end
.box{
padding: 20px;
display: table;
}
.red{
background: red;
}
.green{
background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box" data-type="c1" data-class="red"></div>
<div class="box" data-type="c2" data-class="green"></div>
Probably you're searching for something like this.
// document.ready
$(function() {
'use strict';
$('.box').each(function(i,elem){
var ref = +$(elem).attr("data-type").match(/\d/)[0], addClass = 'default';
switch(true) {
case ref === 1:
addClass = 'red';
break;
case ref === 2:
addClass = 'green';
break;
}
$(this)
.addClass(addClass)
.append('<div class="cp-title">c'+ref+' title</div>');
});
}); //end
.red{
background: red;
padding: 20px;
display: table;
}.green{
background: green;
padding: 20px;
display: table;
}.default {
background: #2d2d2d;
color: #f6f6f6;
padding: 20px;
display: table;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box" data-type="c1"></div><div class="box" data-type="c2"></div>

How can I update attributes with jQuery?

$(document).ready(function() {
var hero_image = new Array();
hero_image[0] = new Image();
hero_image[0].src = 'assets/images/link.png';
hero_image[0].id = 'image';
hero_image[1] = new Image();
hero_image[1].src = 'assets/images/bongo.png';
hero_image[1].id = 'image';
hero_image[2] = new Image();
hero_image[2].src = 'assets/images/gandondorf.jpg';
hero_image[2].id = 'image';
hero_image[3] = new Image();
hero_image[3].src = 'assets/images/queen.png';
hero_image[3].id = 'image';
var young_hero = ["Link", "Bongo Bongo", "Gandondorf", "Queen Gohma"];
var health = [100, 70, 120, 50];
var attack_power = [];
var counter_power = [];
console.log(hero_image[0]);
function it_is_over_9000(){
for (var i = 0; i < young_hero.length; i++) {
var x = Math.floor(Math.random(attack_power)*20) + 3;
var y = Math.floor(Math.random(attack_power)*10) + 3;
attack_power.push(x);
counter_power.push(y);
}
}
function ready_board(){
it_is_over_9000();
for (var i = 0; i < young_hero.length; i++) {
var hero_btns = $("<button>");
hero_btns.addClass("hero hero_button");
hero_btns.attr({
"data-name": young_hero[i],
"data-health": health[i],
"data-image": hero_image[i],
"data-attack": attack_power[i],
"data-counter": counter_power[i],
"data-index": i
});
hero_btns.text(young_hero[i]);
hero_btns.append(hero_image[i]);
hero_btns.append(health[i]);
$("#buttons").append(hero_btns);
}
}
function char(){
$(".hero_button").on("click", function() {
var hero = $(this);
var hero_select = hero.data('index');
for (var i = 0; i < young_hero.length; i++) {
//var attack = ;
if (i != hero_select){
var enemies = $("<button>");
enemies.addClass("hero enemy");
enemies.attr({
"data-power" : it_is_over_9000(),
"data-name": young_hero[i],
"data-health": health[i],
"data-image": hero_image[i],
"data-attack": attack_power[i],
"data-counter": counter_power[i],
"data-index": i
});
enemies.text(young_hero[i]);
enemies.append(hero_image[i]);
enemies.append(health[i]);
$("#battle").append(enemies);
}
}
$("#buttons").html($(this).data('name','health','image'));
defender();
});
}
function defender(){
$(".enemy").on("click", function() {
var enemy = $(this);
var enemy_select = enemy.data("index");
console.log(enemy_select);
for (var i = 0; i < young_hero.length; i++) {
if (i == enemy_select) {
var defender = $("<button>");
defender.addClass("hero defender");
defender.attr({
"data-name": young_hero[i],
"data-health": health[i],
"data-image": hero_image[i],
"data-attack": attack_power[i],
"data-counter": counter_power[i],
"data-index": i
});
defender.text(young_hero[i]);
defender.append(hero_image[i]);
defender.append(health[i]);
$("#defend").append(defender);
$(this).remove();
}
}
});
}
$(".defend_button").on("click" , function(){
if($(".defender").data("health") == 0){
$(".defender").remove();
}
$(".defender").attr({
"data-health": $(".defender").data("health") - $(".hero_button").data("attack")
});
});
ready_board();
char();
});
I am trying to make a RPG game and I have the characters being generated the way I want them too but on the $(".defend_button").on("click" , function() at the end it doesn't update the data-health as it should. It only updates once but upon many clicks on the defend-button it doesn't update past the first time.
<!DOCTYPE html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Zelda</title>
<script type='text/javascript' src='https://code.jquery.com/jquery-2.2.0.min.js'></script>
<script type = "text/javascript" src = "assets/javascript/game.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="assets/css/style.css">
</head>
<style type="text/css">
.hero { width: 125px; height:150px; border-style: solid; padding: 2px; float: left; margin: 2px; float: left; }
.letter-button-color { color: darkcyan; }
.fridge-color { color: orange; }
#display { margin-top:78px; height:500px; width:220px; margin-left:60px; }
#buttons { padding-top:60px; }
#clear { margin-left: 20px; font-size: 25px; color: black; border-style: solid; width: 100px; }
#image{width: 100px; height: 100px; margin-left: 10px; }
</style>
<body>
<div class="row">
<div class="col-md-8">Select Your Character</div>
</div>
<div class="row">
<div id="buttons" class="col-md-8"></div>
</div>
<div class="row">
<div id="battle" class="col-md-8">
</div>
</div>
<div class="row">
<div class="col-md-8">
<button class="btn btn-primary defend_button">Defend</button>
</div>
</div>
<div class="row">
<div id="defend">
</div>
</div>
</body>
</html>
You have to use .data() to update the health value.
var battleResult = $(".defender").data("health") - $(".hero_button").data("attack");
console.log("battleResult should be: "+battleResult );
$(".defender").data({
"health": battleResult
});
I played a little with your game.
I found how to update the health display below the image too...
Since only updating the data wasn't changing anything on the screen.
So, I left the above code there, for you to see it is effectively working.
But since you have to re-create the button to update health on scrreen... It is kind of useless.
I also fixed the death condition
from if($(".defender").data("health") == 0){
to if($(".defender").data("health") <= 0){
I have to stop here before changing to much things.
See it in CodePen
Check your loop in it_is_over_9000(), because I think it is running uselessly too often.
And a dead defender has to be "buried" (lol).
Because when it is killed, a click on the defend button is kind of ressurrecting it.
;)
Try setting the attribute like this. Also, I recommend putting $(".defender") in a variable so you aren't requerying it each time.
var defender = $(".defender");
var loweredHealth = defender.data("health") - $(".hero_button").data("attack");
defender.attr('data-health`, loweredHealth);
Update:
It looks like the $('.defender') call will return multiple items. You either need to select a specific defender or iterate through them individually like so:
$('.defender').each(function(i, nextDefender) {
var loweredHealth = nextDefender.data("health") - $(".hero_button").data("attack");
nextDefender.attr('data-health`, loweredHealth);
});`

Event listener hover changing other element

I made this script for showing/hiding other div that comes to place of the one with event (ricon1) on mouse in and out:
HTML:
<div class="rule-container">
<div class="rule" id="rule1">
<div class="rule-icon" id="ricon1">
</div>
<div class="rule-decription" id="rdescription1">
</div>
</div>
<div class="rule" id="rule2">
<div class="rule-icon" id="ricon2">
</div>
<div class="rule-decription" id="rdescription2">
</div>
</div>
<div class="rule" id="rule3">
<div class="rule-icon" id="ricon3">
</div>
<div class="rule-decription" id="rdescription3">
</div>
</div>
<div class="rule" id="rule4">
<div class="rule-icon" id="ricon4">
</div>
<div class="rule-decription" id="rdescription4">
</div>
</div>
</div>
CSS:
div.rule {
display: inline-block;
width:20%;
margin-left:2%;
margin-right:2%;
background-color: cadetblue;
}
div.rule:first-child {
margin-left:3.5%;
background-color:yellow;
}
div.rule > div {
width:100%;
}
div.rule-icon {
height:240px;
background-color:lightpink;
display:block;
}
div.rule-decription {
height: 240px;
background-color: springgreen;
display:none;
}
JS:
document.getElementById("ricon1").addEventListener("mouseenter",function (){
document.getElementById('ricon1').style.display = 'none';
document.getElementById('rdescription1').style.display = 'block';
});
document.getElementById("ricon1").addEventListener("mouseout",function (){
document.getElementById('ricon1').style.display = 'block';
document.getElementById('rdescription1').style.display = 'none';
});
But the problem is that it flashes (continuously switching between on and off state, what am i doing wrong ?
How may i change script so i dont have to do it for all pairs of divs (ricon1, rdescription1; ricon2, rdescription2... etc) because there is like 6 pairs?
Is there a specific reason you don't want to use jQuery for that?
Anyway, here's an example without jQuery:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div class = "switch">
<div class = "icon">A</div>
<div style = "display:none" class = "desc">Desc1</div>
</div>
<div class = "switch">
<div class = "icon">B</div>
<div style = "display:none" class = "desc">Desc2</div>
</div>
<div class = "switch">
<div class = "icon">C</div>
<div style = "display:none" class = "desc">Desc3</div>
</div>
<script>
var icons = document.querySelectorAll('.switch');
for (var i = 0; i < icons.length; i++) {
icons[i].addEventListener("mouseenter", function() {
(this.querySelectorAll(".icon")[0]).style.display = 'none';
(this.querySelectorAll(".desc")[0]).style.display = 'block';
});
icons[i].addEventListener("mouseleave", function() {
(this.querySelectorAll(".icon")[0]).style.display = 'block';
(this.querySelectorAll(".desc")[0]).style.display = 'none';
});
}
</script>
</body>
</html>

Unable to store permanently the id of dragged item

I am working on a project in which i had to store the the 3ID's of drop item in 3 textbox. but when i dragg and drop either one it stores it's id but when i drop the second item it stores it's ID but remove the ID of first from the textbox.
code
function dropItems(idOfDraggedItem, targetId, x, y) {
var targetObj = document.getElementById(targetId);
var subDivs = targetObj.getElementsByTagName('DIV');
if(subDivs.length>0 && targetId!='body')return;
var sourceObj = document.getElementById(idOfDraggedItem);
var numericIdTarget = targetId.replace(/[^0-9]/gi,'')/1;
var numericIdSource = idOfDraggedItem.replace(/[^0-9]/gi,'')/1;
if (numericIdTarget == '101') {
document.getElementById('txt1').value = numericIdSource;
} else {
document.getElementById('txt1').value = "";
}
if (numericIdTarget == '102') {
document.getElementById('txt2').value = numericIdSource;
} else {
document.getElementById('txt2').value = "";
}
if (numericIdTarget == '103') {
document.getElementById('txt3').value = numericIdSource;
} else {
document.getElementById('txt3').value = "";
}
var fn = "Feeling1:-" + document.getElementById('txt1').value + ", Feeling2:-" + document.getElementById('txt2').value + ", Feeling3:-" + document.getElementById('txt3').value + "";
document.getElementById('txt4').value = fn;
if (numericIdTarget - numericIdSource == 100) {
sourceObj.style.backgroundColor = '';
} else {
sourceObj.style.backgroundColor = '';
}
if (targetId == 'body') {
targetObj = targetObj.getElementsByTagName('DIV')[0];
}
targetObj.appendChild(sourceObj);
}
Initialization (from comments)
$(document).ready(function(e) {
var inp1=$("#txt1");
var inp2=$("#txt2");
var inp3=$("#txt3");
$("#bttn").click(function(){
if(inp1.val()=="" && (inp2.val()!="" || inp3.val()!="")) {
alert("Provide answer in consecutive manner");
} else if((inp1.val()=="" || inp2.val()=="") && inp3.val()!="" ) {
alert("Provide answer in consecutive manner");
} else {
alert("Submit");
}
});
})
I like to use jquery's built in draggable/droppable to acquire id's maybe this will help you with your current situation.
<!DOCTYPE HTML>
<html>
<head>
<title>Test Page</title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( ".draggable" ).draggable();
$( ".droppable" ).droppable({
drop: function( event, ui ) {
var id = $( this ).attr("id");
var container = ui.draggable.attr("id");
alert(id + " " + container);
}
});
});
</script>
<style>
.draggable{
width: 100px;
height: 50px;
border: 1px black solid;
margin: 0.5em;
}
.droppable{
width: 100px;
height: 50px;
border: 1px black solid;
margin: 0.5em;
}
</style>
</head>
<body>
<div id="draggable1" class="draggable">
<p>Drag me to my target</p>
</div>
<div id="draggable2" class="draggable">
<p>Drag me to my target</p>
</div>
<div id="draggable3" class="draggable">
<p>Drag me to my target</p>
</div>
<div style="height: 25px;"></div>
<div id="droppable1" class="droppable">
<p>Drop here</p>
</div>
<div id="droppable2" class="droppable">
<p>Drop here</p>
</div>
</body>
</html>

Categories

Resources