jQuery not updating variable info - javascript

There are two divs with class of .egg. The user is supposed to click on the div they want to change the background color of and then click the color for the div's new background. Two steps total. I've written a jQuery function to capture the id of the div chosen for the background change and then the id for the color to change to background. Works great, except that when the new div is selected, to change the background color, the previously selected div id is still stored in the variable called clickedId.
To try to fix this problem, I have set clickedId = ''; after the background has been changed for the selected div. However when a new div is selected, it doesn't work anymore. The console says Cannot read property 'style' of null. It looks like the first part of the code, $(".egg").click(function() {... isn't be executed for new div selections.
Does anyone have any suggestions or advice for this? Thanks in advance!
jQuery Code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
//Select the div to change the background color
$(".egg").click(function() {
var clickedId = $(this).attr("id");
//Updating the background color for selected div
$(".color").click(function() {
var clickedColor = $(this).attr("id");
if(clickedColor == 'red'){
document.getElementById(clickedId).style.backgroundColor = "red";
clickedId = '';
return;
}else if(clickedColor == 'blue'){
document.getElementById(clickedId).style.backgroundColor = "blue";
clickedId = '';
return;
}else if (clickedColor == 'yellow') {
document.getElementById(clickedId).style.backgroundColor = "yellow";
clickedId = '';
return;
}else{
document.getElementById(clickedId).style.backgroundColor = "white";
clickedId = '';
return;
}
});
});
});
</script>
HTML Code:
<body>
<div id="egg-main">
<div id="left-egg"></div>
<div id="center-egg1" class="egg" onclick="semi_left()"></div>
<div id="center-egg2" class="egg" onclick="semi_right()"></div>
<div id="right-egg"></div>
<div id="bottom">
<div id="red" class="color"></div>
<div id="blue" class="color"></div>
<div id="yellow" class="color"></div>
<div id="white" class="color"></div>
</div>
</div>
<script src="demo.js"></script>
</body>

Why it's not working
It looks like the problem is that the event listener for .color is declared inside the event listener for .egg. This means that every time you click .egg a new event handler is being created for .color.
The second time you click on a .color it is still running the event from the first time you clicked it. And, since you have changed the id to '', a getElementById('') is indeed null.
Possible Solution
Move the .color event listener outside the .egg event listener. You'll also have to change the scope of the clickedID variable.
$(document).ready(function(){
var clickedId = '';
//Select the div to change the background color
$(".egg").click(function() {
clickedId = $(this).attr("id");
alert(clickedId);
});
//Updating the background color for selected div
$(".color").click(function() {
var clickedColor = $(this).attr("id");
if(clickedId != '') document.getElementById(clickedId).style.backgroundColor = clickedColor;
});
});

Related

Is it possible to store an entire element into a localstorage or else?

I know that i ask the most silliest, but since i'm not familiar and i'm totally a beginner in localstorage i want to see the mechanic of the code how it is working as it should be else . I have created a div box and also two buttons , i want to be able to change the color of that box and store it in a localstorage , so that after refreshing i want end up with the background color of my stylesheet which is Red. So meaning when i change to Blue color after refshing the page to remain that color . Like i sad im pretty much new to localstorage and their use. Anyway thank you for the help that you can give me , i know its again a silly question but im very intresed to that. My javascript code is below as you can see:
var red=document.getElementById("red");
var blue=document.getElementById("blue");
var redColor='red';
var blueColor='blue';
localStorage.setItem('RColor',redColor);
localStorage.setItem('BColor',blueColor);
red.onclick=function red(){
document.getElementById("box").style.backgroundColor=localStorage.getItem('RColor');
};
blue.onclick=function blue(){
document.getElementById("box").style.backgroundColor=localStorage.getItem('BColor');
} ;
Check my comments below. This is one sample usage.
var redColor = 'red';
var blueColor = 'blue';
// When opening, read the Color value from localStorage. If it not set, then use the default color (say red)
document.getElementById("box").style.backgroundColor = localStorage.getItem('Color') || redColor;
var red = document.getElementById("red");
var blue = document.getElementById("blue");
red.onclick = function red() {
// Once user click on red button, Change the box background and update localStorage with Color
localStorage.setItem('Color', redColor);
document.getElementById("box").style.backgroundColor = redColor;
};
blue.onclick = function blue() {
// Once user click on blue button, Change the box background and update localStorage with Color
localStorage.setItem('Color', blueColor);
document.getElementById("box").style.backgroundColor = blueColor;
};
You don't need separate items (RColor and BColor) for the two colors in your localStorage.
Just add a common item called say, boxColor to your localStorage then just toggle its value based on which button is clicked. Now just create a function say, getColor that sets the color of your div based on the boxColor item and run that function when the page loads as well as when any of the two buttons are clicked.
Check the following Code Snippet for a practical example of the above approach.
However, running the following code snippet won't work because StackOverflow doesn't allow you to use localStorage in their code sandbox so you can check this JSFiddle instead to see it in action.
var red = document.getElementById("red");
var blue = document.getElementById("blue");
var box = document.getElementById("box");
var redColor='red';
var blueColor='blue';
function getColor(){
box.style.backgroundColor=localStorage.getItem('boxColor');
}
red.onclick=function red(){
localStorage.setItem('boxColor', redColor);
getColor();
};
blue.onclick=function blue(){
localStorage.setItem('boxColor', blueColor);
getColor();
};
getColor();
#box {
width: 200px;
height: 200px;
margin: 0 auto;
padding: 0;
}
<button id="red">Red</button>
<button id="blue">Blue</button>
<div id="box"></div>
Alternatively, if you don't want to repeat yourself with every colour, just place the colour on the button using a data attribute.
So something like:
// your default color
var defaultColor = "red";
// grab all buttons
var buttons = document.querySelectorAll(".set-color");
// loop over them
for (const button of buttons) {
// apply the btn style (optional)
button.style.color = button.dataset.text || "unset";
button.style.backgroundColor = button.dataset.bg || "unset";
button.style.border = 0;
// attach a click event to the button
button.addEventListener("click", function(e) {
// set element bg color and assign in to localstorage
document.getElementById(
"box"
).style.backgroundColor = localStorage.color = this.dataset.bg;
});
}
// setup the initial state
document.getElementById("box").style.backgroundColor =
localStorage.color || defaultColor;
#box {
display: block;
width: 50px;
height: 50px;
}
<div id="box"></div>
<button class="set-color" data-bg="red" data-text="black">red</button>
<button class="set-color" data-bg="blue" data-text="white">blue</button>
<button class="set-color" data-bg="#000000" data-text="white">#000000</button>
<button class="set-color" data-bg="#ff55aa">#ff55aa</button>

How to show/hide content

I have a page where I would like two buttons which when one is clicked, displays hello, and when the other one is clicked would hide the "hello" message and then display "goodbye". I know this needs to be done in javascript but I am not good with javascript.
Check this snippet
<p id="msg"></p>
<button onclick="helloFunction()">Say Hello</button>
<button onclick="byeFunction()">Wave Goodbye</button>
<script>
function helloFunction() {
document.getElementById("msg").innerHTML = "Hello";
}
function byeFunction() {
document.getElementById("msg").innerHTML = "Goodbye";
}
</script>
There are a couple of ways to do it, one of which would be affecting the visiblity of dom elements which say hello or goodbye, the other method as illustrated below you would actually change the text of a dom object based on which button is pressed
<button onClick="javascript:say('Hello');">Say Hi</button>
<button onClick="javascript:say('Goodbye');">Say Goodbye</button>
<div id="TextField"></div>
<script>
function say(text) {
var element = document.getElementById("TextField");
element.innerHTML = text;
}
</script>
here what you'll need to achieve such a feat.
first create a div or a p tag to hold ur text and two buttons
eg
<div id="container">Hello</div>
<button id="show">Show</button>
<button id="hide">Show</button>
make sure your div has an id and you buttons too. You use that for reference.
then in your javascript, you can either toggle the display or visibility of the div
<script type="text/javascript">
//Declare variable
var div = document.getElementById("container");
var show = document.getElementById("show");
var hide = document.getElementById("hide");
//run when windows fully loads
window.onload = function(){
//when i click show button
show.onclick = function(){
div.style.display = "block";
}
//when i click hide button
hide.onclick = function(){
div.style.display = "none";
}
}
//That is champ, this is all vanilla javascript. You can also look into implementing with jquery.
</script>

Changing Text in div without toggling Div Visiblity

In my Div (Code Below) there is an onClick function that triggers the visibility of a second div, and there is also a content edible in the div as well. When I click to change the text it also triggers the visibility of the second div. How would I change the code so that I can click the text without changing the second div's visibility?
<div class="div1" id ="div1" onclick="onStepClicked()" style ="text-align:center"><p contenteditable="true" >Step 1</p></div>
Function:
function onStepClicked() {
var elem = document.getElementById('div2');
if (Visible === true) {
elem.style.display = 'none';
Visible = false;
}
else {
if (Visible === false) {
elem.style.display = 'block';
Visible = true;
}
}
}
You may trigger the click on the Parent div only and exclude the click on child in jQuery like this:
$("#div1").click(function(){
$("#div2").css('visibility','hidden');
}).children().click(function(e) {
return false;
});
If you are not OK with jQuery and are after a JavaScript - only solution, please leave a comment and let me know.
UPDATE
If you are after a JavaScript solution, here U R:
HTML
<div id ="div1" onclick="onStepClicked()" >
<p id="editable" contenteditable="true">Step 1</p>
</div>
JS
function onStepClicked(){
document.getElementById('div1').onclick = function(e) {
if(e.target != document.getElementById('editable')) {
document.getElementById('div2').style.visibility = 'hidden';
}
}
}
Try using the element>element selector in your script. It will only affect the first child element and then stop from affecting sub-child elements.
Tutorial:
(http://www.w3schools.com/cssref/sel_element_gt.asp)

Change the text in a div when a function is executed

I have a javascript function, used to increase and decrease the height of div.
This is the code
function chk()
{
var node = document.getElementById('content');
node.classList.toggle('expand');
}
Works with this HTML code:
<div id="hite">
<div id = "content">
This is dummy text.
</div>
<div id="button" onclick="chk()">
click to read
</div>
</div>
I want the text to change in button div, once user click on it, and when again click on it, text should be again 'click to read'.
Try add this:
document.getElementById('button').innerHTML = node.classList.contains('expand')? 'hide':'click to read';
http://jsfiddle.net/rooseve/Bup8u/
You can use innerHTML property.
var ele = document.getElementById('button');
if (ele.innerHTML == "click to read")
ele.innerHTML = "User click on it!";
else
ele.innerHTML = "click to read";
you can also use "textContent" if you want to add only text and not html data.
if(document.getElementById("button").textContent!='click to read'){
document.getElementById("button").textContent="your content";
}else{
document.getElementById("button").textContent="click to read";
}

FAQ dropdown- Text color changed when clicked

I am using a JavaScript dropdown for my FAQ, and what I can't figure out is how to have the color of the question change when clicked, and then change back when clicked again.
Here's the JavaScript:
<script type="text/javascript">
function toggle(Info) {
var CState = document.getElementById(Info);
CState.style.display = (CState.style.display != 'block')
? 'block' : 'none';}
</script>
I know using :action will work just for when the question is clicked, but I'm trying to style it so that each click either turns the color on or off, as that's what happens with the answer dropping down and I'd like both to be coordinated.
If I understand correctly you toggle function shows/hides the answer. Then all you have to do is to get the question container and toggle a css class which contains the text color
For example:
document.getElementById(your question).classList.toggle(your-class);
and in a css file
.your-class {
color: selected color;
}
<style>
.classStyle1 {background-color:white}
.classStyle2 {background-color:green}
</style>
<script type="text/javascript">
function toggle(Info) {
var CState = document.getElementById(Info);
if(CStage.className == "classStyle1"){
CStage.className = classStyle2;
}else{
CStage.className = classStyle1;
}
// or else
// create style attribute for select element and put style='background-color:white' like this
if(CStage.style.backgroundColor == "white"){
CStage.style.backgroundColor = 'green';
}else{
CStage.style.backgroundColor = 'white';
}
</script>
If I understand correctly - try this
CState=document.getElementById("myColor");
CState.onmouseover=function(){this.style.color='red';};
CState.onmouseout=function(){this.style.color='blue';};

Categories

Resources