How can I disable a <div> - javascript

I am trying to build a simple traffic light with HTML, CSS and Javascript. Clicking on the light should change the color of the light (if I click when it is Green, it changes to Yellow and so on).
HTML:
<div id="outer_box" onclick = "change()">
<div id ="red"></div>
<div id ="yellow"></div>
<div id ="green"></div>
</div>
CSS:
#outer_box{
width: 70px;
height:150px;
background:black;
}
#red{
width: 50px;
height:50px;
margin: auto;
border-radius: 50%;
background: red;
}
#yellow{
width: 50px;
height:50px;
margin: auto;
border-radius: 50%;
background: yellow;
}
JavaScript:
var state;
state = "green"
function change(){
if (state=="green"){
state = "yellow";
}
else if (state== "yellow"){
state = "red";
//state_def();
}
else{
state = "green";
//state_def();
}
console.log(state);
state_def();
}
function state_def(){
console.log("inside state def")
console.log(state);
if (state == "green"){
document.getElementById("yellow").disabled = true;
//$("#yellow").prop('disabled',true);
//$("#red").prop('disabled',true);
}
else if (state == "yellow"){
$("#green").prop('disabled',true);
$("#red").prop('disabled',true);
}
else{
$("#yellow").prop('disabled',true);
$("#green").prop('disabled',true);
}
}
Here is the jsFiddle link: https://jsfiddle.net/taniachanda86/mx7r0hrL/
Please help me understand what is that I am doing wrong?

Following way you can do using JQuery. Add and remove active class.
First display one light. On click it will change.
var items = $('div.light');
var currentItem = items.filter('.active');
$('#outer_box').on('click', function() {
var nextItem = currentItem.next();
currentItem.removeClass('active');
if ( nextItem.length ) {
currentItem = nextItem.addClass('active');
} else {
currentItem = items.first().addClass('active');
}
});
#outer_box{
width: 70px;
height:150px;
background:black;
}
#red{
width: 50px;
height:50px;
margin: auto;
border-radius: 50%;
background: red;
display:none;
}
#yellow{
width: 50px;
height:50px;
margin: auto;
border-radius: 50%;
background: yellow;
display:none;
}
#green{
width: 50px;
height:50px;
margin: auto;
border-radius: 50%;
background: green;
display:none;
}
.active{
display:block !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="outer_box">
<div id ="red" class="light active"></div>
<div id ="yellow" class="light"></div>
<div id ="green" class="light"></div>
</div>

The solution is quite simple.
$("#green").attr('disabled', true);
will show that your div is actually being disabled while you inspect element. However, it will not quite get you to point of having the css color affected by it.
Instead defining the opacity attribute will help you achieve your need.
Here is the plunker: https://plnkr.co/edit/mdlAS68gpFBm64jfiCCu?p=preview. I hope this is what you are asking for.

var colors = ["red", "yellow", "green"];
var state = 1;//because red already visible
//addEventListener method to add onclick handler
document.getElementById('outer_box').addEventListener('click', function(){
if (state==3){//if state reaches to 3, reset to 0
state = 0;
}
var allLights = document.querySelectorAll('.light');
for(var i = 0; i < allLights.length; i++) {//remove active class from all light
allLights[i].className = "light";
}
document.getElementById(colors[state]).className = "light active"; //add active class on the next light;
state++;//increment state
}, false);
I have updated your fiddle. check here

Open your javascript console and see the failure:
Uncaught ReferenceError: change is not defined
change is not in scope of the onclick of the <div>.
This is because the Javascript part of jsfiddle is executed in the onload function. See https://stackoverflow.com/a/5468370/189058

I guess you wanted a traffic light which on click will glow the clicked light.If so, can be achieved by the below code.
$( document ).ready(function() {
$('#red').css("background-color", "red");
$('#yellow').css("background-color", "white");
$('#green').css("background-color", "white");
$('.trafficlight').click(function(){
var selected_id=$(this).attr("id");
if(selected_id=='green')
{
$('#green').css("background-color", "green");
$('#red').css("background-color", "white");
$('#yellow').css("background-color", "white");
}
else if(selected_id=='yellow')
{
$('#yellow').css("background-color", "yellow");
$('#red').css("background-color", "white");
$('#green').css("background-color", "white");
}
else
{
$('#red').css("background-color", "red");
$('#yellow').css("background-color", "white");
$('#green').css("background-color", "white");
}
});
});
#outer_box{
width: 70px;
height:150px;
background:black;
}
#red{
width: 50px;
height:50px;
margin: auto;
border-radius: 50%;
background:red;
}
#yellow{
width: 50px;
height:50px;
margin: auto;
border-radius: 50%;
background: yellow;
}
#green{
width: 50px;
height:50px;
margin: auto;
border-radius: 50%;
background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="outer_box" >
<div id ="red" class="trafficlight"></div>
<div id ="yellow" class="trafficlight"></div>
<div id ="green" class="trafficlight"></div>
</div>

Related

Change line color depending on where it sits on different divs

I am trying to use jQuery to make my border line change color depending on where it sits on the divs. I set it position: absolute and it is laying on both divs. I was trying to make the line on the top div to be the color grey and the line on the bottom div to be white. I want to dynamically change the color depending on which section it is over.
https://codepen.io/asreenz/pen/MWpGMQO link to Codepen.
<div>
<div class="line">
</div>
<div class="top-box"></div>
<div class="bottom-box"></div>
</div>
.line{
width:0px;
height: 100px;
border: 1px solid black;
position:absolute;
left: 50%;
bottom: -225px;
transform: translate(-50%, -50%);
margin: 0 auto;
}
.top-box{
width:100vw;
height:500px;
background-color: pink;
}
.bottom-box{
width:100vw;
height:500px;
background-color: yellow;
}
.line-grey{
color:#8a96a3;
}
.line-white{
color:white;
}
var top1height = $(".top-box" ).height();
var bottom1height = $(".bottom-box" ).height();
var linePosition = $(this).offset();
if(linePosition > top1height){
$(".line").addClass(".line-grey");
} else {
$(".line").removeClass("line-grey");
}
if(linePosition > bottom1height){
$(".line").addClass(".line-white");
} else {
$(".line").removeClass("line-white");
}
You need to use an event listener to watch for when the page scrolls.
to keep the code DRY you can re-use a lot of the code and reduce the amount of javascript you have to write and maintain.
$(document).ready(function () {
const formatLine = function () {
var topBox = $(".top-box");
var bottomBox = $(".bottom-box");
var line = $(".line");
var positionFormatter = function (line, box, className) {
const lineTop = line.offset()['top'];
if (lineTop > box.offset()['top'] &&
lineTop < (box.offset()['top'] + box.height())){
line.addClass(className);
return true;
} else {
line.removeClass(className);
}
return false;
}
positionFormatter(line, topBox, "line-grey");
positionFormatter(line, bottomBox, "line-white");
};
formatLine();
$(document).scroll(formatLine);
});
.line{
width:0px;
height: 100px;
border: 1px solid black;
position:fixed;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
margin: 0 auto;
}
.top-box{
width:100vw;
height:500px;
background-color: pink;
}
.bottom-box{
width:100vw;
height:500px;
background-color: yellow;
}
.line-grey{
border-color:#8a96a3;
}
.line-white{
border-color:white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<div class="line">
</div>
<div class="top-box"></div>
<div class="bottom-box"></div>
</div>

Toggle change 2 DIV width at a time + localStorage

function myFunction() {
var element = document.getElementById("one1");
element.classList.toggle("one2");
var element = document.getElementById("two1");
element.classList.toggle("two2");
}
<style>
#section{margin-left:50px;
margin-right:50px
}
#monbouton{float:right;
font-size:25px;
width:50px;
height:50px;
background-color:#F1F1F1;
border:1px solid ##F1F1F1
}
#one1{
float:left;
width:40%;
height:100px;
border:1px solid blue
}
.one2{
width:10% !important;
height:200px;
border:1px solid red !important;
}
.one2 #afairedisparaitre{display:none
}
#two1{float:right;
width:59%;
height:100px;
border:1px solid green
}
.two2{width:89% !important
}
</style>
<!DOCTYPE html>
<html>
<body>
<div id="section">
<div id="one1">
<button id="monbouton" onclick="myFunction()">↔</button>
<div id="afairedisparaitre">This is DIV #one1<br />
Button toggle to CLASS .one2<br />
and reverse</div>
</div>
<div id="two1">This is DIV #two1<br />
Button toggle to CLASS .two2<br />
and reverse</div>
</div>
</body>
</html>
I am trying to make the leftside of my website shrink, so that the users can have a wider rightside if they find it more confortable.
What I am missing is a way that would keep the choice all over the site, when an other page is loaded, until the user clicks again. Maybe the solution would be a few more lines in js with "localStorage" ? I would really appreciate any help.
Made your CSS a bit better. Now we need to toggle only one class .with_toggle for #section.
It can sow errors here, in Snippet, but will fork fine on Codepan, see please. Try to switch it and reload the page on Codepan.
// checking if our storage is not empty
if (localStorage.toggled != '') {
// set class to #section form storage value
document.getElementById("section").classList.toggle(localStorage.toggled);
}
function myFunction() {
if (localStorage.toggled != "with_toggle") {
document.getElementById("section").classList.add("with_toggle");
localStorage.toggled = "with_toggle";
} else {
document.getElementById("section").classList.remove("with_toggle");
localStorage.toggled = "";
}
}
#section {
margin-left: 50px;
margin-right: 50px;
}
#monbouton {
float: right;
font-size: 25px;
width: 50px;
height: 50px;
background-color: #F1F1F1;
border: 1px solid #F1F1F1;
}
#one1 {
float: left;
width: 40%;
height: 100px;
border: 1px solid blue;
}
.with_toggle #one1 {
width: 10%;
border: 1px solid red;
}
.with_toggle #one1 #afairedisparaitre {
display: none;
}
#two1 {
float: right;
width: 59%;
height: 100px;
border: 1px solid green;
}
.with_toggle #two1 {
width: 89%;
}
<div id="section">
<div id="one1">
<button id="monbouton" onclick="myFunction()">↔</button>
<div id="afairedisparaitre">This is DIV #one1<br /> Button toggle to CLASS .one2<br /> and reverse</div>
</div>
<div id="two1">This is DIV #two1<br /> Button toggle to CLASS .two2<br /> and reverse</div>
</div>
Sure. Just create a localStorage variable that keeps track of whether the shrink should be active and use that to apply your styles on page load or something similar.
function shrinkActive() {
var shrink;
if (!(shrink = localStorage.getItem("shrink"))) {
localStorage.setItem("shrink", "false");
return false;
}
return JSON.parse(shrink);
}
function setShrink(active) {
var element1 = document.getElementById("one1");
var element2 = document.getElementById("two1");
if (active) {
element1.classList.add("one2");
element2.classList.add("two2");
} else {
element1.classList.remove("one2");
element2.classList.remove("two2");
}
localStorage.setItem("shrink", active.toString());
}
function myFunction() {
setShrink(!shrinkActive());
}
window.onload = function() {
setShrink(shrinkActive());
}
Link to working Codepen. https://codepen.io/bugcatcher9000/pen/pogZbrz?editors=1111

i want to make multiple mouseover functions with minimum codes

I have 10 links and each of them is different from the others.I want when user hovers on them background image of the div changes and a tooltip text be shown on top of the links with a fade-in animation .
i have tried to make several functions using JS and it works but it's a lot of code and mostly repetitive.I want a good shortcut through all of that useless coding.
document.getElementById("d1").onmouseover = function() {
mouseOver1()
};
document.getElementById("d2").onmouseover = function() {
mouseOver2()
};
document.getElementById("d3").onmouseover = function() {
mouseOver3()
};
document.getElementById("d1").onmouseout = function() {
mouseOut1()
};
document.getElementById("d2").onmouseout = function() {
mouseOut2()
};
document.getElementById("d3").onmouseout = function() {
mouseOut3()
};
function mouseOver1() {
document.getElementById("dogs").style.background = "blue";
document.getElementById("tooltiptext1").style.visibility = "visible";
}
function mouseOut1() {
document.getElementById("dogs").style.background = "black";
document.getElementById("tooltiptext1").style.visibility = "hidden";
}
function mouseOver2() {
document.getElementById("dogs").style.background = "green";
document.getElementById("tooltiptext2").style.visibility = "visible";
}
function mouseOut2() {
document.getElementById("dogs").style.background = "black";
document.getElementById("tooltiptext2").style.visibility = "hidden";
}
function mouseOver3() {
document.getElementById("dogs").style.background = "red";
document.getElementById("tooltiptext3").style.visibility = "visible";
}
function mouseOut3() {
document.getElementById("dogs").style.background = "black";
document.getElementById("tooltiptext3").style.visibility = "hidden";
}
#dogs {
float: right;
margin-top: 5%;
background: black;
width: 150px;
height: 150px;
}
#d-list {
color: white;
direction: ltr;
float: right;
width: 60%;
height: 60%;
}
#tooltiptext1,
#tooltiptext2,
#tooltiptext3 {
color: black;
background-color: gray;
width: 120px;
height: 30px;
border-radius: 6px;
text-align: center;
padding-top: 5px;
visibility: hidden;
}
<div id="animals">
<div id="dogs"></div>
<div id="d-list">
<pre style="font-size:22px; color:darkorange">dogs</pre><br />
<pre>white Husky</pre>
<p id="tooltiptext1">Tooltip text1</p>
<pre>black Bull</pre>
<p id="tooltiptext2">Tooltip text2</p>
<pre>brown Rex</pre>
<p id="tooltiptext3">Tooltip text3</p>
</div>
</div>
Please have in mind that all of links will change same outer div object and the idea is to change the background image of that div and the tooltip shoud appear on the top of the links....so,
any ideas?
edit: added animation requested.
CSS is almost always better done in script by using classes when multiple elements are being manipulated with similar functions so I used that here. Rather than put some complex set of logic in place I simply added data attributes for the colors - now it works for any new elements you wish to add as well.
I did find your markup to be somewhat strangely chosen and would have done it differently but that was not part of the question as stated.
I took the liberty of removing the style attribute from your dogs element and put it in the CSS also as it seemed to belong there and mixing markup and css will probably make it harder to maintain over time and puts all the style in one place.
Since you DID tag this with jQuery here is an example of that.
$(function() {
$('#d-list').on('mouseenter', 'a', function(event) {
$('#dogs').css('backgroundColor', $(this).data('colorin'));
$(this).parent().next('.tooltip').animate({
opacity: 1
});
}).on('mouseleave', 'a', function(event) {
$('#dogs').css('backgroundColor', $(this).data('colorout'));
$(this).parent().next('.tooltip').animate({
opacity: 0
});
});
});
#dogs {
float: right;
margin-top: 5%;
background: black;
width: 150px;
height: 150px;
}
#d-list {
color: white;
direction: ltr;
float: right;
width: 60%;
height: 60%;
}
.dog-header {
font-size: 22px;
color: darkorange;
margin-bottom: 2em;
}
.tooltip {
color: black;
background-color: gray;
width: 120px;
height: 30px;
border-radius: 6px;
text-align: center;
padding-top: 5px;
opacity: 0;
position:relative;
top:-4.5em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div id="animals">
<div id="dogs"></div>
<div id="d-list">
<pre class="dog-header">dogs</pre>
<pre>white Husky</pre>
<p id="tooltiptext1" class="tooltip">Tooltip text1</p>
<pre>black Bull</pre>
<p id="tooltiptext2" class="tooltip">Tooltip text2</p>
<pre>brown Rex</pre>
<p id="tooltiptext3" class="tooltip">Tooltip text3</p>
</div>
</div>
Updated
This answer was written before the question was edited to show the intended markup/styling and before all the details were included. The code has been updated to work with that structure.
I think the simplest thing is just to create a configuration object to detail the varying bits, and then use common code for the rest. Here's one approach:
const configs = [
['d1', 'tooltiptext1', 'blue'],
['d2', 'tooltiptext2', 'green'],
['d3', 'tooltiptext3', 'red'],
];
configs.forEach(([id, tt, color]) => {
const dogs = document.getElementById('dogs');
const el = document.getElementById(id);
const tip = document.getElementById(tt);
el.onmouseover = (evt) => {
dogs.style.background = color
tip.style.visibility = "visible";
}
el.onmouseout = (evt) => {
dogs.style.background = "black";
tip.style.visibility = "hidden";
}
})
#dogs{float:right;margin-top:5%;background:#000;width:150px;height:150px}#d-list{color:#fff;direction:ltr;float:right;width:60%;height:60%}#tooltiptext1,#tooltiptext2,#tooltiptext3{color:#000;background-color:gray;width:120px;height:30px;border-radius:6px;text-align:center;padding-top:5px;visibility:hidden}
<div id="animals"> <div id="dogs"></div><div id="d-list"> <pre style="font-size:22px; color:darkorange">dogs</pre><br/> <pre>white Husky</pre> <p id="tooltiptext1">Tooltip text1</p><pre>black Bull</pre> <p id="tooltiptext2">Tooltip text2</p><pre>brown Rex</pre> <p id="tooltiptext3">Tooltip text3</p></div></div>
Obviously you can extend this with new rows really easily. And if you want to add more varying properties, you can simply make the rows longer. If you need to add too many properties to each list, an array might become hard to read, and it might become better to switch to {id: 'demo', tt: 'dem', color: 'blue'} with the corresponding change to the parameters in the forEach callback. (That is, replacing configs.forEach(([id, tt, color]) => { with configs.forEach(({id, tt, color}) => {.) But with only three parameters, a short array seems cleaner.
Older code snippet based on my made-up markup.
const configs = [
['demo', 'dem', 'blue'],
['dd', 'dem1', 'green']
];
configs.forEach(([id1, id2, color]) => {
const a = document.getElementById(id1)
const b = document.getElementById(id2)
a.onmouseover = (evt) => {
a.style.background = color
b.style.visibility = "visible";
}
a.onmouseout = (evt) => {
a.style.background = "black";
b.style.visibility = "hidden";
}
})
div {width: 50px; height: 50px; float: left; margin: 10px; background: black; border: 1px solid #666; color: red; padding: 10px; text-align: center}
#dem , #dem1{visibility:hidden;}
<div id="demo">demo</div>
<div id="dem">dem</div>
<div id="dd">dd</div>
<div id="dem1">dem1</div>
my way of seeing that => zero Javascript:
div[data-info] {
display: inline-block;
margin:80px 20px 0 0;
border:1px solid red;
padding: 10px 20px;
position: relative;
}
div[data-bg=blue]:hover {
background-color: blue;
color: red;
}
div[data-bg=green]:hover {
background-color: green;
color: red;
}
div[data-info]:hover:after {
background: #333;
background: rgba(0, 0, 0, .8);
border-radius: 5px;
bottom: 46px;
color: #fff;
content: attr(data-info);
left: 20%;
padding: 5px 15px;
position: absolute;
z-index: 98;
min-width: 120px;
max-width: 220px;
}
div[data-info]:hover:before {
border: solid;
border-color: #333 transparent;
border-width: 6px 6px 0px 6px;
bottom: 40px;
content: "";
left: 50%;
position: absolute;
z-index: 99;
}
<div data-info="Tooltip for A Tooltip for A" data-bg="blue">with Tooltip CSS3 A</div>
<div data-info="Tooltip for B" data-bg="green" >with Tooltip CSS3 B</div>

jquery - Control CSS properties of elements according to CSS properties of other elements

How do I change CSS properties of elements according to CSS properties of other elements? For instance; I want to change the default position of "bigbutton" if the color of "div1" is black. This is what I've tried:
HTML
<div> <div class="div1"> </div> <div class="div2"></div> <div class="div3"></div> <button type="button" class="bigbutton">bigbutton </button> </div>
CSS
.div1{ position:fixed; left: 10px; width:100px; height: 100px; background-color: red; } .div2{ position:fixed; left: 10px; top: 110px; width:100px; height: 100px; background-color: green; } .div3{ position:fixed; left: 10px; top: 220px; width:100px; height: 100px; background-color: teal; .bigbutton{ position: fixed; left: 15px; width: 100px; height: 30px; background-color: blue; }
JQUERY
$(document).ready(function(){ $('.div1').mouseenter(function(){ $(this).css('background','black'); }); $('.div1').mouseleave(function(){ $(this).css('background',''); }); $('.div2').mouseenter(function(){ $('.div1').css('background','yellow'); }); $('.div2').mouseleave(function(){ $('.div1').css('background',''); }); $('.div3').mouseenter(function(){ $('.div1').css('background','black'); }); $('.div3').mouseleave(function(){ $('.div1').css('background',''); }); if($('.div').css('background') == 'black'){ $('.bigbutton').css('left','200px'); } else{ $('.bigbutton').css('left','100px'); } });
Is it possible to do it without if-else?
PS:I apologise for the formating problem, as it's nearly impossible to properly format with my phone.Thank you.
When you say "change x according to y", you're basically describing an if conditional.
Given your example, you can also get the desired result by changing the button's position in the same code block where the div1 becomes black: https://codepen.io/pen/RvXQMP
Update
To get the desired result for any input that would change the color of div1, you can use Mutation observer, works like an eventListener for DOM changes: https://codepen.io/pen/PVMVzw
first of all you need to get the color of the bigbutton
var color = $('.bigbutton').css('color');
then do your check
if(color == "red"){ //example
$('.div1').css('top':'10px') // finally do your changes [for example]
}
you can try it, html code:
<div id="container">
<div class="div1"> </div>
<div class="div2"></div>
<div class="div3"></div>
<button type="button" class="bigbutton">bigbutton </button>
</div>
css code:
.div1{ position:fixed; left: 10px; width:100px; height: 100px; background-color: red; }
.div2{ position:fixed; left: 10px; top: 110px; width:100px; height: 100px; background-color: green; }
.div3{ position:fixed; left: 10px; top: 220px; width:100px; height: 100px; background-color: teal;}
.bigbutton{ position: fixed; left: 15px; width: 100px; height: 30px; background-color: blue; }
javascript code:
container.onmouseover = container.onmouseout = handler;
function handler(event){
if (event.type == 'mouseover') {
if(event.target.className=='div1'){
event.target.style.background = 'black';
moveLeft();
}
if(event.target.className=='div2'){
document.getElementsByClassName('div1')[0].style.background = 'yellow';
}
if(event.target.className=='div3'){
document.getElementsByClassName('div1')[0].style.background = 'black';
moveLeft();
}
}
if (event.type == 'mouseout') {
if(event.target.className=='div1'){
event.target.style.background = '';
}
if(event.target.className=='div2'){
document.getElementsByClassName('div1')[0].style.background = '';
}
if(event.target.className=='div3'){
document.getElementsByClassName('div1')[0].style.background = '';
}
moveRight();
}
}
function moveLeft(){
$('.bigbutton').css('left','200px');
}
function moveRight(){
$('.bigbutton').css('left','100px');
}

Focus textarea using css

I'm searching one javascript or html or css code that make change background color when i click in textarea i need something like this http://prntscr.com/bzsqgq
I tried with javascript but i can't do that its to hard, i tried onclick change background color with rgba something like blur.
$('.comment .body').on('click', function() {
if($(this).hasClass('changing')) {
$('.comment textarea').blur();
}else {
$('.comment textarea').focus();
}
});
$('.comment textarea').on('focus',function() {
$('.comment .body').addClass('changing').style('background-color: #FF0000;');
});
$('.change-stamp textarea').on('blur',function() {
$('.comment .body').removeClass('changing').text('background-color: transparent;');
});
Thanks who can help me.
Add a wrapper and an inner element like this
.wrapper {
display: inline-block;
position: relative;
padding: 20px;
}
input:focus ~ .inner,
textarea:focus ~ .inner {
position: absolute;
z-index: -1;
left: 0; top: 0;
width: 100%; height: 100%;
background: yellow;
border: 2px solid red;
box-sizing: border-box;
}
<div class="wrapper">
<input type="text">
<br/>
<br/>
<textarea></textarea>
<div class="inner"></div>
</div>
var element = document.getElementsByClassName("chg_parent_on_focus")[0]
var parent = element.parentElement
element.onfocus = function(){
parent.className = "cont active";
}
element.onblur = function(){
parent.className = "cont";
}
.cont{
width:200px;
background:red;
padding:100px;
}
input{
margin:10px;
}
.cont.active{
background:black;
}
<div class="cont">
<input class="chg_parent_on_focus"/>
</div>

Categories