How can I use a boolean to toggle an images visibility? - javascript

I'm trying to use a single button to toggle between an image being visible and invisible. I want the first click to make the image appear, and the second to hide it again. I figured using a boolean would be the best way to do this, but I can't quite get it to work.
function myStats(){
counter = true;
if(counter == true){
document.getElementById('stat').style.display = 'block';
}
if(counter == false){
document.getElementById('stat').style.display = 'none';
}
}
<!DOCTYPE html>
<html>
<head>
<style>
body{background-color: #A9A9A9;}
</style>
</head>
<body>
<p> Dallas Fuel </p>
<center><img id="stat" src="Images/buttonLA.png" style="display:none;"/></center>
<button onclick="myStats()">Player 1</button>
<h3 id="var"></h3>
</body>
</html>
I realize this will obviously not work because I'm not toggling the boolean, but that's what I'm looking for help with.

Create a css class called hidden, then use classList.toggle(). When the button is clicked toggle the class on the image.
It can be done like this:
document.querySelector('button').addEventListener('click', myStats)
function myStats() {
document.getElementById('stat').classList.toggle('hidden')
}
.hidden { display: none; }
<center><button>Player 1</button></center>
<center><img id="stat" src="https://via.placeholder.com/150" class="hidden"></center>

I edited your snippet to put a toggle on there and made it so the function myStats() doesn't set counter = true everytime you click it. Seems to work fine. I also hoisted the declaration of the counter variable above that function declaration, since that's where your toggle should be, represented by counter = !counter.
let counter = true;
function myStats(){
counter = !counter;
if(counter == true){
document.getElementById('stat').style.display = 'block';
}
if(counter == false){
document.getElementById('stat').style.display = 'none';
}
}
<!DOCTYPE html>
<html>
<head>
<style>
body{background-color: #A9A9A9;}
</style>
</head>
<body>
<p> Dallas Fuel </p>
<center><img id="stat" src="Images/buttonLA.png" style="display:none;"/></center>
<button onclick="myStats()">Player 1</button>
<h3 id="var"></h3>
</body>
</html>

Boolean variable should be outside of the function so its value won't reset every time you called a function. Also you should toggle this boolean variable value from true to false and vise versa. Check out my solution. Hope this helps!
var isImageShouldBeVisible = true;
function toggleImageVisibility() {
isImageShouldBeVisible = !isImageShouldBeVisible;
if (isImageShouldBeVisible) {
document.getElementById('stat').style.display = 'block';
} else {
document.getElementById('stat').style.display = 'none';
}
}
<!DOCTYPE html>
<html>
<head>
<style>
body{background-color: #A9A9A9;}
</style>
</head>
<body>
<p> Dallas Fuel </p>
<center><img id="stat" src="Images/buttonLA.png" style="display:block;"/></center>
<button onclick="toggleImageVisibility()">Player 1</button>
<h3 id="var"></h3>
</body>
</html>

This is because counter remains same throughout the code. You need to add counter = !counter at end of you function. I would do it using ternary operators. There is need of Boolean just check the style.display
let elm = document.getElementById('stat');
function myStats(){
let {display} = elm.style;
elm.style.display = display === 'none' ? 'block' : 'none';
}
body{background-color: #A9A9A9;}
<p> Dallas Fuel </p>
<center><img id="stat" src="Images/buttonLA.png" style="display:none;"/></center>
<button onclick="myStats()">Player 1</button>
<h3 id="var"></h3>

Related

Make id ex disappear if you click anywhere outside of it

I'm trying to figure out how I can make a targeted element disappear. If you click any where that is outside of that element. I have created a toggle effect with a button but I want to also hide id ex if there is any clicks outside of ex. I have
found working sources on this subject but it's based on jQuery most of the time. I have nothing against jQuery I just need to do this in pure JS structure for
personal reasons.
<!DOCTYPE html>
<html>
<head>
<style>
#ex{
display: none;
}
</style>
<script>
document.addEventListener('DOMContentLoaded',function(){
var b= document.getElementsByTagName('button')[0];
b.addEventListener('click',fx);
function fx() {
var x = document.getElementById("ex");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
});
</script>
</head>
<body>
<button>Toggle</button>
<h1 id="ex">Blablablablabla bla bla JS</h1>
</body>
</html>
UPDATE
Any time I tried to ask this question on this topic on many sites nobody never understand what I mean. In other words I don't want the body to do any toggling just the button the best way I can explain this is like this you know how in some applications if you click on a drop down menu and you click out side of that drop down menu then it disappears but you can use the navigation bar button to bring it back? That's what i'm trying to do .
I want something like this but in pure JS structure.
<style>
#ex{
display: none;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#ex').click(function(execute){
execute.stopPropagation();
});
$('button').click(function(execute) {
execute.preventDefault();
execute.stopPropagation();
$('#ex').toggle();
});
$(document).click(function() {
$('#ex').hide();
});
});
</script>
<button>Toggle</button>
<h1 id='ex'>Blablablablabla bla bla JS</h1>
<!DOCTYPE html>
<html>
<head>
<style>
#ex{
display: none;
}
</style>
<script>
document.addEventListener("click", function(obj){
var x = document.getElementById("ex");
if(obj.target.id != "ex") {
if (x.style.display === "block") {
x.style.display = "none";
} else if(obj.target.id == "btn") {
x.style.display = "block";
}
}
});
</script>
</head>
<body>
<button id="btn">Toggle</button>
<h1 id="ex">Blablablablabla bla bla JS</h1>
</body>
</html>
Update
You can save the button id and compare it with the clicked element id.
var b= document.getElementsByTagName('button')[0];
var btnId = b.getAttribute('id');
document.addEventListener('click',fx);
function fx(e) {
var x = document.getElementById("ex");
if (e.target.getAttribute('id') == btnId) {
if(x.style.display == "block")
x.style.display = "none";
else
x.style.display = "block";
}
else{ // we did not click on button
if (e.target.getAttribute('id') != 'ex')
x.style.display = 'none';
}
}

how to avoid rewriting java script code?

I am looking for a way to avoid rewriting the same code again and again.
I am making a web page that has divs with hide and show option, with the help of a button you toggle between hide and show. I found an easy way to achieve the effect with this code:
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>
This works perfectly but gets a bit tedious when you have a dozen or more divs with said effect. Is there a way to avoid having to rewrite the function for each and every div?
Thank you! :)
Easy, parameterize the id:
function myFunction(divId) {
var x = document.getElementById(divId);
and in the HTML pass the id to the function:
<button onclick="myFunction('myDIV')">Try it</button>
<div id="myDIV"> ...</div>
<button onclick="myFunction('myOtherDIV')">Try it</button>
<div id="myOtherDIV"> ...</div>
... and so on ...
You can keep one single function and handle as many divs as you want.
You could run the javascript function with a parameter. So you only have one function and then you only need to change the parameter name. See the example below.
function myFunction(div) {
var x = document.getElementById(div);
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<body>
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
<button onclick="myFunction('myDIV')">Try it</button>
<button onclick="myFunction('myDIV2')">Try it2</button>
<div id="myDIV">
This is my DIV element.
</div>
<div id="myDIV2">
This is my DIV2 element.
</div>
<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>
</body>
Just pass the div id to a function
function toggleDiv(divId) {
var x = document.getElementById(divId);
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
This works perfectly but gets a bit tedious when you have a dozen or
more divs with said effect
Create an array of such div ids to be toggled and iterate the same, for example
var divIds = ["myDIV1", "myDIV2", "myDIV3"];
divIds.forEach( s => toggleDiv(s) );
Pass a parameter into the function.
function myFunction(divName) {
var x = document.getElementById(divName);
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<body>
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
<button onclick="myFunction('myDIV')">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
<button onclick="myFunction('myDIV2')">Try it</button>
<div id="myDIV2">
This is my DIV2 element.
</div>
<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>
</body>
using event target and operating relatively on elements, can do the task.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
<hr>
<div class="wrapper">
<button onclick="myFunction(event)">Try first</button>
<div class="content">
This is my DIV element.
</div>
</div>
<hr>
<div class="wrapper">
<button onclick="myFunction(event)">Try second</button>
<div class="content">
This is my DIV element.
</div>
</div>
<hr>
<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>
<script>
function myFunction(event) {
var wrapper = event.target.parentElement;
var content = wrapper.querySelector('.content');
if (content.style.display === "none") {
content.style.display = "block";
} else {
content.style.display = "none";
}
}
</script>
</body>
</html>
function myFunction() {
var x = document.getElementsByClassName("myDIV");
for (let i = 0; i < x.length; i++){
x[i].style.display = x[i].style.display == "none" ? "block" : "none";
}
}
<body>
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
<button onclick="myFunction()">Try it</button>
<div class="myDIV">
This is my DIV element.
</div>
<div class="myDIV">
This is my DIV element.
</div>
<div class="myDIV">
This is my DIV element.
</div>
<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>
</body>
function toggleVisibility(selector) {
const elements = document.querySelectorAll(selector);
elements.forEach( element => {
const isVisible = element.offsetHeight;
if (isVisible) {
element.setAttribute('hidden', '');
} else {
element.removeAttribute('hidden');
}
});
}
<button onclick="toggleVisibility('#myDIV')">Try it</button>
<button onclick="toggleVisibility('.toggle')">Try it with className</button>
<div id="myDIV">
This is my DIV element.
</div>
<div class="toggle">
This is my DIV element.
</div>
<div class="toggle">
This is my DIV element.
</div>

how do I use the same link to "re-hide" previously hidden text via Javascript?

The below code snippet shows the invite code when I click "Invite Code". But how do I re-hide the invite code if the same link is clicked again? And can it be done where it cycles back and forth with subsequent clicks? I didn't write this code but merely modified it to my use. I am still very new to this type of thing. Thanks!
<style>
div.hide { display:none; }
div.show { text-align:center; }
</style>
<script type='text/javascript'>
function showText(show, hide) {
document.getElementById(show).className = "show";
document.getElementById(hide).className = "hide";
}
</script>
<br>
<font color="red">-</font>Home<font color="red"> / </font><a onclick="showText('text1')" href="javascript:void(0);">Invite Code</a>-</font>
<div id="text1" class="hide"><font color="red">abc123</font></div>
</center></h3>
Simply use this function:
function showText(id)
{
var elem = document.getElementById(id);
if(elem.style.display == 'none')
{
elem.style.display = 'inline';
}
else
{
elem.style.display = 'none';
}
}
<a onClick="showText('text1');" href="#">Show or Hide</a><br/>
<div style="height: 30px;"><div id="text1" style="display: none;">Text to hide or show... WTF?!</div></div>
<div>This text should not move.</div>
PS: This also works for 2 Elements...
Greetings
I really don't see the use for the show class. You could just toggle the hide class on the elements that you want to toggle.
Assume you dont need the show class, then use the classList.toggle function like this
function toggle(target){
document.getElementById(target).classList.toggle('hide');
}
.hide{ display:none }
<button onclick="toggle('test')">Show / Hide</button>
<div id="test" class="hide">Hello world!</div>
save the state with a boolean
var hided = true;
function showText(show,hide){
if (hided){
document.getElementById(show).className = "show";
document.getElementById(hide).className = "hide";
}
else{
document.getElementById(show).className = "hide";
document.getElementById(hide).className = "show";
}
hided = !hided;
}
fiddle with this code and some of your html : fiddle,
isn't it the expected behavior ?
<html>
<div ID="content" style="display:block;">This is content.</div>
<script type="text/javascript">
function toggleContent() {
// Get the DOM reference
var contentId = document.getElementById("content");
// Toggle
contentId.style.display == "block" ? contentId.style.display = "none" :
contentId.style.display = "block";
}
</script>
<button onclick="toggleContent()">Toggle</button>
</html>
//Code is pretty self explanatory.

Updating innerHTML in javascript but erasing past innerHTML

Using Javascript, I want to toggle on and off between 2 images.
So far I am using a counter and then changing my innerHTML based off if the counter is even or odd for when the image is clicked
It works the first time i click the image by replacing the image already there, but after the first time it keeps on adding images instead.
How can i make it change the image after the second time rather than add images when I click?
<!DOCTYPE html>
<html>
<head>
<script>
var x = 0;
function myFunction() {
x++;
var div1 = document.getElementById('div1');
if (x % 2 != 0) {
var y = document.write('<img src="http://www.computric.com/wp-content/uploads/2011/09/119709197585381818TzeenieWheenie_Power_On_Off_Switch_red_2.svg_.med_.ng" alt="sometext" onclick=myFunction()>');
div1.appendChild.innerHtml = y;
} else if (x % 2 == 0) {
var y = document.write('<img src="http://0.tqn.com/d/pcsupport/1/0/Y/A/-/-/on.jpg" alt="some_text" onclick=myFunction()>')
div1.appendChild.innerHTML = y;
}
}
</script>
</head>
<body>
<div id="div1" style="font-size:12px" onclick=myFunction()> <span onclick=myFunction()>
<img src="http://0.tqn.com/d/pcsupport/1/0/Y/A/-/-/on.jpg" alt="some_text">
</span>
</div>
</body>
</html>
If you are only trying to achieve the toggle effect something like this should work:
<!DOCTYPE html>
<html>
<head>
<script>
var x=0;
function myFunction(){
var div1=document.getElementById('div1');
if(x==0){
x=1;
document.getElementById("myimgid").src = "http://www.computric.com/wp-content/uploads/2011/09/119709197585381818TzeenieWheenie_Power_On_Off_Switch_red_2.svg_.med_.ng";
}
else{
x=0;
document.getElementById("myimgid").src = "http://0.tqn.com/d/pcsupport/1/0/Y/A/-/-/on.jpg";
}
}
</script>
</head>
<body>
<div id="div1" style="font-size:12px" onclick=myFunction()>
<span>
<img id="myimgid" src="http://0.tqn.com/d/pcsupport/1/0/Y/A/-/-/on.jpg" alt="some_text">
</span>
</div>
</body>
</html>

Use link click to clear input field Javascript

I am trying to use a link to clear a text input field. I am hiding and showing a memo field and and if the user puts text in the field and clicks "remove memo" link I want to text field to clear on click.
<html>
<head>
<script language="JavaScript">
function toggle(id) {
var state = document.getElementById(id).style.display;
if (state == 'block') {
document.getElementById(id).style.display = 'none';
} else {
document.getElementById(id).style.display = 'block';
}
}
oldTextAry = new Array();
function changeText (fieldObj, newTexStr) {
if (newTexStr == fieldObj.innerHTML) {
fieldObj.innerHTML = oldTextAry[fieldObj.id];
} else {
oldTextAry[fieldObj.id] = fieldObj.innerHTML;
fieldObj.innerHTML = newTexStr;
}
}
</script>
<style type="text/css">
<!--
#hidden1 {display: none;}
-->
</style>
</head>
<body>
<a href="###" onclick="toggle('hidden1'); changeText(this,'Remove Memo');" class="memo" >Add Memo</a>
</div>
<div id="hidden1"><div class="memo">Memo: <input type="text" id="ctlWorkflow_ctlMemo381" size="45" maxlength="32" name="ctlWorkflow:ctlMemo381"></div> </div>
</body>
</html>
I am stuck and cannot get the field to clear.
Use the below code in the click delegate. Sorry for the mistaken answer.
document.getElementById("ctlWorkflow_ctlMemo381").value = '';
Cheers

Categories